',
- '#states' => [
- // 'visible' => [
- // [
- // [
- // ':input[name="lab_actions"]' => ['value' => 3],
- // ],
- // 'or',
- // [
- // ':input[name="lab_experiment_actions"]' => ['value' => 3],
- // ],
- // 'or',
- // [
- // ':input[name="lab_experiment_solution_actions"]' => ['value' => 3],
- // ],
- // 'or',
- // [
- // ':input[name="lab_actions"]' => ['value' => 4],
- // ],
- // ],
- // ],
- 'required' => [
- [
- [
- ':input[name="lab_actions"]' => ['value' => 3],
- ],
- 'or',
- [
- ':input[name="lab_experiment_actions"]' => ['value' => 3],
+ ];
+
+ $form['download_solution_wrapper'] = [
+ '#type' => 'container',
+ '#attributes' => ['id' => 'ajax_download_solution_file'],
+ ];
+
+ $form['download_solution_wrapper']['download_solution'] = [
+ '#type' => 'item',
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Download Solution'),
+ Url::fromUri('internal:/lab-migration/download/solution/' . $form_state->getValue('solution_list'))
+ )->toString(),
+ ];
+
+ $form['download_solution_wrapper']['lab_experiment_solution_actions'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Please select action for solution'),
+ '#options' => $this->_bulk_list_solution_actions(),
+ '#default_value' => 0,
+ '#prefix' => '
',
+ '#states' => [
+ 'invisible' => [
+ ':input[name="lab"]' => ['value' => 0],
],
- 'or',
- [
- ':input[name="lab_experiment_solution_actions"]' => ['value' => 3],
+ ],
+ ];
+
+ $form['download_solution'] = [
+ '#type' => 'item',
+ '#markup' => '
',
+ ];
+
+ $form['edit_solution'] = [
+ '#type' => 'item',
+ '#markup' => '
',
+ ];
+
+ $form['solution_files'] = [
+ '#type' => 'item',
+ '#markup' => '
',
+ '#states' => [
+ 'invisible' => [
+ ':input[name="lab"]' => ['value' => 0],
],
- 'or',
- [
- ':input[name="lab_actions"]' => ['value' => 4],
+ ],
+ ];
+
+ $form['message'] = [
+ '#type' => 'textarea',
+ '#title' => $this->t('If Dis-Approved, please specify reason for Dis-Approval'),
+ '#prefix' => '
',
+ '#states' => [
+ 'required' => [
+ [
+ [':input[name="lab_actions"]' => ['value' => 3]],
+ 'or',
+ [':input[name="lab_experiment_actions"]' => ['value' => 3]],
+ 'or',
+ [':input[name="lab_experiment_solution_actions"]' => ['value' => 3]],
+ 'or',
+ [':input[name="lab_actions"]' => ['value' => 4]],
+ ],
],
],
- ],
- ],
-];
-//List of solution file
-$query = \Drupal::database()->select('lab_migration_solution_files', 's');
- $query->fields('s');
- $query->condition('solution_id', $form_state->getValue('solution_list'));
- $solution_list_q = $query->execute();
- if ($solution_list_q) {
- $solution_files_rows = [];
- while ($solution_list_data = $solution_list_q->fetchObject()) {
-
-//var_dump($solution_list_data);die;
- $solution_file_type = '';
- switch ($solution_list_data->filetype) {
- case 'S':
- $solution_file_type = 'Source or Main file';
- break;
- case 'R':
- $solution_file_type = 'Result file';
- break;
- case 'X':
- $solution_file_type = 'xcos file';
- break;
- default:
- $solution_file_type = 'Unknown';
- break;
- }
-
- // Create file download link
- $items = [
-
- Link::fromTextAndUrl($solution_list_data->filename, Url::fromUri('internal:/lab-migration/download/file/' . $solution_list_data->id))->toString(),
- "{$solution_file_type}"
- ];
+ ];
+
+ $solution_files_rows = [];
+ $solution_list_q = $this->database->select('lab_migration_solution_files', 's')
+ ->fields('s')
+ ->condition('solution_id', $form_state->getValue('solution_list'))
+ ->execute();
+
+ while ($solution_list_data = $solution_list_q->fetchObject()) {
+ $solution_file_type = '';
+ switch ($solution_list_data->filetype) {
+ case 'S':
+ $solution_file_type = $this->t('Source or Main file');
+ break;
+ case 'R':
+ $solution_file_type = $this->t('Result file');
+ break;
+ case 'X':
+ $solution_file_type = $this->t('xcos file');
+ break;
+ default:
+ $solution_file_type = $this->t('Unknown');
+ break;
}
- }
- array_push($solution_files_rows, $items);
- //var_dump($solution_rows);die;
- $form['download_solution_wrapper']['solution_files'] = [
- '#type' => 'fieldset',
- '#title' => t('List of solution files'),
+
+ $solution_files_rows[] = [
+ Link::fromTextAndUrl($solution_list_data->filename, Url::fromUri('internal:/lab-migration/download/file/' . $solution_list_data->id))->toString(),
+ $solution_file_type,
];
- $solution_files_header = ['Filename', 'Type']; // Table headers
+ }
+
+ $form['download_solution_wrapper']['solution_files'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('List of solution files'),
+ ];
- $table = [
- '#type' => 'table',
- '#header' => $solution_files_header,
- '#rows' => $solution_files_rows,
-
+ $form['download_solution_wrapper']['solution_files']['table'] = [
+ '#type' => 'table',
+ '#header' => [$this->t('Filename'), $this->t('Type')],
+ '#rows' => $solution_files_rows,
'#attributes' => [
'style' => 'width: 100%;',
-
],
];
- // Add the table to the fieldset
-$form['download_solution_wrapper']['solution_files']['table'] = $table;
-
-
-$form['submit'] = [
- '#type' => 'submit',
- '#value' => $this->t('Submit'),
-];
- return $form;
+
+ $form['submit'] = [
+ '#type' => 'submit',
+ '#value' => $this->t('Submit'),
+ ];
+
+ return $form;
}
+
public function ajax_experiment_list_callback(array &$form, FormStateInterface $form_state) {
return $form['download_lab_wrapper'];
-
}
+
public function ajax_solution_list_callback(array &$form, FormStateInterface $form_state) {
return $form['download_experiment_wrapper'];
-
}
+
public function ajax_solution_file_callback(array &$form, FormStateInterface $form_state) {
return $form['download_solution_wrapper'];
-
}
- public function _ajax_bulk_get_experiment_list($lab_default_value = '') {
- // return $form['download_lab_wrapper'];
+ public function _ajax_bulk_get_experiment_list($lab_default_value = '') {
$experiments = [
- '0' => 'Please select...',
+ '0' => $this->t('Please select...'),
];
-
- // Get the database connection.
- $connection = Database::getConnection();
-
- // Prepare the query.
- $query = $connection->select('lab_migration_experiment', 'lme')
+
+ $experiments_q = $this->database->select('lab_migration_experiment', 'lme')
->fields('lme', ['id', 'number', 'title'])
->condition('proposal_id', $lab_default_value)
- ->orderBy('number', 'ASC');
-
- // Execute the query and fetch results.
- $experiments_q = $query->execute();
- // var_dump($experiment_q);die;
+ ->orderBy('number', 'ASC')
+ ->execute();
+
foreach ($experiments_q as $experiments_data) {
$experiments[$experiments_data->id] = $experiments_data->number . '. ' . $experiments_data->title;
}
-
+
return $experiments;
}
-
+
public function _bulk_list_lab_actions(): array {
return [
- 0 => 'Please select...',
- 1 => 'Approve Entire Lab',
- 2 => 'Pending Review Entire Lab',
- 3 => 'Dis-Approve Entire Lab (This will delete all the solutions in the lab)',
- 4 => 'Delete Entire Lab Including Proposal',
+ 0 => $this->t('Please select...'),
+ 1 => $this->t('Approve Entire Lab'),
+ 2 => $this->t('Pending Review Entire Lab'),
+ 3 => $this->t('Dis-Approve Entire Lab (This will delete all the solutions in the lab)'),
+ 4 => $this->t('Delete Entire Lab Including Proposal'),
];
}
-
public function _bulk_list_of_labs(): array {
$lab_titles = [
- '0' => 'Please select...',
+ '0' => $this->t('Please select...'),
];
-
- // Get the database connection.
- $connection = Database::getConnection();
-
- // Prepare the query.
- $query = $connection->select('lab_migration_proposal', 'lmp')
+
+ $results = $this->database->select('lab_migration_proposal', 'lmp')
->fields('lmp', ['id', 'lab_title', 'name'])
->condition('solution_display', 1)
- ->orderBy('lab_title', 'ASC');
-
- // Execute the query and fetch results.
- $results = $query->execute();
- // var_dump($results);die;
+ ->orderBy('lab_title', 'ASC')
+ ->execute();
+
foreach ($results as $lab_titles_data) {
$lab_titles[$lab_titles_data->id] = $lab_titles_data->lab_title . ' (Proposed by ' . $lab_titles_data->name . ')';
}
- // var_dump($lab_titles);die;
+
return $lab_titles;
}
-
- public function ajax_bulk_experiment_list_callback(array &$form, FormStateInterface $form_state) {
- return $form['update_exp'];
- }
+ public function _ajax_bulk_get_solution_list($lab_experiment_list = ''): array {
+ $solutions = [
+ 0 => $this->t('Please select...'),
+ ];
+
+ if (empty($lab_experiment_list)) {
+ return $solutions;
+ }
-public function _ajax_bulk_get_solution_list($lab_experiment_list = ''): array {
- // return $form['download_solution_wrapper'];
+ $query = $this->database->select('lab_migration_solution', 'lms')
+ ->fields('lms', ['id', 'code_number', 'caption'])
+ ->condition('experiment_id', $lab_experiment_list);
- $solutions = [
- 0 => 'Please select...',
- ];
+ $query->addExpression("CAST(SUBSTRING_INDEX(code_number, '.', 1) AS BINARY)", 'part1');
+ $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(code_number, '.', 2), '.', -1) AS UNSIGNED)", 'part2');
+ $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(code_number, '.', -1), '.', 1) AS UNSIGNED)", 'part3');
+ $query->orderBy('part1', 'ASC');
+ $query->orderBy('part2', 'ASC');
+ $query->orderBy('part3', 'ASC');
+
+ $results = $query->execute();
+ foreach ($results as $solution) {
+ $solutions[$solution->id] = $solution->code_number . ' (' . $solution->caption . ')';
+ }
- if (empty($lab_experiment_list)) {
return $solutions;
}
-// var_dump($lab_experiment_list);die;
- // Get the database connection.
- $connection = Database::getConnection();
-
- // Prepare the query.
- $query = $connection->select('lab_migration_solution', 'lms')
- ->fields('lms', ['id', 'code_number', 'caption'])
- ->condition('experiment_id', $lab_experiment_list);
-
- // Add custom ordering logic for `code_number`.
- $query->addExpression("CAST(SUBSTRING_INDEX(code_number, '.', 1) AS BINARY)", 'part1');
- $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(code_number, '.', 2), '.', -1) AS UNSIGNED)", 'part2');
- $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(code_number, '.', -1), '.', 1) AS UNSIGNED)", 'part3');
- $query->orderBy('part1', 'ASC');
- $query->orderBy('part2', 'ASC');
- $query->orderBy('part3', 'ASC');
-
- // Execute the query and fetch results.
- $results = $query->execute();
-// var_dump($results);die;
- foreach ($results as $solution) {
- $solutions[$solution->id] = $solution->code_number . ' (' . $solution->caption . ')';
+
+ public function _lab_information($proposal_id) {
+ $lab_data = $this->database->select('lab_migration_proposal', 'l')
+ ->fields('l')
+ ->condition('l.id', $proposal_id)
+ ->condition('l.approval_status', 3)
+ ->execute()
+ ->fetchObject();
+
+ return $lab_data ?: NULL;
}
-// var_dump($solutions);die;
- return $solutions;
-}
-public function _lab_information($proposal_id)
- {
- //var_dump($proposal_id);die;
- //$lab_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal', 'l')
- ->fields('l')
- // ->fields('e',[])
- ->condition('l.id', $proposal_id)
- ->condition('l.approval_status', 3);
-
-$lab_q = $query->execute();
-$lab_data = $lab_q->fetchObject();
-//var_dump($lab_data);die;
-// Get the database connection.
-if ($lab_data) {
- return $lab_data;
-} else {
- return;
-}
-}
-public function _lab_details($lab_default_value)
- {
- // $lab_default_value = $form_state['values']['lab'];
+
+ public function _lab_details($lab_default_value) {
$lab_details = $this->_lab_information($lab_default_value);
- // $experiment_details = $this->_lab_experiment_information($lab_default_value);
- //var_dump($experiment_details);die;
- if ($lab_default_value != 0)
- {
- if ($lab_details){
- if ($lab_details->solution_provider_uid > 0)
- {
- $user_solution_provider = User::load($lab_details->solution_provider_uid);
- if ($user_solution_provider)
- {
- $solution_provider = '
Solution Provider ' . '' . 'Solution Provider Name: ' . $lab_details->solution_provider_name_title . ' ' . $lab_details->solution_provider_name . ' ' . 'Department: ' . $lab_details->solution_provider_department . ' ' . 'University: ' . $lab_details->solution_provider_university . ' ' . ' ';
- }
- else
- {
- $solution_provider = 'Solution Provider ' . '' . 'Solution Provider: (Open) ' . ' ';
- }
+ if ($lab_default_value != 0) {
+ if ($lab_details) {
+ if ($lab_details->solution_provider_uid > 0) {
+ $user_solution_provider = User::load($lab_details->solution_provider_uid);
+ if ($user_solution_provider) {
+ $solution_provider = 'Solution Provider ' . '' . 'Solution Provider Name: ' . $lab_details->solution_provider_name_title . ' ' . $lab_details->solution_provider_name . ' ' . 'Department: ' . $lab_details->solution_provider_department . ' ' . 'University: ' . $lab_details->solution_provider_university . ' ' . ' ';
}
- else
- {
+ else {
$solution_provider = 'Solution Provider ' . '' . 'Solution Provider: (Open) ' . ' ';
- }}
- else{
- // drupal_goto('lab-migration/lab-migration-run');
- $url = Url::fromRoute('lab_migration.run_form');
-
-// Create a RedirectResponse and send it.
-$response = new RedirectResponse($url->toString());
-$response->send();
-
+ }
+ }
+ else {
+ $solution_provider = 'Solution Provider ' . '' . 'Solution Provider: (Open) ' . ' ';
+ }
}
-
- $form['lab_details']['#markup'] = 'About the Lab ' . '' . 'Proposer Name: ' . $lab_details->name_title . ' ' . $lab_details->name . ' ' . 'Title of the Lab: ' . $lab_details->lab_title . ' ' . 'Department: ' . $lab_details->department . ' ' . 'University: ' . $lab_details->university . ' ' . 'Operating System: ' . $lab_details->operating_system . ' ' . ' ' . $solution_provider;
-
- $details = $form['lab_details']['#markup'];
- return $details;
-
+ else {
+ return;
}
-
- }
-
-public function _bulk_list_solution_actions(): array {
- return [
- 0 => 'Please select...',
- 1 => 'Approve Entire Solution',
- 2 => 'Pending Review Entire Solution',
- 3 => 'Dis-approve Solution (This will delete the solution)',
- ];
-}
-public function _bulk_list_experiment_actions()
- {
- $lab_experiment_actions = array(
- 0 => 'Please select...'
- );
- $lab_experiment_actions[1] = 'Approve Entire Experiment';
- $lab_experiment_actions[2] = 'Pending Review Entire Experiment';
- $lab_experiment_actions[3] = 'Dis-Approve Entire Experiment (This will delete all the solutions in the experiment)';
- return $lab_experiment_actions;
- }
-
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- //var_dump($user->id());die;
- $root_path = \Drupal::service("lab_migration_global")->lab_migration_path();
- // var_dump($form_state->get(['clicked_button', '#value']));die;
- // if ($form_state->get(['clicked_button', '#value']) == 'Submit') {
- if ($form_state->getValue(['lab']))
- //lab_migration_del_lab_pdf($form_state['values']['lab']);
- {
- //var_dump($form_state->getValue(['lab_actions']));die;
- if ($user->hasPermission('lab migration bulk manage code')) {
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $form_state->getValue(['lab']));
- $user_query = $query->execute();
- $user_info = $user_query->fetchObject();
- $user_data = User::load($user_info->uid);
- if (($form_state->getValue(['lab_actions']) == 1) && ($form_state->getValue(['lab_experiment_actions']) == 0) && ($form_state->getValue(['lab_experiment_solution_actions']) == 0)) {
- // var_dump("hi");die;
- /* approving entire lab */
- // $experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d", $form_state['values']['lab']);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $form_state->getValue(['lab']));
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_list = '';
- while ($experiment_data = $experiment_q->fetchObject()) {
- // \Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 1, approver_uid = %d WHERE experiment_id = %d AND approval_status = 0", $user->uid, $experiment_data->id);
- \Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 1, approver_uid = :approver_uid WHERE experiment_id = :experiment_id AND approval_status = 0", [
- ':approver_uid' => $user->id(),
- ':experiment_id' => $experiment_data->id,
- ]);
- $experiment_list .= '' . $experiment_data->number . ') ' . $experiment_data->title . ' Description : ' . $experiment_data->description . ' ';
- $experiment_list .= ' ';
- $experiment_list .= '
';
- }
- $msg = \Drupal::messenger()->addmessage(t('Approved Entire Lab. Click on the checkbox below to mark this lab completed'), 'status');
- // fromUri('internal:/lab-migration/manage-proposal/status/' . $form_state->getValue(['lab']))
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solutions have been approved', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-// Your all the uploaded solutions for the Lab with the below detail has been approved:
+ $form['lab_details']['#markup'] = 'About the Lab ' . '' . 'Proposer Name: ' . $lab_details->name_title . ' ' . $lab_details->name . ' ' . 'Title of the Lab: ' . $lab_details->lab_title . ' ' . 'Department: ' . $lab_details->department . ' ' . 'University: ' . $lab_details->university . ' ' . 'Operating System: ' . $lab_details->operating_system . ' ' . ' ' . $solution_provider;
-// Title of Lab:' . $user_info->lab_title . '
+ return $form['lab_details']['#markup'];
+ }
+ }
-// List of experiments: ' . $experiment_list . '
+ public function _bulk_list_solution_actions(): array {
+ return [
+ 0 => $this->t('Please select...'),
+ 1 => $this->t('Approve Entire Solution'),
+ 2 => $this->t('Pending Review Entire Solution'),
+ 3 => $this->t('Dis-approve Solution (This will delete the solution)'),
+ ];
+ }
-// Best Wishes,
+ public function _bulk_list_experiment_actions() {
+ return [
+ 0 => $this->t('Please select...'),
+ 1 => $this->t('Approve Entire Experiment'),
+ 2 => $this->t('Pending Review Entire Experiment'),
+ 3 => $this->t('Dis-Approve Entire Experiment (This will delete all the solutions in the experiment)'),
+ ];
+ }
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '@site_name' => $config->get('site_name', ''),
-// '@user_name' => $user_data->name,
-// ])
-// ];
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $root_path = $this->labGlobal->lab_migration_path();
+
+ if ($form_state->getValue('lab')) {
+ if ($this->currentUser->hasPermission('lab migration bulk manage code')) {
+ $user_info = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $form_state->getValue('lab'))
+ ->execute()
+ ->fetchObject();
+
+ $user_data = User::load($user_info->uid);
+
+ if (($form_state->getValue('lab_actions') == 1) && ($form_state->getValue('lab_experiment_actions') == 0) && ($form_state->getValue('lab_experiment_solution_actions') == 0)) {
+ /* approving entire lab */
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $form_state->getValue('lab'))
+ ->orderBy('number', 'ASC')
+ ->execute();
+
+ while ($experiment_data = $experiment_q->fetchObject()) {
+ $this->database->update('lab_migration_solution')
+ ->fields([
+ 'approval_status' => 1,
+ 'approver_uid' => $this->currentUser->id(),
+ ])
+ ->condition('experiment_id', $experiment_data->id)
+ ->condition('approval_status', 0)
+ ->execute();
}
- elseif (($form_state->getValue(['lab_actions']) == 2) && ($form_state->getValue(['lab_experiment_actions']) == 0) && ($form_state->getValue(['lab_experiment_solution_actions']) == 0)) {
- /* pending review entire lab */
- //$experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d", $form_state['values']['lab']);
- $experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = :proposal_id", [
- ':proposal_id' => $form_state->getValue(['lab'])
- ]);
- while ($experiment_data = $experiment_q->fetchObject()) {
- //\Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 0 WHERE experiment_id = %d", $experiment_data->id);
- \Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 0 WHERE experiment_id = :experiment_id", [
- ":experiment_id" => $experiment_data->id
- ]);
- }
- \Drupal::messenger()->addmessage(t('Pending Review Entire Lab.'), 'status');
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solutions have been marked as pending', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// Your all the uploaded solutions for the Lab with Title: ' . $user_info->lab_title . ' have been marked as pending to be reviewed.
-
-// You will be able to see the solutions after they have been approved by one of our reviewers.
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /* $email_subject = t('Your uploaded Lab Migration solutions have been marked as pending');
- $email_body = array(0 => t('Your all the uploaded solutions for the Lab have been marked as pending to be review. You will be able to see the solutions after they have been approved by one of our reviewers.'));*/
+ $this->messenger->addMessage($this->t('Approved Entire Lab. Click on the checkbox below to mark this lab completed'), 'status');
+ }
+ elseif (($form_state->getValue('lab_actions') == 2) && ($form_state->getValue('lab_experiment_actions') == 0) && ($form_state->getValue('lab_experiment_solution_actions') == 0)) {
+ /* pending review entire lab */
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $form_state->getValue('lab'))
+ ->execute();
+
+ while ($experiment_data = $experiment_q->fetchObject()) {
+ $this->database->update('lab_migration_solution')
+ ->fields(['approval_status' => 0])
+ ->condition('experiment_id', $experiment_data->id)
+ ->execute();
}
- elseif (($form_state->getValue(['lab_actions']) == 3) && ($form_state->getValue(['lab_experiment_actions']) == 0) && ($form_state->getValue(['lab_experiment_solution_actions']) == 0)) {
-
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- //$form_state->setErrorByName('message', t(''));
- \Drupal::messenger()->addmessage("Please mention the reason for disapproval. Minimum 30 character required", 'error');
- return;
- }
- if (!$user->hasPermission('lab migration bulk delete code')) {
- \Drupal::messenger()->addmessage(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Lab.'), 'error');
- return;
- }
- if (lab_migration_delete_lab($form_state->getValue(['lab']))) {
- \Drupal::messenger()->addmessage(t('Dis-Approved and Deleted Entire Lab.'), 'status');
- }
- else {
- \Drupal::messenger()->addmessage(t('Error Dis-Approving and Deleting Entire Lab.'), 'error');
- }
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solutions have been marked as dis-approved', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// Your all the uploaded solutions for the whole Lab with Title: ' . $user_info->lab_title . ' have been marked as dis-approved.
-
-// Reason for dis-approval: ' . $form_state->getValue(['message']) . '
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
-// /* email */
- /* $email_subject = t('Your uploaded Lab Migration solutions have been marked as dis-approved');
- $email_body = array(0 =>t('Your all the uploaded solutions for the whole Lab have been marked as dis-approved.
-
- Reason for dis-approval:
-
- ' . $form_state['values']['message']));*/
+ $this->messenger->addMessage($this->t('Pending Review Entire Lab.'), 'status');
+ }
+ elseif (($form_state->getValue('lab_actions') == 3) && ($form_state->getValue('lab_experiment_actions') == 0) && ($form_state->getValue('lab_experiment_solution_actions') == 0)) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $this->messenger->addError($this->t("Please mention the reason for disapproval. Minimum 30 character required"));
+ return;
}
- elseif (($form_state->getValue(['lab_actions']) == 4) && ($form_state->getValue(['lab_experiment_actions']) == 0) && ($form_state->getValue(['lab_experiment_solution_actions']) == 0)) {
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- //$form_state->setErrorByName('message', t(''));
- \Drupal::messenger()->addmessage("Please mention the reason for disapproval/deletion. Minimum 30 character required", 'error');
- return;
- }
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $form_state->getValue(['lab']));
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_list = '';
- while ($experiment_data = $experiment_q->fetchObject()) {
- $experiment_list .= '' . $experiment_data->number . ') ' . $experiment_data->title . ' Description: ' . $experiment_data->description . ' ';
- $experiment_list .= ' ';
- $experiment_list .= '
';
- }
- if (!$user->hasPermission('lab migration bulk delete code')) {
- \Drupal::messenger()->addmessage(t('You do not have permission to Bulk Delete Entire Lab Including Proposal.'), 'error');
- return;
- }
- /* check if dependency files are present */
- $dep_q = \Drupal::database()->query("SELECT * FROM {lab_migration_dependency_files} WHERE proposal_id = :proposal_id", [
- ":proposal_id" => $form_state->getValue(['lab'])
- ]);
- if ($dep_data = $dep_q->fetchObject()) {
- \Drupal::messenger()->addmessage(t("Cannot delete lab since it has dependency files that can be used by others. First delete the dependency files before deleting the lab."), 'error');
- return;
- }
- if (\Drupal::service("lab_migration_global")->lab_migration_delete_lab($form_state->getValue(['lab']))) {
- \Drupal::messenger()->addmessage(t('Dis-Approved and Deleted Entire Lab solutions.'), 'status');
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $form_state->getValue(['lab']));
- $proposal_q = $query->execute()->fetchObject();
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $form_state->getValue(['lab']));
- $experiment_q = $query->execute();
- $experiment_data = $experiment_q->fetchObject();
- $exp_path = $root_path . $proposal_q->directory_name . '/EXP' . $experiment_data->number;
- $dir_path = $root_path . $proposal_q->directory_name;
- if (is_dir($dir_path)) {
- rmdir($exp_path);
- $res = rmdir($dir_path);
- if (!$res) {
- \Drupal::messenger()->addmessage(t("Cannot delete Lab directory: " . $dir_path . ". Please contact administrator."), 'error');
- return;
- }
+ if (!$this->currentUser->hasPermission('lab migration bulk delete code')) {
+ $this->messenger->addError($this->t('You do not have permission to Bulk Dis-Approved and Deleted Entire Lab.'));
+ return;
+ }
+ if ($this->labGlobal->lab_migration_delete_lab($form_state->getValue('lab'))) {
+ $this->messenger->addMessage($this->t('Dis-Approved and Deleted Entire Lab.'), 'status');
+ }
+ else {
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Entire Lab.'));
+ }
+ }
+ elseif (($form_state->getValue('lab_actions') == 4) && ($form_state->getValue('lab_experiment_actions') == 0) && ($form_state->getValue('lab_experiment_solution_actions') == 0)) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $this->messenger->addError($this->t("Please mention the reason for disapproval/deletion. Minimum 30 character required"));
+ return;
+ }
+ if (!$this->currentUser->hasPermission('lab migration bulk delete code')) {
+ $this->messenger->addError($this->t('You do not have permission to Bulk Delete Entire Lab Including Proposal.'));
+ return;
+ }
+ /* check if dependency files are present */
+ $dep_data = $this->database->select('lab_migration_dependency_files')
+ ->fields('lab_migration_dependency_files')
+ ->condition('proposal_id', $form_state->getValue('lab'))
+ ->execute()
+ ->fetchObject();
+
+ if ($dep_data) {
+ $this->messenger->addError($this->t("Cannot delete lab since it has dependency files that can be used by others. First delete the dependency files before deleting the lab."));
+ return;
+ }
+ if ($this->labGlobal->lab_migration_delete_lab($form_state->getValue('lab'))) {
+ $this->messenger->addMessage($this->t('Dis-Approved and Deleted Entire Lab solutions.'), 'status');
+ $proposal_q = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $form_state->getValue('lab'))
+ ->execute()
+ ->fetchObject();
+
+ $experiment_data = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $form_state->getValue('lab'))
+ ->execute()
+ ->fetchObject();
+
+ $dir_path = $root_path . $proposal_q->directory_name;
+ if (is_dir($dir_path)) {
+ if ($experiment_data) {
+ $exp_path = $root_path . $proposal_q->directory_name . '/EXP' . $experiment_data->number;
+ @rmdir($exp_path);
}
- else {
- \Drupal::messenger()->addmessage(t("Lab directory not present: " . $dir_path . ". Skipping deleting lab directory."), 'status');
+ $res = @rmdir($dir_path);
+ if (!$res) {
+ $this->messenger->addError($this->t("Cannot delete Lab directory: @dir. Please contact administrator.", ['@dir' => $dir_path]));
+ return;
}
- /* deleting full proposal */
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $form_state['values']['lab']);
- $proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = :id", [
- ":id" => $form_state->getValue(['lab'])
- ]);
- $proposal_data = $proposal_q->fetchObject();
- $proposal_id = $proposal_data->id;
- \Drupal::database()->query("DELETE FROM {lab_migration_experiment} WHERE proposal_id = :proposal_id", [
- ":proposal_id" => $proposal_id
- ]);
- \Drupal::database()->query("DELETE FROM {lab_migration_proposal} WHERE id = :id", [
- ":id" => $proposal_id
- ]);
- \Drupal::messenger()->addmessage(t('Deleted Lab Proposal.'), 'status');
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solutions including the Lab proposal have been deleted', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear ' . $proposal_data->name . ',
-
-// We regret to inform you that all the uploaded Experiments of your Lab with following details have been deleted permanently.
-
-// Title of Lab:' . $user_info->lab_title . '
-
-// List of experiments: ' . $experiment_list . '
-
-// Reason for dis-approval: ' . $form_state->getValue(['message']) . '
-
-// Best Wishes,
-
-// !site_name Team
-// FOSSEE, IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /* $email_subject = t('Your uploaded Lab Migration solutions including the Lab proposal have been deleted');
- $email_body = array(0 =>t('Your all the uploaded solutions including the Lab proposal have been deleted permanently.'));*/
}
else {
- \Drupal::messenger()->addmessage(t('Error Dis-Approving and Deleting Entire Lab.'), 'error');
+ $this->messenger->addMessage($this->t("Lab directory not present: @dir. Skipping deleting lab directory.", ['@dir' => $dir_path]), 'status');
}
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $form_state->getValue('lab'))
+ ->execute()
+ ->fetchObject();
+
+ if ($proposal_data) {
+ $this->database->delete('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_data->id)
+ ->execute();
+
+ $this->database->delete('lab_migration_proposal')
+ ->condition('id', $proposal_data->id)
+ ->execute();
+ }
+
+ $this->messenger->addMessage($this->t('Deleted Lab Proposal.'), 'status');
}
- elseif (($form_state->getValue(['lab_actions']) == 0) && ($form_state->getValue(['lab_experiment_actions']) == 1) && ($form_state->getValue(['lab_experiment_solution_actions']) == 0)) {
- \Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 1, approver_uid = :approver_uid WHERE experiment_id = :experiment_id AND approval_status = 0", [
- ":approver_uid" => $user->id(),
- ":experiment_id" => $form_state->getValue(['lab_experiment_list']),
- ]);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $form_state->getValue(['lab_experiment_list']));
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_value = $experiment_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $form_state->getValue(['lab_experiment_list']));
- $query->orderBy('code_number', 'ASC');
- $solution_q = $query->execute();
- $solution_value = $solution_q->fetchObject();
- \Drupal::messenger()->addmessage(t('Approved Entire Experiment.'), 'status');
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solution have been approved', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// Your Experiment for R Lab Migration with the following details is approved.
-
-// Experiment name: ' . $experiment_value->title . '
-// Caption: ' . $solution_value->caption . '
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /* $email_subject = t('Your uploaded Lab Migration solutions have been approved');
- $email_body = array(0 =>t('Your all the uploaded solutions for the experiment have been approved.'));*/
+ else {
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Entire Lab.'));
}
- elseif (($form_state->getValue(['lab_actions']) == 0) && ($form_state->getValue(['lab_experiment_actions']) == 2) && ($form_state->getValue(['lab_experiment_solution_actions']) == 0)) {
- \Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 0 WHERE experiment_id = :experiment_id", [
- ":experiment_id" => $form_state->getValue(['lab_experiment_list'])
- ]);
- \Drupal::messenger()->addmessage(t('Entire Experiment marked as Pending Review.'), 'status');
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $form_state->getValue(['lab_experiment_list']));
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_value = $experiment_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $form_state->getValue(['lab_experiment_list']));
- $query->orderBy('code_number', 'ASC');
- $solution_q = $query->execute();
- $solution_value = $solution_q->fetchObject();
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solution have been marked as pending', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// Your all the uploaded solutions for the experiment have been marked as pending to be reviewed.
-
-// Experiment name: ' . $experiment_value->title . '
-// Caption: ' . $solution_value->caption . '
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /*$email_subject = t('Your uploaded Lab Migration solutions have been marked as pending');
- $email_body = array(0 =>t('Your all the uploaded solutions for the experiment have been marked as pending to be review.'));*/
+ }
+ elseif (($form_state->getValue('lab_actions') == 0) && ($form_state->getValue('lab_experiment_actions') == 1) && ($form_state->getValue('lab_experiment_solution_actions') == 0)) {
+ $this->database->update('lab_migration_solution')
+ ->fields([
+ 'approval_status' => 1,
+ 'approver_uid' => $this->currentUser->id(),
+ ])
+ ->condition('experiment_id', $form_state->getValue('lab_experiment_list'))
+ ->condition('approval_status', 0)
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Approved Entire Experiment.'), 'status');
+ }
+ elseif (($form_state->getValue('lab_actions') == 0) && ($form_state->getValue('lab_experiment_actions') == 2) && ($form_state->getValue('lab_experiment_solution_actions') == 0)) {
+ $this->database->update('lab_migration_solution')
+ ->fields(['approval_status' => 0])
+ ->condition('experiment_id', $form_state->getValue('lab_experiment_list'))
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Entire Experiment marked as Pending Review.'), 'status');
+ }
+ elseif (($form_state->getValue('lab_actions') == 0) && ($form_state->getValue('lab_experiment_actions') == 3) && ($form_state->getValue('lab_experiment_solution_actions') == 0)) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $this->messenger->addError($this->t("Please mention the reason for disapproval. Minimum 30 character required"));
+ return;
}
- elseif (($form_state->getValue(['lab_actions']) == 0) && ($form_state->getValue(['lab_experiment_actions']) == 3) && ($form_state->getValue(['lab_experiment_solution_actions']) == 0)) {
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- //$form_state->setErrorByName('message', t(''));
- \Drupal::messenger()->addmessage("Please mention the reason for disapproval. Minimum 30 character required", 'error');
- return;
- }
- if (!$user->hasPermission('lab migration bulk delete code')) {
- \Drupal::messenger()->addmessage(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Experiment.'), 'error');
- return;
- }
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $form_state->getValue(['lab_experiment_list']));
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_value = $experiment_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $form_state->getValue(['lab_experiment_list']));
- $query->orderBy('code_number', 'ASC');
- $solution_q = $query->execute();
- $solution_value = $solution_q->fetchObject();
- if (\Drupal::service("lab_migration_global")->lab_migration_delete_experiment($form_state->getValue(['lab_experiment_list']))) {
- \Drupal::messenger()->addmessage(t('Dis-Approved and Deleted Entire Experiment.'), 'status');
- }
- else {
- \Drupal::messenger()->addmessage(t('Error Dis-Approving and Deleting Entire Experiment.'), 'error');
- }
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solutions have been marked as dis-approved', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// We regret to inform you that your experiment with the following details under R Lab Migration is disapproved and has been deleted.
-
-// Experiment name: ' . $experiment_value->title . '
-// Caption: ' . $solution_value->caption . '
-
-// Reason for dis-approval: ' . $form_state->getValue(['message']) . '
-
-// Please resubmit the modified solution.
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /*$email_subject = t('Your uploaded Lab Migration solutions have been marked as dis-approved');
- $email_body = array(0 => t('Your uploaded solutions for the entire experiment have been marked as dis-approved.
-
- Reason for dis-approval:
-
- ' . $form_state['values']['message']));*/
+ if (!$this->currentUser->hasPermission('lab migration bulk delete code')) {
+ $this->messenger->addError($this->t('You do not have permission to Bulk Dis-Approved and Deleted Entire Experiment.'));
+ return;
}
- elseif (($form_state->getValue(['lab_actions']) == 0) && ($form_state->getValue(['lab_experiment_actions']) == 0) && ($form_state->getValue(['lab_experiment_solution_actions']) == 1)) {
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $form_state->getValue(['solution_list']));
- $query->orderBy('code_number', 'ASC');
- $solution_q = $query->execute();
- $solution_value = $solution_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_value->experiment_id);
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_value = $experiment_q->fetchObject();
- \Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 1, approver_uid = :approver_uid WHERE id = :id", [
- ":approver_uid" => $user->uid,
- ":id" => $form_state->getValue(['solution_list']),
- ]);
- \Drupal::messenger()->addmessage(t('Solution approved.'), 'status');
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solution has been approved', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// Your Experiment for R Lab Migration with the following details is approved.
-
-// Experiment name: ' . $experiment_value->title . '
-// Caption: ' . $solution_value->caption . '
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /* $email_subject = t('Your uploaded Lab Migration solution has been approved');
- $email_body = array(0 =>t('Your uploaded solution has been approved.'));*/
+ if ($this->labGlobal->lab_migration_delete_experiment($form_state->getValue('lab_experiment_list'))) {
+ $this->messenger->addMessage($this->t('Dis-Approved and Deleted Entire Experiment.'), 'status');
}
- elseif (($form_state->getValue(['lab_actions']) == 0) && ($form_state->getValue(['lab_experiment_actions']) == 0) && ($form_state->getValue(['lab_experiment_solution_actions']) == 2)) {
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $form_state->getValue(['solution_list']));
- $query->orderBy('code_number', 'ASC');
- $solution_q = $query->execute();
- $solution_value = $solution_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_value->experiment_id);
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_value = $experiment_q->fetchObject();
- \Drupal::database()->query("UPDATE {lab_migration_solution} SET approval_status = 0 WHERE id = :id", [
- ":id" => $form_state->getValue(['solution_list'])
- ]);
- \Drupal::messenger()->addmessage(t('Solution marked as Pending Review.'), 'status');
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solution has been marked as pending', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// Your all the uploaded solutions for the experiment have been marked as pending to be reviewed.
-
-// Experiment name: ' . $experiment_value->title . '
-// Caption: ' . $solution_value->caption . '
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /*$email_subject = t('Your uploaded Lab Migration solution has been marked as pending');
- $email_body = array(0 =>t('Your uploaded solution has been marked as pending to be review.'));*/
+ else {
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Entire Experiment.'));
}
- elseif (($form_state->getValue(['lab_actions']) == 0) && ($form_state->getValue(['lab_experiment_actions']) == 0) && ($form_state->getValue(['lab_experiment_solution_actions']) == 3)) {
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $form_state->getValue(['solution_list']));
- $query->orderBy('code_number', 'ASC');
- $solution_q = $query->execute();
- $solution_value = $solution_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_value->experiment_id);
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
- $experiment_value = $experiment_q->fetchObject();
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- //$form_state->setErrorByName('message', t(''));
- \Drupal::messenger()->addmessage("Please mention the reason for disapproval. Minimum 30 character required", 'error');
- return;
- }
- if (\Drupal::service("lab_migration_global")->lab_migration_delete_solution($form_state->getValue(['solution_list']))) {
- \Drupal::messenger()->addmessage(t('Solution Dis-Approved and Deleted.'), 'status');
- }
- else {
- \Drupal::messenger()->addmessage(t('Error Dis-Approving and Deleting Solution.'), 'error');
- }
- /* email */
-// $email_subject = t('[!site_name] Your uploaded Lab Migration solution has been marked as dis-approved', [
-// '!site_name' => $config->get('site_name', '')
-// ]);
-// $email_body = [
-// 0 => t('
-
-// Dear !user_name,
-
-// We regret to inform you that your experiment with the following details under R Lab Migration is disapproved and has been deleted.
-
-// Experiment name: ' . $experiment_value->title . '
-// Caption: ' . $solution_value->caption . '
-
-// Reason for dis-approval: ' . $form_state->getValue(['message']) . '
-
-// Please resubmit the modified solution.
-
-// Best Wishes,
-
-// !site_name Team,
-// FOSSEE,IIT Bombay', [
-// '!site_name' => $config->get('site_name', ''),
-// '!user_name' => $user_data->name,
-// ])
-// ];
- /* email */
- /* $email_subject = t('Your uploaded Lab Migration solution has been marked as dis-approved');
- $email_body = array(0 =>t('Your uploaded solution has been marked as dis-approved.
-
- Reason for dis-approval:
-
- ' . $form_state['values']['message']));*/
+ }
+ elseif (($form_state->getValue('lab_actions') == 0) && ($form_state->getValue('lab_experiment_actions') == 0) && ($form_state->getValue('lab_experiment_solution_actions') == 1)) {
+ $this->database->update('lab_migration_solution')
+ ->fields([
+ 'approval_status' => 1,
+ 'approver_uid' => $this->currentUser->id(),
+ ])
+ ->condition('id', $form_state->getValue('solution_list'))
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Solution approved.'), 'status');
+ }
+ elseif (($form_state->getValue('lab_actions') == 0) && ($form_state->getValue('lab_experiment_actions') == 0) && ($form_state->getValue('lab_experiment_solution_actions') == 2)) {
+ $this->database->update('lab_migration_solution')
+ ->fields(['approval_status' => 0])
+ ->condition('id', $form_state->getValue('solution_list'))
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Solution marked as Pending Review.'), 'status');
+ }
+ elseif (($form_state->getValue('lab_actions') == 0) && ($form_state->getValue('lab_experiment_actions') == 0) && ($form_state->getValue('lab_experiment_solution_actions') == 3)) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $this->messenger->addError($this->t("Please mention the reason for disapproval. Minimum 30 character required"));
+ return;
+ }
+ if ($this->labGlobal->lab_migration_delete_solution($form_state->getValue('solution_list'))) {
+ $this->messenger->addMessage($this->t('Solution Dis-Approved and Deleted.'), 'status');
}
else {
- \Drupal::messenger()->addmessage(t('Please select only one action at a time'), 'error');
- return;
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Solution.'));
}
- /** sending email when everything done **/
- // if ($email_subject) {
- // $email_to = $user_data->mail;
- // $from = $config->get('lab_migration_from_email', '');
- // $bcc = $config->get('lab_migration_emails', '');
- // $cc = $config->get('lab_migration_cc_emails', '');
- // $param['standard']['subject'] = $email_subject;
- // $param['standard']['body'] = $email_body;
- // $param['standard']['headers'] = [
- // 'From' => $from,
- // 'MIME-Version' => '1.0',
- // 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- // 'Content-Transfer-Encoding' => '8Bit',
- // 'X-Mailer' => 'Drupal',
- // 'Cc' => $cc,
- // 'Bcc' => $bcc,
- // ];
- // if (!drupal_mail('lab_migration', 'standard', $email_to, language_default(), $param, $from, TRUE)) {
- // \Drupal::messenger()->addmessage('Error sending email message.', 'error');
- // }
- // }
}
- // else {
- // \Drupal::messenger()->addmessage(t('You do not have permission to bulk manage code.'), 'error');
- // }
+ else {
+ $this->messenger->addError($this->t('Please select only one action at a time'));
+ }
}
- //}
- return $msg;
+ }
}
- }
-?>
\ No newline at end of file
+
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationBulkUploadCodeForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationBulkUploadCodeForm.php
index e5e4ba6..6959c6e 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationBulkUploadCodeForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationBulkUploadCodeForm.php
@@ -9,12 +9,96 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\user\Entity\User;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
+use Drupal\Core\Link;
use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedFormResponseException;
class LabMigrationBulkUploadCodeForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * Constructs a new LabMigrationBulkUploadCodeForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ LabMigrationGlobalfunction $lab_global,
+ MailService $mail_service,
+ RequestStack $request_stack
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->labGlobal = $lab_global;
+ $this->mailService = $mail_service;
+ $this->requestStack = $request_stack;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('lab_migration_global'),
+ $container->get('lab_migration.mail_service'),
+ $container->get('request_stack')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -22,465 +106,496 @@ public function getFormId() {
return 'lab_migration_bulk_upload_code_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('proposal_id');
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('proposal_id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
if (!$proposal_data) {
- \Drupal::messenger()->addmessage("Invalid proposal selected", 'error');
- // RedirectResponse('lab_migration/code_approval/bulk');
- $url = Url::fromRoute('lab_migration.code_approval')->toString();
-$response = new RedirectResponse($url);
-$response->send();
+ $this->messenger->addError($this->t("Invalid proposal selected"));
+ $response = new RedirectResponse(Url::fromRoute('lab_migration.bulk_approval_form')->toString());
+ throw new EnforcedFormResponseException($response);
}
- /* add javascript for dependency selection effects */
+
$dep_selection_js = "(function ($) {
$('#edit-existing-depfile-dep-lab-title').change(function() {
var dep_selected = '';
+ var activeClass = $(this).val();
/* showing and hiding relevant files */
- $('.form-checkboxes .option').hide();
- $('.form-checkboxes .option').each(function(index) {
- var activeClass = $('#edit-existing-depfile-dep-lab-title').va\Drupal\Core\Link;
- if ($(this).children().hasClass(activeClass)) {
+ $('.form-checkboxes .form-item').hide();
+ $('.form-checkboxes .form-item').each(function() {
+ if ($(this).find('input').hasClass(activeClass)) {
$(this).show();
}
- if ($(this).children().attr('checked') == true) {
- dep_selected += $(this).children().next().text() + ' ';
+ if ($(this).find('input').prop('checked') == true) {
+ dep_selected += $(this).find('label').text() + ' ';
}
});
/* showing list of already existing dependencies */
$('#existing_depfile_selected').html(dep_selected);
});
- $('.form-checkboxes .option').change(function() {
+ $('.form-checkboxes input').change(function() {
$('#edit-existing-depfile-dep-lab-title').trigger('change');
});
$('#edit-existing-depfile-dep-lab-title').trigger('change');
})(jQuery);";
- #attached($dep_selection_js, 'inline', 'header');
+
+ $form['#attached']['html_head'][] = [
+ [
+ '#tag' => 'script',
+ '#value' => $dep_selection_js,
+ ],
+ 'dep_selection_js',
+ ];
+
$form['#attributes'] = ['enctype' => "multipart/form-data"];
+
$form['lab_title'] = [
'#type' => 'item',
- '#value' => $proposal_data->lab_title,
- '#title' => t('Title of the Lab'),
+ '#markup' => $proposal_data->lab_title,
+ '#title' => $this->t('Title of the Lab'),
];
+
$form['name'] = [
'#type' => 'item',
- '#value' => $proposal_data->name_title . ' ' . $proposal_data->name,
- '#title' => t('Proposer Name'),
+ '#markup' => $proposal_data->name_title . ' ' . $proposal_data->name,
+ '#title' => $this->t('Proposer Name'),
];
+
/* get experiment list */
$experiment_rows = [];
- //$experiment_q = $injected_database->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY id ASC", $proposal_data->id);
- $query = $injected_database->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_data->id);
- $query->orderBy('id', 'ASC');
- $experiment_q = $query->execute();
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_data->id)
+ ->orderBy('id', 'ASC')
+ ->execute();
+
while ($experiment_data = $experiment_q->fetchObject()) {
$experiment_rows[$experiment_data->id] = $experiment_data->number . '. ' . $experiment_data->title;
}
+
$form['experiment'] = [
'#type' => 'select',
- '#title' => t('Title of the Experiment'),
+ '#title' => $this->t('Title of the Experiment'),
'#options' => $experiment_rows,
'#multiple' => FALSE,
'#size' => 1,
'#required' => TRUE,
];
+
$form['code_number'] = [
'#type' => 'textfield',
- '#title' => t('Code No'),
+ '#title' => $this->t('Code No'),
'#size' => 5,
'#maxlength' => 10,
- '#description' => t(""),
'#required' => TRUE,
];
+
$form['code_caption'] = [
'#type' => 'textfield',
- '#title' => t('Caption'),
+ '#title' => $this->t('Caption'),
'#size' => 40,
'#maxlength' => 255,
- '#description' => t(''),
'#required' => TRUE,
];
+
$form['code_warning'] = [
'#type' => 'item',
- '#title' => t('Upload all the dwsim project files in .zip format'),
+ '#markup' => $this->t('Upload all the dwsim project files in .zip format'),
'#prefix' => '',
'#suffix' => '
',
];
+
+ $config = $this->configFactory()->get('lab_migration.settings');
+
$form['sourcefile'] = [
'#type' => 'fieldset',
- '#title' => t('Main or Source Files'),
+ '#title' => $this->t('Main or Source Files'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
];
+
$form['sourcefile']['sourcefile1'] = [
'#type' => 'file',
- '#title' => t('Upload main or source file'),
+ '#title' => $this->t('Upload main or source file'),
'#size' => 48,
- '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . $config->get('lab_migration_source_extensions', ''),
+ '#description' => $this->t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . $this->t('Allowed file extensions : ') . $config->get('lab_migration_source_extensions'),
];
+
$form['dep_files'] = [
'#type' => 'item',
- '#title' => t('Dependency Files'),
+ '#title' => $this->t('Dependency Files'),
];
+
/************ START OF EXISTING DEPENDENCIES **************/
- /* existing dependencies */
$form['existing_depfile'] = [
'#type' => 'fieldset',
- '#title' => t('Use Already Existing Dependency Files'),
+ '#title' => $this->t('Use Already Existing Dependency Files'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'#prefix' => '',
'#suffix' => '
',
'#tree' => TRUE,
];
- /* existing dependencies */
+
$form['existing_depfile']['selected'] = [
'#type' => 'item',
- '#title' => t('Existing Dependency Files Selected'),
- '#value' => '
',
+ '#title' => $this->t('Existing Dependency Files Selected'),
+ '#markup' => '
',
];
+
$form['existing_depfile']['dep_lab_title'] = [
'#type' => 'select',
- '#title' => t('Title of the Lab'),
- '#options' => _list_of_lab_titles(),
+ '#title' => $this->t('Title of the Lab'),
+ '#options' => $this->_list_of_lab_titles(),
];
- list($files_options, $files_options_class) = _list_of_dependency_files();
+
+ list($files_options, $files_options_class) = $this->_list_of_dependency_files();
$form['existing_depfile']['dep_experiment_files'] = [
'#type' => 'checkboxes',
- '#title' => t('Dependency Files'),
+ '#title' => $this->t('Dependency Files'),
'#options' => $files_options,
- '#options_class' => $files_options_class,
+ '#options_attributes' => $files_options_class,
'#multiple' => TRUE,
];
+
$form['existing_depfile']['dep_upload'] = [
'#type' => 'item',
- '#value' => Link::fromTextAndUrl('Upload New Depedency Files', 'lab_migration/code/upload_dep'),
+ '#markup' => Link::fromTextAndUrl($this->t('Upload New Dependency Files'), Url::fromRoute('lab_migration.upload_dep'))->toString(),
];
/************ END OF EXISTING DEPENDENCIES **************/
+
$form['result'] = [
'#type' => 'fieldset',
- '#title' => t('Result Files'),
+ '#title' => $this->t('Result Files'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
];
+
$form['result']['result1'] = [
'#type' => 'file',
- '#title' => t('Upload result file'),
+ '#title' => $this->t('Upload result file'),
'#size' => 48,
- '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . $config->get('lab_migration_result_extensions', ''),
+ '#description' => $this->t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . $this->t('Allowed file extensions : ') . $config->get('lab_migration_result_extensions'),
];
+
$form['result']['result2'] = [
'#type' => 'file',
- '#title' => t('Upload result file'),
+ '#title' => $this->t('Upload result file'),
'#size' => 48,
- '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . $config->get('lab_migration_result_extensions', ''),
+ '#description' => $this->t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . $this->t('Allowed file extensions : ') . $config->get('lab_migration_result_extensions'),
];
+
$form['xcos'] = [
'#type' => 'fieldset',
- '#title' => t('XCOS Files'),
+ '#title' => $this->t('XCOS Files'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
];
+
$form['xcos']['xcos1'] = [
'#type' => 'file',
- '#title' => t('Upload xcos file'),
+ '#title' => $this->t('Upload xcos file'),
'#size' => 48,
- '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . $config->get('lab_migration_xcos_extensions', ''),
+ '#description' => $this->t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . $this->t('Allowed file extensions : ') . $config->get('lab_migration_xcos_extensions'),
];
+
$form['xcos']['xcos2'] = [
'#type' => 'file',
- '#title' => t('Upload xcos file'),
+ '#title' => $this->t('Upload xcos file'),
'#size' => 48,
- '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . $config->get('lab_migration_xcos_extensions', ''),
+ '#description' => $this->t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . $this->t('Allowed file extensions : ') . $config->get('lab_migration_xcos_extensions'),
];
-
+
$form['submit'] = [
- '#type' =>'submit',
- '#value' => t('Submit'),
+ '#type' => 'submit',
+ '#value' => $this->t('Submit'),
];
+
$form['cancel'] = [
'#type' => 'markup',
- '#value' => Link::fromTextAndUrl(t('Cancel'), 'lab_migration/code_approval/bulk'),
+ '#markup' => Link::fromTextAndUrl($this->t('Cancel'), Url::fromRoute('lab_migration.bulk_approval_form'))->toString(),
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if (!lab_migration_check_code_number($form_state->getValue(['code_number']))) {
- $form_state->setErrorByName('code_number', t('Invalid Code Number. Code Number can contain only numbers.'));
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (!$this->labGlobal->lab_migration_check_code_number($form_state->getValue('code_number'))) {
+ $form_state->setErrorByName('code_number', $this->t('Invalid Code Number. Code Number can contain only numbers.'));
}
- if (!lab_migration_check_name($form_state->getValue(['code_caption']))) {
- $form_state->setErrorByName('code_caption', t('Caption can contain only alphabets, numbers and spaces.'));
+
+ if (!$this->labGlobal->lab_migration_check_name($form_state->getValue('code_caption'))) {
+ $form_state->setErrorByName('code_caption', $this->t('Caption can contain only alphabets, numbers and spaces.'));
}
+
if (isset($_FILES['files'])) {
- /* check if atleast one source or result file is uploaded */
if (!($_FILES['files']['name']['sourcefile1'] || $_FILES['files']['name']['xcos1'])) {
- $form_state->setErrorByName('sourcefile1', t('Please upload atleast one main or source file or xcos file.'));
+ $form_state->setErrorByName('sourcefile1', $this->t('Please upload at least one main or source file or xcos file.'));
}
- /* check for valid filename extensions */
+
+ $config = $this->configFactory()->get('lab_migration.settings');
+
foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
if ($file_name) {
- /* checking file type */
if (strstr($file_form_name, 'source')) {
$file_type = 'S';
}
+ elseif (strstr($file_form_name, 'result')) {
+ $file_type = 'R';
+ }
+ elseif (strstr($file_form_name, 'xcos')) {
+ $file_type = 'X';
+ }
else {
- if (strstr($file_form_name, 'result')) {
- $file_type = 'R';
- }
- else {
- if (strstr($file_form_name, 'xcos')) {
- $file_type = 'X';
- }
- else {
- $file_type = 'U';
- }
- }
+ $file_type = 'U';
}
+
$allowed_extensions_str = '';
switch ($file_type) {
case 'S':
- $allowed_extensions_str = $config->get('lab_migration_source_extensions', '');
+ $allowed_extensions_str = $config->get('lab_migration_source_extensions');
break;
case 'R':
- $allowed_extensions_str = $config->get('lab_migration_result_extensions', '');
+ $allowed_extensions_str = $config->get('lab_migration_result_extensions');
break;
case 'X':
- $allowed_extensions_str = $config->get('lab_migration_xcos_extensions', '');
+ $allowed_extensions_str = $config->get('lab_migration_xcos_extensions');
break;
}
+
$allowed_extensions = explode(',', $allowed_extensions_str);
- $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name])));
+ $parts = explode('.', strtolower($_FILES['files']['name'][$file_form_name]));
+ $temp_extension = end($parts);
+
if (!in_array($temp_extension, $allowed_extensions)) {
- $form_state->setErrorByName($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.'));
+ $form_state->setErrorByName($file_form_name, $this->t('Only file with @ext extensions can be uploaded.', ['@ext' => $allowed_extensions_str]));
}
+
if ($_FILES['files']['size'][$file_form_name] <= 0) {
- $form_state->setErrorByName($file_form_name, t('File size cannot be zero.'));
+ $form_state->setErrorByName($file_form_name, $this->t('File size cannot be zero.'));
}
- /* check if valid file name */
- if (!lab_migration_check_valid_filename($_FILES['files']['name'][$file_form_name])) {
- $form_state->setErrorByName($file_form_name, t('Invalid file name specified. Only alphabets and numbers are allowed as a valid filename.'));
+
+ if (!$this->labGlobal->lab_migration_check_valid_filename($_FILES['files']['name'][$file_form_name])) {
+ $form_state->setErrorByName($file_form_name, $this->t('Invalid file name specified. Only alphabets and numbers are allowed as a valid filename.'));
}
}
}
}
- /* add javascript dependency selection effects */
- $dep_selection_js = "(function ($) {
- $('#edit-existing-depfile-dep-lab-title').change(function() {
- var dep_selected = '';
- /* showing and hiding relevant files */
- $('.form-checkboxes .option').hide();
- $('.form-checkboxes .option').each(function(index) {
- var activeClass = $('#edit-existing-depfile-dep-lab-title').va\Drupal\Core\Link;
- if ($(this).children().hasClass(activeClass)) {
- $(this).show();
- }
- if ($(this).children().attr('checked') == true) {
- dep_selected += $(this).children().next().text() + ' ';
- }
- });
- /* showing list of already existing dependencies */
- $('#existing_depfile_selected').html(dep_selected);
- });
-
- $('.form-checkboxes .option').change(function() {
- $('#edit-existing-depfile-dep-lab-title').trigger('change');
- });
- $('#edit-existing-depfile-dep-lab-title').trigger('change');
- }(jQuery));";
- #attached($dep_selection_js, 'inline', 'header');
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- $root_path = lab_migration_path();
- $proposal_id = (int) arg(3);
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = $injected_database->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('proposal_id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
if (!$proposal_data) {
- \Drupal::messenger()->addMessage("Invalid proposal selected", 'error');
- RedirectResponse('lab_migration/code_approval/upload/' . $proposal_id);
+ $this->messenger->addError($this->t("Invalid proposal selected"));
+ $form_state->setRedirect('lab_migration.bulk_approval_form');
+ return;
}
+
$proposal_id = $proposal_data->id;
- /************************ check experiment details ************************/
- $experiment_id = (int) $form_state->getValue(['experiment']);
- //$experiment_q = $injected_database->query("SELECT * FROM {lab_migration_experiment} WHERE id = %d AND proposal_id = %d LIMIT 1", $experiment_id, $proposal_id);
- $query = $injected_database->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $experiment_id);
- $query->condition('proposal_id', $proposal_id);
- $query->range(0, 1);
- $experiment_q = $query->execute();
- $experiment_data = $experiment_q->fetchObject();
+ $experiment_id = (int) $form_state->getValue('experiment');
+
+ $experiment_data = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('id', $experiment_id)
+ ->condition('proposal_id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
if (!$experiment_data) {
- \Drupal::messenger()->addMessage("Invalid experiment seleted", 'error');
- RedirectResponse('lab_migration/code_approval/upload/' . $proposal_id);
+ $this->messenger->addError($this->t("Invalid experiment selected"));
+ $form_state->setRedirect('lab_migration.bulk_approval_form');
+ return;
}
- /* create proposal folder if not present */
+
+ $root_path = $this->labGlobal->lab_migration_path();
$dest_path = $proposal_id . '/';
if (!is_dir($root_path . $dest_path)) {
mkdir($root_path . $dest_path);
}
- /* get solution details - dont allow if already solution present */
- // $cur_solution_q = $injected_database->query("SELECT * FROM {lab_migration_solution} WHERE experiment_id = %d AND code_number = '%s'", $experiment_id, $experiment_data->number . '.' . $form_state['values']['code_number']);
- $code_number = $experiment_data->number . '.' . $form_state->getValue(['code_number']);
- $query = $injected_database->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $experiment_id);
- $query->condition('code_number', $code_number);
- $cur_solution_q = $query->execute();
- if ($cur_solution_d = $cur_solution_q->fetchObject()) {
+
+ $code_number = $experiment_data->number . '.' . $form_state->getValue('code_number');
+ $cur_solution_d = $this->database->select('lab_migration_solution')
+ ->fields('lab_migration_solution')
+ ->condition('experiment_id', $experiment_id)
+ ->condition('code_number', $code_number)
+ ->execute()
+ ->fetchObject();
+
+ if ($cur_solution_d) {
if ($cur_solution_d->approval_status == 1) {
- \Drupal::messenger()->addMessage(t("Solution already approved. Cannot overwrite it."), 'error');
- RedirectResponse('lab_migration/code_approval/upload/' . $proposal_id);
+ $this->messenger->addError($this->t("Solution already approved. Cannot overwrite it."));
return;
}
else {
if ($cur_solution_d->approval_status == 0) {
- \Drupal::messenger()->addMessage(t("Solution is under pending review. Delete the solution and reupload it."), 'error');
- RedirectResponse('lab-migration/code-approval/upload/' . $proposal_id);
+ $this->messenger->addError($this->t("Solution is under pending review. Delete the solution and reupload it."));
return;
}
else {
- \Drupal::messenger()->addMessage(t("Error uploading solution. Please contact administrator."), 'error');
- RedirectResponse('lab-migration/code-approval/upload/' . $proposal_id);
+ $this->messenger->addError($this->t("Error uploading solution. Please contact administrator."));
return;
}
}
}
- /* creating experiment directories */
+
$dest_path .= 'EXP' . $experiment_data->number . '/';
if (!is_dir($root_path . $dest_path)) {
mkdir($root_path . $dest_path);
}
- /* creating code directories */
- $dest_path .= 'CODE' . $experiment_data->number . '.' . $form_state->getValue(['code_number']) . '/';
+
+ $dest_path .= 'CODE' . $experiment_data->number . '.' . $form_state->getValue('code_number') . '/';
if (!is_dir($root_path . $dest_path)) {
mkdir($root_path . $dest_path);
}
- /* creating solution database entry */
- $query = "INSERT INTO {lab_migration_solution} (experiment_id, approver_uid, code_number, caption, approval_date, approval_status, timestamp) VALUES (:experiment_id, :approver_uid, :code_number, :caption, :approval_date, :approval_status, :timestamp)";
- $args = [
- ":experiment_id" => $experiment_id,
- ":approver_uid" => 0,
- ":code_number" => $experiment_data->number . '.' . $form_state->getValue(['code_number']),
- ":caption" => $form_state->getValue(['code_caption']),
- ":approval_date" => 0,
- ":approval_status" => 0,
- ":timestamp" => time(),
- ];
- $solution_id = $injected_database->query($query, $args, [
- 'return' => Database::RETURN_INSERT_ID
- ]);
- /* linking existing dependencies */
- foreach ($form_state->getValue(['existing_depfile', 'dep_experiment_files']) as $row) {
- if ($row > 0) {
- /* insterting into database */
- $query = "INSERT INTO {lab_migration_solution_dependency} (solution_id, dependency_id)
- VALUES (:solution_id, :dependency_id)";
- $args = [
- ":solution_id" => $solution_id,
- ":dependency_id" => $row,
- ];
- $injected_database->query($query, $args);
+
+ $solution_id = $this->database->insert('lab_migration_solution')
+ ->fields([
+ 'experiment_id' => $experiment_id,
+ 'approver_uid' => 0,
+ 'code_number' => $code_number,
+ 'caption' => $form_state->getValue('code_caption'),
+ 'approval_date' => 0,
+ 'approval_status' => 0,
+ 'timestamp' => time(),
+ ])
+ ->execute();
+
+ if ($form_state->getValue(['existing_depfile', 'dep_experiment_files'])) {
+ foreach ($form_state->getValue(['existing_depfile', 'dep_experiment_files']) as $row) {
+ if ($row > 0) {
+ $this->database->insert('lab_migration_solution_dependency')
+ ->fields([
+ 'solution_id' => $solution_id,
+ 'dependency_id' => $row,
+ ])
+ ->execute();
+ }
}
}
- /* uploading files */
+
foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
if ($file_name) {
- /* checking file type */
if (strstr($file_form_name, 'source')) {
$file_type = 'S';
}
+ elseif (strstr($file_form_name, 'result')) {
+ $file_type = 'R';
+ }
+ elseif (strstr($file_form_name, 'xcos')) {
+ $file_type = 'X';
+ }
else {
- if (strstr($file_form_name, 'result')) {
- $file_type = 'R';
- }
- else {
- if (strstr($file_form_name, 'xcos')) {
- $file_type = 'X';
- }
- else {
- $file_type = 'U';
- }
- }
+ $file_type = 'U';
}
+
if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- \Drupal::messenger()->addMessage(t("Error uploading file. File !filename already exists.", [
- '!filename' => $_FILES['files']['name'][$file_form_name]
- ]), 'error');
+ $this->messenger->addError($this->t("Error uploading file. File @filename already exists.", ['@filename' => $_FILES['files']['name'][$file_form_name]]));
return;
}
- /* uploading file */
+
if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- /* for uploaded files making an entry in the database */
- $query = "INSERT INTO {lab_migration_solution_files} (solution_id, filename, filepath, filemime, filesize, filetype, timestamp)
- VALUES (:solution_id, :filename, :filepath, :filemime, :filesize, :filetype, :timestamp)";
- $args = [
- ":solution_id" => $solution_id,
- ":filename" => $_FILES['files']['name'][$file_form_name],
- ":filepath" => $dest_path . $_FILES['files']['name'][$file_form_name],
- ":filemime" => $_FILES['files']['type'][$file_form_name],
- ":filesize" => $_FILES['files']['size'][$file_form_name],
- ":filetype" => $file_type,
- ":timestamp" => time(),
- ];
- $injected_database->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' uploaded successfully.', 'status');
+ $this->database->insert('lab_migration_solution_files')
+ ->fields([
+ 'solution_id' => $solution_id,
+ 'filename' => $_FILES['files']['name'][$file_form_name],
+ 'filepath' => $dest_path . $_FILES['files']['name'][$file_form_name],
+ 'filemime' => $_FILES['files']['type'][$file_form_name],
+ 'filesize' => $_FILES['files']['size'][$file_form_name],
+ 'filetype' => $file_type,
+ 'timestamp' => time(),
+ ])
+ ->execute();
+ $this->messenger->addMessage($file_name . ' uploaded successfully.', 'status');
}
else {
- \Drupal::messenger()->addMessage('Error uploading file : ' . $dest_path . '/' . $file_name, 'error');
+ $this->messenger->addError($this->t('Error uploading file: @file', ['@file' => $dest_path . $file_name]));
}
}
}
- \Drupal::messenger()->addMessage('Solution uploaded successfully.', 'status'); /* sending email */
-
- $user_data = \Drupal::entityTypeManager()->getStorage('user')->load($proposal_data->uid);
-$email_to = $user_data->getEmail();
- $from = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
-$bcc = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
-$cc = \Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
-
- $param['solution_uploaded']['solution_id'] = $solution_id;
- $param['solution_uploaded']['user_id'] = $user->uid;
- $param['solution_uploaded']['headers'] = [ 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
-];
-
- $langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
- $mail_manager = \Drupal::service('plugin.manager.mail');
- if (!\Drupal::service('plugin.manager.mail')->mail('lab_migration', 'proposal_uploaded', $email_to, 'en', $params, $form, TRUE));
- { \Drupal::messenger()->addMessage('Mail sent successfully.');
+
+ $this->messenger->addMessage($this->t('Solution uploaded successfully.'));
+
+ $user_data = User::load($proposal_data->uid);
+ if ($user_data && $user_data->getEmail()) {
+ $email_to = $user_data->getEmail();
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $params['solution_uploaded']['solution_id'] = $solution_id;
+ $params['solution_uploaded']['user_id'] = $this->currentUser->id();
+ $params['solution_uploaded']['headers'] = [
+ 'From' => $from,
+ 'Cc' => $cc,
+ 'Bcc' => $bcc,
+ ];
+
+ if ($this->mailService->sendMail('lab_migration', 'solution_uploaded', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail notification sent successfully.'));
+ }
+ }
+
+ $form_state->setRedirect('lab_migration.bulk_approval_form');
}
+ /**
+ * Helper function to get approved lab titles.
+ */
+ protected function _list_of_lab_titles() {
+ $lab_titles = ['0' => $this->t('Please select...')];
+ $results = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p', ['id', 'lab_title', 'name'])
+ ->condition('approval_status', 3)
+ ->orderBy('lab_title', 'ASC')
+ ->execute();
+ foreach ($results as $row) {
+ $lab_titles[$row->id] = $row->lab_title . ' (Proposed by ' . $row->name . ')';
+ }
+ return $lab_titles;
+ }
- // if (!drupal_mail('lab_migration', 'solution_uploaded', $email_to, language_default(), $param, $from, TRUE)) {
- // add_message('Error sending email message.', 'error');
- // }
- RedirectResponse('lab-migration/code-approval/bulk/');
+ /**
+ * Helper function to get dependency files list.
+ */
+ protected function _list_of_dependency_files() {
+ $options = [];
+ $options_class = [];
+ $query = $this->database->select('lab_migration_dependency_files', 'd')
+ ->fields('d', ['id', 'filename', 'proposal_id'])
+ ->execute();
+ foreach ($query as $row) {
+ $options[$row->id] = $row->filename;
+ $options_class[$row->id] = [
+ 'class' => [$row->proposal_id],
+ ];
+ }
+ return [$options, $options_class];
}
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCategoryEditForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCategoryEditForm.php
index a9348bb..598b969 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCategoryEditForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCategoryEditForm.php
@@ -9,15 +9,82 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\Core\Link;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
-use Drupal\user\Entity\User;
-
+use Drupal\Core\Link;
class LabMigrationCategoryEditForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+
+ /**
+ * Constructs a new LabMigrationCategoryEditForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ EntityTypeManagerInterface $entity_type_manager,
+ RequestStack $request_stack,
+ LabMigrationGlobalfunction $lab_global
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->requestStack = $request_stack;
+ $this->labGlobal = $lab_global;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('entity_type.manager'),
+ $container->get('request_stack'),
+ $container->get('lab_migration_global')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -25,160 +92,123 @@ public function getFormId() {
return 'lab_migration_category_edit_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- /* get current proposal */
- // $proposal_id = (int) arg(4);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('id');
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query =\Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.category_edit_form')->toString());
-
-// Send the redirect response
-$response->send();
-
-
-// return new RedirectResponse('/lab-migration/manage-proposal/category');
- return;
- }
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ return $form;
}
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
-
-$response = new RedirectResponse(Url::fromRoute('lab_migration.category_edit_form')->toString());
-
-// Send the redirect response
-$response->send();
- return;
- }
$form['name'] = [
'#type' => 'item',
- '#markup' => Link::fromTextAndUrl($proposal_data->name_title . ' ' . $proposal_data->name,Url::fromRoute('entity.user.canonical', ['user' => $proposal_data->uid]))->toString(),
- '#attributes' => array('class' => array('form-control')),
-
- '#title' => t('Name'),
+ '#markup' => Link::fromTextAndUrl(
+ $proposal_data->name_title . ' ' . $proposal_data->name,
+ Url::fromRoute('entity.user.canonical', ['user' => $proposal_data->uid])
+ )->toString(),
+ '#attributes' => ['class' => ['form-control']],
+ '#title' => $this->t('Name'),
];
+
+ $proposal_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
$form['email_id'] = [
'#type' => 'item',
- // '#markup' => User::load($proposal_data->uid)->getEmail(),
- '#attributes' => array('class' => array('form-control')),
-
- '#title' => t('Email'),
+ '#markup' => $proposal_user ? $proposal_user->getEmail() : $this->t('Unknown'),
+ '#attributes' => ['class' => ['form-control']],
+ '#title' => $this->t('Email'),
];
+
$form['contact_ph'] = [
'#type' => 'item',
'#markup' => $proposal_data->contact_ph,
- '#attributes' => array('class' => array('form-control')),
-
- '#title' => t('Contact No.'),
+ '#attributes' => ['class' => ['form-control']],
+ '#title' => $this->t('Contact No.'),
];
+
$form['department'] = [
'#type' => 'item',
'#markup' => $proposal_data->department,
- '#attributes' => array('class' => array('form-control')),
-
- '#title' => t('Department/Branch'),
+ '#attributes' => ['class' => ['form-control']],
+ '#title' => $this->t('Department/Branch'),
];
+
$form['university'] = [
'#type' => 'item',
'#markup' => $proposal_data->university,
- '#attributes' => array('class' => array('form-control')),
-
- '#title' => t('University/Institute'),
+ '#attributes' => ['class' => ['form-control']],
+ '#title' => $this->t('University/Institute'),
];
$form['lab_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->lab_title,
- '#attributes' => array('class' => array('form-control')),
-
- '#title' => t('Title of the Lab'),
+ '#attributes' => ['class' => ['form-control']],
+ '#title' => $this->t('Title of the Lab'),
];
+
$form['category'] = [
'#type' => 'select',
- '#attributes' => array('class' => array('form-control')),
-
- '#title' => t('Category'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_departments(),
+ '#attributes' => ['class' => ['form-control']],
+ '#title' => $this->t('Category'),
+ '#options' => $this->labGlobal->_lm_list_of_departments(),
'#required' => TRUE,
'#default_value' => $proposal_data->category,
];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
+
$form['cancel'] = [
- '#type' => 'item',
- // '#markup' => Link::fromTextAndUrl(t('Cancel'), 'lab-migration/manage-proposal/category'),
+ '#type' => 'markup',
'#markup' => Link::fromTextAndUrl(
- $this->t('Cancel'),Url::fromRoute('lab_migration.category_all'))->toString(),
+ $this->t('Cancel'),
+ Url::fromRoute('lab_migration.category_all')
+ )->toString(),
];
+
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- /* get current proposal */
- // $proposal_id = (int) arg(4);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('id');
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.category_all')->toString());
-
- // Send the redirect response
- $response->send();
-
- return;
- }
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.category_all')->toString());
-
- // Send the redirect response
- $response->send();
-
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirect('lab_migration.category_all');
return;
}
- $query = "UPDATE {lab_migration_proposal} SET category = :category WHERE id = :proposal_id";
- $args = [
- ":category" => $form_state->getValue(['category']),
- ":proposal_id" => $proposal_data->id,
- ];
- $result = \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addmessage(t('Proposal Category Updated'), 'status');
- // RedirectResponse('lab-migration/manage-proposal/category');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.category_all')->toString());
-
- // Send the redirect response
- $response->send();
+ $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'category' => $form_state->getValue('category'),
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Proposal Category Updated'), 'status');
+ $form_state->setRedirect('lab_migration.category_all');
}
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCodeApprovalForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCodeApprovalForm.php
index a370469..42f2216 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCodeApprovalForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationCodeApprovalForm.php
@@ -7,19 +7,106 @@
namespace Drupal\lab_migration\Form;
+use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Symfony\Component\HttpFoundation\Response;
-use Drupal\user\Entity\User;
use Drupal\Core\Link;
-use Drupal\Core\Config\ConfigFactoryInterface;
-use Drupal\Core\Form\FormBase;
-
class LabMigrationCodeApprovalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * Constructs a new LabMigrationCodeApprovalForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ RequestStack $request_stack,
+ LabMigrationGlobalfunction $lab_global,
+ MailService $mail_service
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->requestStack = $request_stack;
+ $this->labGlobal = $lab_global;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('request_stack'),
+ $container->get('lab_migration_global'),
+ $container->get('lab_migration.mail_service')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -27,346 +114,274 @@ public function getFormId() {
return 'lab_migration_code_approval_form';
}
- public function buildForm(array $form,FormStateInterface $form_state) {
- // $solution_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
- $solution_id = (int) $route_match->getParameter('solution_id');
- /* get solution details */
- //$solution_q = \Drupal::database()->query("SELECT * FROM {lab_migration_solution} WHERE id = %d", $solution_id);
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $solution_id);
- $solution_q = $query->execute();
- $solution_data = $solution_q->fetchObject();
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $solution_id = $route_match ? (int) $route_match->getParameter('solution_id') : 0;
+
+ $solution_data = $this->database->select('lab_migration_solution')
+ ->fields('lab_migration_solution')
+ ->condition('id', $solution_id)
+ ->execute()
+ ->fetchObject();
+
if (!$solution_data) {
- \Drupal::messenger()->addmessage(t('Invalid solution selected.'), 'status');
- // drupal_goto('lab-migration/code-approval');
- $url = Url::fromRoute('lab_migration.code_approval')->toString(); // Replace with the actual route name
- $response = new RedirectResponse($url);
+ $this->messenger->addMessage($this->t('Invalid solution selected.'), 'status');
+ return $form;
}
+
if ($solution_data->approval_status == 1) {
- \Drupal::messenger()->addmessage(t('This solution has already been approved. Are you sure you want to change the approval status?'), 'error');
+ $this->messenger->addMessage($this->t('This solution has already been approved. Are you sure you want to change the approval status?'), 'error');
}
if ($solution_data->approval_status == 2) {
- \Drupal::messenger()->addmessage(t('This solution has already been dis-approved. Are you sure you want to change the approval status?'), 'error');
- }
- /* get experiment data */
- //xperiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE id = %d", $solution_data->experiment_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_data->experiment_id);
- $experiment_q = $query->execute();
- $experiment_data = $experiment_q->fetchObject();
- /* get proposal data */
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $experiment_data->proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $experiment_data->proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- /* get solution provider details */
- $solution_provider_user_name = '';
- $user_data = User::load($proposal_data->solution_provider_uid);
- if ($user_data) {
- $solution_provider_user_name = $user_data->name;
- }
- else {
- $solution_provider_user_name = '';
+ $this->messenger->addMessage($this->t('This solution has already been dis-approved. Are you sure you want to change the approval status?'), 'error');
}
+
+ $experiment_data = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('id', $solution_data->experiment_id)
+ ->execute()
+ ->fetchObject();
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $experiment_data->proposal_id)
+ ->execute()
+ ->fetchObject();
+
$form['#tree'] = TRUE;
+
$form['lab_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->lab_title,
- '#title' => t('Title of the Lab'),
+ '#title' => $this->t('Title of the Lab'),
];
+
$form['name'] = [
'#type' => 'item',
'#markup' => $proposal_data->name,
- '#title' => t('Contributor Name'),
+ '#title' => $this->t('Contributor Name'),
];
+
$form['experiment']['number'] = [
'#type' => 'item',
'#markup' => $experiment_data->number,
- '#title' => t('Experiment Number'),
+ '#title' => $this->t('Experiment Number'),
];
+
$form['experiment']['title'] = [
'#type' => 'item',
'#markup' => $experiment_data->title,
- '#title' => t('Title of the Experiment'),
+ '#title' => $this->t('Title of the Experiment'),
];
-
+
$form['back_to_list'] = [
'#type' => 'item',
- '#markup' => Link::fromTextAndUrl($this->t('Back to Code Approval List'),
- Url::fromRoute('lab_migration.code_approval')
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Back to Code Approval List'),
+ Url::fromRoute('lab_migration.code_approval')
)->toString(),
- ];
+ ];
+
$form['code_number'] = [
'#type' => 'item',
'#markup' => $solution_data->code_number,
- '#title' => t('Code No'),
+ '#title' => $this->t('Code No'),
];
+
$form['code_caption'] = [
'#type' => 'item',
'#markup' => $solution_data->caption,
- '#title' => t('Caption'),
+ '#title' => $this->t('Caption'),
];
- /* get solution files */
- /* get solution files */
-$solution_files_html = '';
-
-$query = \Drupal::database()->select('lab_migration_solution_files', 'lmsf');
-$query->fields('lmsf');
-$query->condition('solution_id', $solution_id);
-$query->orderBy('id', 'ASC');
-$solution_files_q = $query->execute();
-
-if ($solution_files_q) {
- while ($solution_files_data = $solution_files_q->fetchObject()) {
- $filetype_map = [
- 'S' => 'Source',
- 'R' => 'Result',
- 'X' => 'Xcox',
- 'U' => 'Unknown',
- ];
-
- $code_file_type = $filetype_map[$solution_files_data->filetype] ?? 'Unknown';
- $url = Url::fromUri('internal:/lab-migration/download/solution/' . $solution_files_data->id);
+ $solution_files_html = '';
+ $solution_files_q = $this->database->select('lab_migration_solution_files', 'lmsf')
+ ->fields('lmsf')
+ ->condition('solution_id', $solution_id)
+ ->orderBy('id', 'ASC')
+ ->execute();
+
+ if ($solution_files_q) {
+ $filetype_map = [
+ 'S' => 'Source',
+ 'R' => 'Result',
+ 'X' => 'Xcox',
+ 'U' => 'Unknown',
+ ];
+ while ($solution_files_data = $solution_files_q->fetchObject()) {
+ $code_file_type = $filetype_map[$solution_files_data->filetype] ?? 'Unknown';
+ $url = Url::fromUri('internal:/lab-migration/download/solution/' . $solution_files_data->id);
+ $link = Link::fromTextAndUrl($solution_files_data->filename, $url)->toString();
+ $solution_files_html .= $link . ' (' . $code_file_type . ') ';
+ }
+ }
- $link = Link::fromTextAndUrl($solution_files_data->filename, $url)->toString();
+ $form['solution_files'] = [
+ '#type' => 'item',
+ '#markup' => $solution_files_html ?: 'No files uploaded. ',
+ '#title' => $this->t('Solution Files'),
+ ];
- $solution_files_html .= $link . ' (' . $code_file_type . ') ';
- }
-}
-
-$form['solution_files'] = [
- '#type' => 'item',
- '#markup' => $solution_files_html ?: 'No files uploaded. ',
- '#title' => t('Solution Files'),
-];
-$form['approved'] = [
+ $form['approved'] = [
'#type' => 'radios',
'#options' => [
'0' => 'Pending',
'1' => 'Approved',
'2' => 'Dis-approved (Solution will be deleted)',
],
- '#title' => t('Approval'),
+ '#title' => $this->t('Approval'),
'#default_value' => $solution_data->approval_status,
];
+
$form['message'] = [
'#type' => 'textarea',
- '#title' => t('Reason for dis-approval'),
+ '#title' => $this->t('Reason for dis-approval'),
];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
+
$form['cancel'] = [
'#type' => 'markup',
- //'#markup' => l(t('Cancel'), 'lab_migration/code_approval'),
- '#markup' => Link::fromTextAndUrl( $this->t('Cancel'),Url::fromRoute('lab_migration.code_approval'))->toString(),
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Cancel'),
+ Url::fromRoute('lab_migration.code_approval')
+ )->toString(),
];
+
return $form;
}
-
+ /**
+ * {@inheritdoc}
+ */
public function validateForm(array &$form, FormStateInterface $form_state) {
- if ($form_state->getValue(['approved']) == 2) {
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- $form_state->setErrorByName('message', t('Please mention the reason for disapproval.'));
+ if ($form_state->getValue('approved') == 2) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $form_state->setErrorByName('message', $this->t('Please mention the reason for disapproval.'));
}
}
- return;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- // $solution_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
- $solution_id = (int) $route_match->getParameter('solution_id');
- /* get solution details */
- //$solution_q = \Drupal::database()->query("SELECT * FROM {lab_migration_solution} WHERE id = %d", $solution_id);
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $solution_id);
- $solution_q = $query->execute();
- $solution_data = $solution_q->fetchObject();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $solution_id = $route_match ? (int) $route_match->getParameter('solution_id') : 0;
+
+ $solution_data = $this->database->select('lab_migration_solution')
+ ->fields('lab_migration_solution')
+ ->condition('id', $solution_id)
+ ->execute()
+ ->fetchObject();
+
if (!$solution_data) {
- \Drupal::messenger()->addmessage(t('Invalid solution selected.'), 'status');
- // drupal_goto('lab_migration/code_approval');
- $url = '/lab-migration/code-approval/bulk'; // Path relative to the site's base URL.
- return new RedirectResponse($url);
+ $this->messenger->addMessage($this->t('Invalid solution selected.'), 'status');
+ $form_state->setRedirect('lab_migration.code_approval');
+ return;
}
- /* get experiment data */
- //$experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE id = %d", $solution_data->experiment_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_data->experiment_id);
- $experiment_q = $query->execute();
- $experiment_data = $experiment_q->fetchObject();
- /* get proposal data */
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $experiment_data->proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $experiment_data->proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- $user_data = User::load($proposal_data->uid);
-
- $approver_uid = $user->id();
- $solution_prove_user_data = User::load($proposal_data->solution_provider_uid);
- // **** TODO **** : del_lab_pdf($proposal_data->id);
- if ($form_state->getValue(['approved']) == "0") {
- $query = "UPDATE {lab_migration_solution} SET approval_status = 0, approver_uid = :approver_uid, approval_date = :approval_date WHERE id = :solution_id";
- $args = [
- ":approver_uid" => $user->id(),
- ":approval_date" => time(),
- ":solution_id" => $solution_id,
- ];
- \Drupal::database()->query($query, $args);
- /* sending email */
- // $email_to = $user_data->mail;
- // $from = $config->get('lab_migration_from_email', '');
- // $bcc = $config->get('lab_migration_emails', '');
- // $cc = $config->get('lab_migration_cc_emails', '');
- // $param['solution_pending']['solution_id'] = $solution_id;
- // $param['solution_pending']['user_id'] = $user_data->uid;
- // $param['solution_pending']['headers'] = [
- // 'From' => $from,
- // 'MIME-Version' => '1.0',
- // 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- // 'Content-Transfer-Encoding' => '8Bit',
- // 'X-Mailer' => 'Drupal',
- // 'Cc' => $cc,
- // 'Bcc' => $bcc,
- // ];
- // if (!drupal_mail('lab_migration', 'solution_pending', $email_to, language_default(), $param, $from, TRUE)) {
- // \Drupal::messenger()->addmessage('Error sending email message.', 'error');
- // }
+
+ $experiment_data = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('id', $solution_data->experiment_id)
+ ->execute()
+ ->fetchObject();
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $experiment_data->proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+
+ if ($form_state->getValue('approved') == "0") {
+ $this->database->update('lab_migration_solution')
+ ->fields([
+ 'approval_status' => 0,
+ 'approver_uid' => $this->currentUser->id(),
+ 'approval_date' => time(),
+ ])
+ ->condition('id', $solution_id)
+ ->execute();
}
- else {
- if ($form_state->getValue(['approved']) == "1") {
- $query = "UPDATE {lab_migration_solution} SET approval_status = 1, approver_uid = :approver_uid, approval_date = :approval_date WHERE id = :solution_id";
- $args = [
- ":approver_uid" => $user->id(),
- ":approval_date" => time(),
- ":solution_id" => $solution_id,
+ elseif ($form_state->getValue('approved') == "1") {
+ $this->database->update('lab_migration_solution')
+ ->fields([
+ 'approval_status' => 1,
+ 'approver_uid' => $this->currentUser->id(),
+ 'approval_date' => time(),
+ ])
+ ->condition('id', $solution_id)
+ ->execute();
+
+ if ($user_data) {
+ $email_to = $user_data->getEmail();
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $param['solution_approved'] = [
+ 'solution_id' => $solution_id,
+ 'user_id' => $user_data->id(),
+ 'headers' => [
+ 'From' => $from,
+ 'Cc' => is_array($cc) ? implode(',', $cc) : $cc,
+ 'Bcc' => is_array($bcc) ? implode(',', $bcc) : $bcc,
+ ],
];
- \Drupal::database()->query($query, $args);
- /* sending email */
-$email_to = $user_data->getEmail(); // Drupal 10 method
-
-// Get config values
-$from = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
-$bcc = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
-$cc = \Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
-
-// Prepare mail parameters
-$param['solution_approved'] = [
- 'solution_id' => $solution_id,
- 'user_id' => $user_data->id(),
- 'headers' => [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => is_array($cc) ? implode(',', $cc) : $cc,
- 'Bcc' => is_array($bcc) ? implode(',', $bcc) : $bcc,
- ],
-];
-
-// Language code
-$langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
-
-// Send mail
-$mail_manager = \Drupal::service('plugin.manager.mail');
-$result = $mail_manager->mail(
- 'lab_migration', // Module name
- 'solution_approved', // Mail key
- $email_to, // Recipient
- $langcode, // Language
- $param, // Parameters
- NULL, // Reply-to
- TRUE // Send immediately
-);
-
-// Error handling
-if (!$result['result']) {
- \Drupal::messenger()->addMessage('Mail sent successfully.');
-}
+
+ if ($this->mailService->sendMail('lab_migration', 'solution_approved', $email_to, $param)) {
+ $this->messenger->addMessage($this->t('Mail sent successfully.'));
+ }
}
- else {
- if ($form_state->getValue(['approved']) == "2") {
- if (\Drupal::service("lab_migration_global")->lab_migration_delete_solution($solution_id)) {
- /* sending email */
-
-// Recipient email
-$email_to = $user_data->getEmail();
-
-// Mail configuration
-$from = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
-$bcc = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
-$cc = \Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
-
-// Prepare mail parameters
-$params = [
- 'solution_id' => $proposal_data->id,
- 'experiment_number' => $experiment_data->number,
- 'experiment_title' => $experiment_data->title,
- 'solution_number' => $solution_data->code_number,
- 'solution_caption' => $solution_data->caption,
- 'user_id' => $user_data->id(),
- 'message' => $form_state->getValue(['message']),
- 'headers' => [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => is_array($cc) ? implode(',', $cc) : $cc,
- 'Bcc' => is_array($bcc) ? implode(',', $bcc) : $bcc,
- ],
-];
-
-// Language code
-$langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
-
-// Send mail
-$mail_manager = \Drupal::service('plugin.manager.mail');
-$result = $mail_manager->mail(
- 'lab_migration',
- 'solution_disapproved',
- $email_to,
- $langcode,
- $params
-);
-
-// Error handling
-if ($result['result']) {
- \Drupal::messenger()->addMessage('Mail sent successfully.');
-} else {
- \Drupal::messenger()->addError('Mail sending failed.');
-}
- }
+ }
+ elseif ($form_state->getValue('approved') == "2") {
+ if ($this->labGlobal->lab_migration_delete_solution($solution_id)) {
+ if ($user_data) {
+ $email_to = $user_data->getEmail();
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $params = [
+ 'solution_id' => $proposal_data->id,
+ 'experiment_number' => $experiment_data->number,
+ 'experiment_title' => $experiment_data->title,
+ 'solution_number' => $solution_data->code_number,
+ 'solution_caption' => $solution_data->caption,
+ 'user_id' => $user_data->id(),
+ 'message' => $form_state->getValue('message'),
+ 'headers' => [
+ 'From' => $from,
+ 'Cc' => is_array($cc) ? implode(',', $cc) : $cc,
+ 'Bcc' => is_array($bcc) ? implode(',', $bcc) : $bcc,
+ ],
+ ];
+
+ if ($this->mailService->sendMail('lab_migration', 'solution_disapproved', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail sent successfully.'));
+ }
else {
- \Drupal::messenger()->addError('Error disapproving and deleting solution. Please contact administrator.', 'error');
+ $this->messenger->addError($this->t('Mail sending failed.'));
}
}
}
+ else {
+ $this->messenger->addError($this->t('Error disapproving and deleting solution. Please contact administrator.'));
+ }
}
- \Drupal::messenger()->addmessage('Updated successfully.', 'status');
- // RedirectResponse('lab-migration/code-approval');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.code_approval')->toString());
-
- // Send the redirect response
- $response->send();
-
+
+ $this->messenger->addMessage($this->t('Updated successfully.'), 'status');
+ $form_state->setRedirect('lab_migration.code_approval');
}
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationLabNotesForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationLabNotesForm.php
index ce94aaa..e5f4922 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationLabNotesForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationLabNotesForm.php
@@ -9,10 +9,60 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\Core\Url;
+use Drupal\Core\Link;
class LabMigrationLabNotesForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * Constructs a new LabMigrationLabNotesForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ RequestStack $request_stack
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->requestStack = $request_stack;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('request_stack')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,99 +70,128 @@ public function getFormId() {
return 'lab_migration_lab_notes_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $proposal_id = (int) arg(3);
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d LIMIT 1", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $query->range(0, 1);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = 0;
+ if ($route_match) {
+ $proposal_id = (int) $route_match->getParameter('proposal_id');
+ if (!$proposal_id) {
+ $proposal_id = (int) $route_match->getParameter('id');
+ }
+ }
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
if (!$proposal_data) {
- \Drupal::messenger()->addmesssage(t('Invalid lab selected. Please try again.'), 'error');
- drupal_goto('lab-migration/code-approval');
- return;
+ $this->messenger->addError($this->t('Invalid lab selected. Please try again.'));
+ // In buildForm we cannot use $form_state->setRedirect. We return the empty form or let it return.
+ return $form;
}
+
/* get current notes */
$notes = '';
- //$notes_q = \Drupal::database()->query("SELECT * FROM {lab_migration_notes} WHERE proposal_id = %d LIMIT 1", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_notes');
- $query->fields('lab_migration_notes');
- $query->condition('proposal_id', $proposal_id);
- $query->range(0, 1);
- $notes_q = $query->execute();
- if ($notes_q) {
- $notes_data = $notes_q->fetchObject();
+ $notes_data = $this->database->select('lab_migration_notes')
+ ->fields('lab_migration_notes')
+ ->condition('proposal_id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if ($notes_data) {
$notes = $notes_data->notes;
}
+
$form['lab_details'] = [
'#type' => 'item',
- '#value' => 'About the Lab ' . 'Proposer: ' . $proposal_data->name . ' ' . 'Title of the Lab: ' . $proposal_data->lab_title . ' ',
+ '#markup' => 'About the Lab ' . 'Proposer: ' . htmlspecialchars($proposal_data->name) . ' ' . 'Title of the Lab: ' . htmlspecialchars($proposal_data->lab_title) . ' ',
];
+
$form['notes'] = [
'#type' => 'textarea',
'#rows' => 20,
- '#title' => t('Notes for Reviewers'),
+ '#title' => $this->t('Notes for Reviewers'),
'#default_value' => $notes,
];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
+
$form['cancel'] = [
'#type' => 'markup',
- '#value' => l(t('Back'), 'lab-migration/code-approval'),
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Back'),
+ Url::fromRoute('lab_migration.code_approval')
+ )->toString(),
];
+
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $proposal_id = (int) arg(3);
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d LIMIT 1", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $query->range(0, 1);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = 0;
+ if ($route_match) {
+ $proposal_id = (int) $route_match->getParameter('proposal_id');
+ if (!$proposal_id) {
+ $proposal_id = (int) $route_match->getParameter('id');
+ }
+ }
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
if (!$proposal_data) {
- \Drupal::messenger()->addmesssage(t('Invalid lab selected. Please try again.'), 'error');
- drupal_goto('lab-migration/code-approval');
+ $this->messenger->addError($this->t('Invalid lab selected. Please try again.'));
+ $form_state->setRedirect('lab_migration.code_approval');
return;
}
- /* find existing notes */
- //$notes_q = \Drupal::database()->query("SELECT * FROM {lab_migration_notes} WHERE proposal_id = %d LIMIT 1", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_notes');
- $query->fields('lab_migration_notes');
- $query->condition('proposal_id', $proposal_id);
- $query->range(0, 1);
- $notes_q = $query->execute();
- $notes_data = $notes_q->fetchObject();
- /* add or update notes in database */
+
+ $notes_data = $this->database->select('lab_migration_notes')
+ ->fields('lab_migration_notes')
+ ->condition('proposal_id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
if ($notes_data) {
- $query = "UPDATE {lab_migration_notes} SET notes = :notes WHERE id = :notes_id";
- $args = [
- ":notes" => $form_state->getValue(['notes']),
- ":notes_id" => $notes_data->id,
- ];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addmesssage('Notes updated successfully.', 'status');
+ $this->database->update('lab_migration_notes')
+ ->fields([
+ 'notes' => $form_state->getValue('notes'),
+ ])
+ ->condition('id', $notes_data->id)
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Notes updated successfully.'));
}
else {
- $query = "INSERT INTO {lab_migration_notes} (proposal_id, notes) VALUES (:proposal_id, :notes)";
- $args = [
- ":proposal_id" => $proposal_id,
- ":notes" => $form_state->getValue(['notes']),
- ];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addmesssage('Notes added successfully.', 'status');
+ $this->database->insert('lab_migration_notes')
+ ->fields([
+ 'proposal_id' => $proposal_id,
+ 'notes' => $form_state->getValue('notes'),
+ ])
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Notes added successfully.'));
}
+
+ $form_state->setRedirect('lab_migration.code_approval');
}
}
-?>
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalApprovalForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalApprovalForm.php
index 7ded62e..b3150f6 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalApprovalForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalApprovalForm.php
@@ -9,20 +9,94 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\user\Entity\User;
-use Symfony\Component\HttpFoundation\Response;
-use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\Config\ConfigFactoryInterface;
-use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\DependencyInjection\ContainerInterface;
-use Drupal\Core\Session\AccountProxy;
class LabMigrationProposalApprovalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * Constructs a new LabMigrationProposalApprovalForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ RequestStack $request_stack,
+ MailService $mail_service
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->requestStack = $request_stack;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('request_stack'),
+ $container->get('lab_migration.mail_service')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -30,360 +104,281 @@ public function getFormId() {
return 'lab_migration_proposal_approval_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('id');
-// var_dump($proposal_id);die;
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $url = Url::fromRoute('lab_migration.proposal_approval_form')->toString();
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
- return;
- }
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ return $form;
}
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration.manage-proposal_approve');
-
- $url = Url::fromRoute('lab_migration.proposal_approval_form')->toString();
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
- return;
- }
- // var_dump($proposal_data->name_title);
- // die;
$form['name'] = [
'#type' => 'item',
- // '#markup' => Link::fromTextAndUrl($proposal_data->name_title . ' ' . $proposal_data->name, 'user/' . $proposal_data->uid),
'#markup' => Link::fromTextAndUrl(
- $proposal_data->name_title . ' ' . $proposal_data->name,
- Url::fromUserInput('/user/' . $proposal_data->uid)
-)->toString(),
- '#title' => t('Name'),
-
+ $proposal_data->name_title . ' ' . $proposal_data->name,
+ Url::fromUserInput('/user/' . $proposal_data->uid)
+ )->toString(),
+ '#title' => $this->t('Name'),
];
+
+ $proposal_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
$form['email_id'] = [
'#type' => 'item',
- // '#markup' => loadMultiple($proposal_data->uid)->mail,
- // '#markup' => User::load($proposal_data->uid)->getEmail(),
- '#markup' => \Drupal\user\Entity\User::load($proposal_data->uid)->getEmail(),
-
- '#title' => t('Email'),
+ '#markup' => $proposal_user ? $proposal_user->getEmail() : $this->t('Unknown'),
+ '#title' => $this->t('Email'),
];
+
$form['contact_ph'] = [
'#type' => 'item',
'#markup' => $proposal_data->contact_ph,
- '#title' => t('Contact No.'),
+ '#title' => $this->t('Contact No.'),
];
+
$form['department'] = [
'#type' => 'item',
'#markup' => $proposal_data->department,
- '#title' => t('Department/Branch'),
+ '#title' => $this->t('Department/Branch'),
];
+
$form['university'] = [
'#type' => 'item',
'#markup' => $proposal_data->university,
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
];
+
$form['country'] = [
'#type' => 'item',
'#markup' => $proposal_data->country,
- '#title' => t('Country'),
+ '#title' => $this->t('Country'),
];
+
$form['all_state'] = [
'#type' => 'item',
'#markup' => $proposal_data->state,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
];
+
$form['city'] = [
'#type' => 'item',
'#markup' => $proposal_data->city,
- '#title' => t('City'),
+ '#title' => $this->t('City'),
];
+
$form['pincode'] = [
'#type' => 'item',
'#markup' => $proposal_data->pincode,
- '#title' => t('Pincode/Postal code'),
+ '#title' => $this->t('Pincode/Postal code'),
];
- // $form['operating_system'] = [
- // '#type' => 'item',
- // '#markup' => $proposal_data->operating_system,
- // '#title' => t('Operating System'),
- // ];
- // $form['version'] = [
- // '#type' => 'item',
- // // '#markup' => $proposal_data->version,
- // '#markup' => isset($proposal_data->version) ? $proposal_data->version : $this->t('Not available'),
- // '#title' =>$this-> t('Version'),
- // ];
- // $form['syllabus_link'] = [
- // '#type' => 'item',
- // '#markup' => $proposal_data->syllabus_link,
- // '#title' => t('Syllabus Link'),
- // ];
+
$form['lab_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->lab_title,
- '#title' => t('Title of the Lab'),
+ '#title' => $this->t('Title of the Lab'),
];
+
/* get experiment details */
$experiment_list = '';
- //$experiment_q = $injected_database->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY id ASC", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('id', 'ASC');
- $experiment_q = $query->execute();
+ $experiment_q = $this->database->select('lab_migration_experiment', 'e')
+ ->fields('e')
+ ->condition('proposal_id', $proposal_id)
+ ->orderBy('id', 'ASC')
+ ->execute();
+
while ($experiment_data = $experiment_q->fetchObject()) {
- $experiment_list .= '' . $experiment_data->title . ' Description of Experiment : ' . $experiment_data->description . ' ';
+ $experiment_list .= '' . htmlspecialchars($experiment_data->title) . ' Description of Experiment : ' . htmlspecialchars($experiment_data->description) . ' ';
}
$experiment_list .= ' ';
+
$form['experiment'] = [
'#type' => 'item',
'#markup' => $experiment_list,
- '#title' => t('Experiments'),
+ '#title' => $this->t('Experiments'),
];
-// if ($proposal_data->syllabus_copy_file_path != "None") {
-// $form['syllabus_copy_file_path'] = [
-// '#type' => 'item',
-// // '#markup' => Link::fromTextAndUrl(t('Click here to download uploaded syllabus copy'), 'lab-migration/download/syllabus-copy-file/' . $proposal_id,$Url) ,
-// '#markup' => Link::fromTextAndUrl(
-// $this->t('Click here to download uploaded syllabus copy'),
-// Url::fromUri('internal:/lab-migration/download/syllabus-copy-file/' . $proposal_id)
-// )->toString(),
-// // var_dump( $proposal_id );die;
-// ];
-// } //$row->samplefilepath != "None"
+
if ($proposal_data->solution_provider_uid == 0) {
- $solution_provider = "User will not provide solution, we will have to provide solution";
+ $solution_provider = $this->t("User will not provide solution, we will have to provide solution");
}
else {
if ($proposal_data->solution_provider_uid == $proposal_data->uid) {
- $solution_provider = "Proposer will provide the solution of the lab";
+ $solution_provider = $this->t("Proposer will provide the solution of the lab");
}
else {
- $solution_provider_user_data = User::load($proposal_data->solution_provider_uid);
- if ($solution_provider_user_data) {
- $solution_provider = "Solution will be provided by user " . Link::fromTextAndUrl($solution_provider_user_data->name, 'user/' . $proposal_data->solution_provider_uid);
+ $sol_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->solution_provider_uid);
+ if ($sol_user) {
+ $solution_provider = $this->t("Solution will be provided by user @user", ['@user' => $sol_user->getDisplayName()]);
}
else {
- $solution_provider = "User does not exists";
+ $solution_provider = $this->t("User does not exist");
}
}
}
+
$form['solution_provider_uid'] = [
'#type' => 'item',
- '#title' => t('Do you want to provide the solution'),
+ '#title' => $this->t('Do you want to provide the solution'),
'#markup' => $solution_provider,
];
- /* $form['solution_display'] = array(
- '#type' => 'item',
- '#title' => t('Do you want to display the solution on the www.r.fossee.in website'),
- '#markup' => ($proposal_data->solution_display == 1) ? "Yes" : "No",
- );*/
+
$form['approval'] = [
'#type' => 'radios',
- '#title' => t('Lab migration proposal'),
+ '#title' => $this->t('Lab migration proposal'),
'#options' => [
- '1' => 'Approve',
- '2' => 'Disapprove',
+ '1' => $this->t('Approve'),
+ '2' => $this->t('Disapprove'),
],
'#required' => TRUE,
];
+
$form['message'] = [
'#type' => 'textarea',
- '#title' => t('Reason for disapproval'),
+ '#title' => $this->t('Reason for disapproval'),
'#attributes' => [
- 'placeholder' => t('Enter reason for disapproval in minimum 30 characters '),
+ 'placeholder' => $this->t('Enter reason for disapproval in minimum 30 characters'),
'cols' => 50,
'rows' => 4,
],
'#states' => [
'visible' => [
':input[name="approval"]' => [
- 'value' => '2'
- ]
- ]
+ 'value' => '2',
+ ],
],
+ ],
];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
-
+
$form['cancel'] = [
'#type' => 'markup',
- // '#markup' =>Link::fromTextAndUrl(t('Cancel'), 'lab-migration/manage-proposal'),
'#markup' => Link::fromTextAndUrl(
- $this->t('Cancel'),
- Url::fromUri('internal:/lab-migration/manage-proposal/pending'))->toString(),
-
+ $this->t('Cancel'),
+ Url::fromUri('internal:/lab-migration/manage-proposal/pending')
+ )->toString(),
];
- return $form;
- // var_dump(t('Cancel'), 'lab-migration/manage-proposal');die;
+ return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if ($form_state->getValue(['approval']) == 2) {
- if ($form_state->getValue(['message']) == '') {
- $form_state->setErrorByName('message', t('Reason for disapproval could not be empty'));
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if ($form_state->getValue('approval') == 2) {
+ if (trim($form_state->getValue('message')) == '') {
+ $form_state->setErrorByName('message', $this->t('Reason for disapproval cannot be empty.'));
}
}
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- // $user = \Drupal::currentUser();
- $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
- $proposal_id = (int) $route_match->getParameter('id');
- // $proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $url = Url::fromRoute('lab_migration.manage_proposal_approve')->toString();
-
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
-
- return;
- }
- }
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $url = Url::fromRoute('lab_migration.manage_proposal_approve')->toString();
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
-
- return;
- }
- if ($form_state->getValue(['approval']) == 1) {
-
- $query = "UPDATE {lab_migration_proposal} SET approver_uid = :uid, approval_date = :date, approval_status = 1, solution_status = 2 WHERE id = :proposal_id";
- $args = [
-
-'uid' => $user->get('uid')->value,
-
- // ":uid" =>\Drupal::currentUser(),
- ":date" => time(),
- ":proposal_id" => $proposal_id,
- ];
- \Drupal::database()->query($query, $args);
- /* sending email */
-$config = \Drupal::config('lab_migration.settings');
-
- $user_data = \Drupal::entityTypeManager()->getStorage('user')->load($proposal_data->uid);
-$email_to = $user_data->getEmail();
- $from = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
-$bcc = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
-$cc = \Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
-
-$params['proposal_approved']['proposal_id'] = $proposal_id;
-$params['proposal_approved']['user_id'] = $proposal_data->uid;
-
-$params['proposal_approved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
-];
-
- $langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
- $mail_manager = \Drupal::service('plugin.manager.mail');
- if (!\Drupal::service('plugin.manager.mail')->mail('lab_migration', 'proposal_approved', $email_to, 'en', $params, $form, TRUE));
- { \Drupal::messenger()->addMessage('Mail sent successfully.');
- }
-
-
-
- // \Drupal::messenger()->add_message('Lab migration proposal No. ' . $proposal_id . ' approved. User has been notified of the approval.', 'status');
- \Drupal::messenger()->addMessage('Lab migration proposal No. ' . $proposal_id . ' approved. User has been notified of the approval.', 'status');
- // RedirectResponse('lab-migration/manage-proposal');
- $url = Url::fromRoute('lab_migration.proposal_pending')->toString();
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirect('lab_migration.proposal_pending');
return;
- // var_dump($proposal_id);die;
}
- else {
- if ($form_state->getValue(['approval']) == 2) {
- $query = "UPDATE {lab_migration_proposal} SET approver_uid = :uid, approval_date = :date, approval_status = 2, message = :message, solution_provider_uid = 0, solution_status = 0 WHERE id = :proposal_id";
- $args = [
-
- ":uid" => $user->get('uid')->value,
- ":date" => time(),
- ":message" => $form_state->getValue(['message']),
- ":proposal_id" => $proposal_id,
- ];
- $result = \Drupal::database()->query($query, $args);
- $config = \Drupal::config('lab_migration.settings');
- $user_data = \Drupal::entityTypeManager()->getStorage('user')->load($proposal_data->uid);
-$email_to = $user_data->getEmail();
- $from = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
-$bcc = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
-$cc = \Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
-
-$params['proposal_disapproved']['proposal_id'] = $proposal_id;
-$params['proposal_disapproved']['user_id'] = $proposal_data->uid;
-
-$params['proposal_disapproved']['headers'] = [
+ if ($form_state->getValue('approval') == 1) {
+ $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'approver_uid' => $this->currentUser->id(),
+ 'approval_date' => time(),
+ 'approval_status' => 1,
+ 'solution_status' => 2,
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ // Send email.
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ if ($user_data) {
+ $email_to = $user_data->getEmail();
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $params['proposal_approved']['proposal_id'] = $proposal_id;
+ $params['proposal_approved']['user_id'] = $proposal_data->uid;
+ $params['proposal_approved']['headers'] = [
'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
'Cc' => $cc,
'Bcc' => $bcc,
-];
+ ];
- $langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
- $mail_manager = \Drupal::service('plugin.manager.mail');
- if (!\Drupal::service('plugin.manager.mail')->mail('lab_migration', 'proposal_disapproved', $email_to, 'en', $params, $form, TRUE));
- { \Drupal::messenger()->addMessage('Mail sent successfully.');
- }
+ if ($this->mailService->sendMail('lab_migration', 'proposal_approved', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail sent successfully.'));
+ }
+ }
+ $this->messenger->addMessage($this->t('Lab migration proposal No. @id approved. User has been notified of the approval.', ['@id' => $proposal_id]), 'status');
+ $form_state->setRedirect('lab_migration.proposal_pending');
+ }
+ else {
+ if ($form_state->getValue('approval') == 2) {
+ $reason = $form_state->getValue('message');
+ $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'approver_uid' => $this->currentUser->id(),
+ 'approval_date' => time(),
+ 'approval_status' => 2,
+ 'message' => $reason,
+ 'solution_provider_uid' => 0,
+ 'solution_status' => 0,
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ // Send email.
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ if ($user_data) {
+ $email_to = $user_data->getEmail();
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $params['proposal_disapproved']['proposal_id'] = $proposal_id;
+ $params['proposal_disapproved']['user_id'] = $proposal_data->uid;
+ $params['proposal_disapproved']['headers'] = [
+ 'From' => $from,
+ 'Cc' => $cc,
+ 'Bcc' => $bcc,
+ ];
+
+ if ($this->mailService->sendMail('lab_migration', 'proposal_disapproved', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail sent successfully.'));
+ }
+ }
- // }
-// if (!\Drupal::service('plugin.manager.mail')->mail('lab_migration', 'proposal_disapproved', $email_to, 'en', $params, $form, TRUE));
-// { \Drupal::messenger()->addError('Error sending email message.');
-// }
- \Drupal::messenger()->addmessage('Lab migration proposal No. ' . $proposal_id . ' dis-approved. User has been notified of the dis-approval.', 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $url = Url::fromRoute('lab_migration.proposal_pending')->toString();
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
- return;
+ $this->messenger->addMessage($this->t('Lab migration proposal No. @id disapproved. User has been notified of the disapproval.', ['@id' => $proposal_id]), 'error');
+ $form_state->setRedirect('lab_migration.proposal_pending');
}
}
}
-
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalEditForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalEditForm.php
index 4fb5377..f3dce29 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalEditForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalEditForm.php
@@ -9,13 +9,82 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\user\Entity\User;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
+
class LabMigrationProposalEditForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+
+ /**
+ * Constructs a new LabMigrationProposalEditForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ EntityTypeManagerInterface $entity_type_manager,
+ RequestStack $request_stack,
+ LabMigrationGlobalfunction $lab_global
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->requestStack = $request_stack;
+ $this->labGlobal = $lab_global;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('entity_type.manager'),
+ $container->get('request_stack'),
+ $container->get('lab_migration_global')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -23,44 +92,29 @@ public function getFormId() {
return 'lab_migration_proposal_edit_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('id');
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
-
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
-return new RedirectResponse('/lab-migration/manage-proposal/pending');
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
- return;
- }
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ return $form;
}
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- return new RedirectResponse('/lab-migration/manage-proposal/pending');
- // return;
- }
- $user_data = User::load($proposal_data->uid);
- //var_dump($user_data->getEmail());die;
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+
$form['name_title'] = [
'#type' => 'select',
- '#title' => t('Title'),
+ '#title' => $this->t('Title'),
'#options' => [
'Mr' => 'Mr',
'Ms' => 'Ms',
@@ -71,45 +125,51 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#required' => TRUE,
'#default_value' => $proposal_data->name_title,
];
+
$form['name'] = [
'#type' => 'textfield',
- '#title' => t('Name of the Proposer'),
+ '#title' => $this->t('Name of the Proposer'),
'#size' => 30,
'#maxlength' => 50,
'#required' => TRUE,
'#default_value' => $proposal_data->name,
];
+
$form['email_id'] = [
'#type' => 'item',
- '#title' => t('Email'),
- '#markup' => $user_data->getEmail(),
+ '#title' => $this->t('Email'),
+ '#markup' => $user_data ? $user_data->getEmail() : $this->t('Unknown'),
];
+
$form['contact_ph'] = [
'#type' => 'textfield',
- '#title' => t('Contact No.'),
+ '#title' => $this->t('Contact No.'),
'#size' => 30,
'#maxlength' => 15,
'#required' => TRUE,
'#default_value' => $proposal_data->contact_ph,
];
+
$form['department'] = [
'#type' => 'select',
- '#title' => t('Department/Branch'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_departments(),
+ '#title' => $this->t('Department/Branch'),
+ '#options' => $this->labGlobal->_lm_list_of_departments(),
'#required' => TRUE,
'#default_value' => $proposal_data->department,
];
+
$form['university'] = [
'#type' => 'textfield',
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
'#size' => 30,
'#maxlength' => 50,
'#required' => TRUE,
'#default_value' => $proposal_data->university,
];
+
$form['country'] = [
'#type' => 'select',
- '#title' => t('Country'),
+ '#title' => $this->t('Country'),
'#options' => [
'India' => 'India',
'Others' => 'Others',
@@ -119,447 +179,375 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#tree' => TRUE,
'#validated' => TRUE,
];
+
$form['other_country'] = [
'#type' => 'textfield',
- '#title' => t('Other than India'),
+ '#title' => $this->t('Other than India'),
'#size' => 100,
'#default_value' => $proposal_data->country,
'#attributes' => [
- 'placeholder' => t('Enter your country name')
- ],
+ 'placeholder' => $this->t('Enter your country name'),
+ ],
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['other_state'] = [
'#type' => 'textfield',
- '#title' => t('State other than India'),
+ '#title' => $this->t('State other than India'),
'#size' => 100,
'#attributes' => [
- 'placeholder' => t('Enter your state/region name')
- ],
+ 'placeholder' => $this->t('Enter your state/region name'),
+ ],
'#default_value' => $proposal_data->state,
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['other_city'] = [
'#type' => 'textfield',
- '#title' => t('City other than India'),
+ '#title' => $this->t('City other than India'),
'#size' => 100,
'#attributes' => [
- 'placeholder' => t('Enter your city name')
- ],
+ 'placeholder' => $this->t('Enter your city name'),
+ ],
'#default_value' => $proposal_data->city,
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['all_state'] = [
'#type' => 'select',
- '#title' => t('State'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_states(),
+ '#title' => $this->t('State'),
+ '#options' => $this->labGlobal->_lm_list_of_states(),
'#default_value' => $proposal_data->state,
'#validated' => TRUE,
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
+ 'value' => 'India',
+ ],
],
+ ],
];
+
$form['city'] = [
'#type' => 'select',
- '#title' => t('City'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_cities(),
+ '#title' => $this->t('City'),
+ '#options' => $this->labGlobal->_lm_list_of_cities(),
'#default_value' => $proposal_data->city,
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
+ 'value' => 'India',
+ ],
],
+ ],
];
+
$form['pincode'] = [
'#type' => 'textfield',
- '#title' => t('Pincode'),
+ '#title' => $this->t('Pincode'),
'#size' => 30,
'#maxlength' => 6,
'#default_value' => $proposal_data->pincode,
'#attributes' => [
- 'placeholder' => 'Insert pincode of your city/ village....'
- ],
+ 'placeholder' => $this->t('Insert pincode of your city/ village....'),
+ ],
];
- // $form['operating_system'] = [
- // '#type' => 'textfield',
- // '#default_value' => $proposal_data->operating_system,
- // '#title' => t('Operating System'),
- // ];
- // $form['version'] = [
- // '#type' => 'select',
- // '#title' => t('R Version'),
- // '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_software_version(),
- // '#default_value' => $proposal_data->version,
- // ];
- // $form['syllabus_link'] = [
- // '#type' => 'item',
- // '#markup' => $proposal_data->syllabus_link,
- // '#title' => t('Syllabus Link'),
- // ];
+
$form['lab_title'] = [
'#type' => 'textfield',
- '#title' => t('Title of the Lab'),
+ '#title' => $this->t('Title of the Lab'),
'#size' => 100,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $proposal_data->lab_title,
];
+
/* get experiment details */
- // $experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY id ASC", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('id', 'ASC');
- $experiment_q = $query->execute();
- /*$form['lab_experiment'] = array(
- '#type' => 'fieldset',
- '#collapsible' => FALSE,
- '#tree' => TRUE,
- );*/
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->orderBy('id', 'ASC')
+ ->execute();
+
for ($counter = 1; $counter <= 15; $counter++) {
$experiment_title = '';
$experiment_data = $experiment_q->fetchObject();
if ($experiment_data) {
$experiment_title = $experiment_data->title;
$experiment_description = $experiment_data->description;
- /*$form['lab_experiment_']['update'][$experiment_data->id] = array(
- '#type' => 'textfield',
- '#title' => t('Title of the Experiment ') . $counter,
- '#size' => 50,
- '#required' => FALSE,
-
- '#default_value' => $experiment_title,
- );
- $form['lab_experiment']['update1'][$experiment_data->id] = array(
- '#type' => 'textarea',
-
- '#title' => t('Description for Experiment ') . $counter,
- '#default_value' => $experiment_description,
- );*/
+
$form['lab_experiment_update' . $experiment_data->id] = [
'#type' => 'textfield',
- '#title' => t('Title of the Experiment ') . $counter,
+ '#title' => $this->t('Title of the Experiment @num', ['@num' => $counter]),
'#size' => 100,
'#default_value' => $experiment_title,
];
+
$namefield = "lab_experiment_update" . $experiment_data->id;
$form['lab_experiment_description_update' . $experiment_data->id] = [
'#type' => 'textarea',
'#attributes' => [
- 'placeholder' => t('Enter Description for your experiment ' . $counter)
- ],
+ 'placeholder' => $this->t('Enter Description for your experiment @num', ['@num' => $counter]),
+ ],
'#default_value' => $experiment_description,
- '#title' => t('Description for Experiment ') . $counter,
+ '#title' => $this->t('Description for Experiment @num', ['@num' => $counter]),
];
}
else {
$form['lab_experiment_insert' . $counter] = [
'#type' => 'textfield',
- '#title' => t('Title of the Experiment ') . $counter,
+ '#title' => $this->t('Title of the Experiment @num', ['@num' => $counter]),
'#size' => 100,
'#required' => FALSE,
'#default_value' => $experiment_title,
];
+
$namefield = "lab_experiment_insert" . $counter;
$form['lab_experiment_description_insert' . $counter] = [
'#type' => 'textarea',
'#attributes' => [
- 'placeholder' => t('Enter Description for your experiment ' . $counter)
- ],
- '#title' => t('Description for Experiment ') . $counter,
+ 'placeholder' => $this->t('Enter Description for your experiment @num', ['@num' => $counter]),
+ ],
+ '#title' => $this->t('Description for Experiment @num', ['@num' => $counter]),
'#states' => [
'invisible' => [
- ':input[name=' . $namefield . ']' => [
- 'value' => ""
- ]
- ]
+ ':input[name="' . $namefield . '"]' => [
+ 'value' => "",
+ ],
],
+ ],
];
}
}
+
if ($proposal_data->solution_provider_uid == 0) {
- $solution_provider_user = 'Open';
+ $solution_provider_user = $this->t('Open');
}
else {
if ($proposal_data->solution_provider_uid == $proposal_data->uid) {
- $solution_provider_user = 'Proposer';
+ $solution_provider_user = $this->t('Proposer');
}
else {
- $user_data = User::load($proposal_data->solution_provider_uid);
- if (!$user_data) {
- $solution_provider_user = 'NA';
- \Drupal::messenger()->addmessage('Solution provider user name is invalid', 'error');
+ $sol_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->solution_provider_uid);
+ if (!$sol_user) {
+ $solution_provider_user = $this->t('NA');
+ $this->messenger->addError($this->t('Solution provider user name is invalid.'));
+ }
+ else {
+ $solution_provider_user = $proposal_data->solution_provider_name;
}
- $solution_provider_user = $proposal_data->soultion_provider_name;
}
}
+
$form['solution_provider_uid'] = [
'#type' => 'item',
- '#title' => t('Who will provide the solution'),
+ '#title' => $this->t('Who will provide the solution'),
'#markup' => $solution_provider_user,
];
+
$form['open_solution'] = [
'#type' => 'checkbox',
- '#title' => t('Open the solution for everyone'),
+ '#title' => $this->t('Open the solution for everyone'),
];
+
$form['solution_display'] = [
'#type' => 'hidden',
- '#title' => t('Do you want to display the solution on the www.r.fossee.in website'),
- '#options' => [
- '1' => 'Yes'
- ],
+ '#title' => $this->t('Do you want to display the solution on the website'),
'#required' => TRUE,
- // '#default_value' => ($proposal_data->solution_display == 1) ? "1" : "2",
- '#default_value' => '1',
+ '#default_value' => '1',
];
+
$form['delete_proposal'] = [
'#type' => 'checkbox',
- '#title' => t('Delete Proposal'),
+ '#title' => $this->t('Delete Proposal'),
];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
+
$form['cancel'] = [
- '#type' => 'item',
- // '#markup' => Link::fromTextAndUrl(t('Cancel'), 'lab-migration/manage-proposal'),
- '#markup' => Link::fromTextAndUrl(t('Cancel'), Url::fromRoute('lab_migration.proposal_pending'))->toString(),
+ '#type' => 'markup',
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Cancel'),
+ Url::fromRoute('lab_migration.proposal_pending')
+ )->toString(),
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('id');
- /* check before delete proposal */
- if ($form_state->getValue(['delete_proposal']) == 1) {
- //$experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $experiment_q = $query->execute();
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ if ($form_state->getValue('delete_proposal') == 1) {
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
while ($experiment_data = $experiment_q->fetchObject()) {
- //$solution_q = \Drupal::database()->query("SELECT * FROM {lab_migration_solution} WHERE experiment_id = %d", $experiment_data->id);
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $experiment_data->id);
- $solution_q = $query->execute();
- if ($solution_q->fetchObject()) {
- $form_state->setErrorByName('', t('Cannot delete proposal since there are solutions already uploaded. Use the "Bulk Manage" interface to delete this proposal'));
+ $solution_data = $this->database->select('lab_migration_solution')
+ ->fields('lab_migration_solution')
+ ->condition('experiment_id', $experiment_data->id)
+ ->execute()
+ ->fetchObject();
+
+ if ($solution_data) {
+ $form_state->setErrorByName('delete_proposal', $this->t('Cannot delete proposal since there are solutions already uploaded. Use the "Bulk Manage" interface to delete this proposal.'));
+ break;
}
}
}
- return;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('proposal_id');
- // $proposal_q = \Drupal::database()->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_all')->toString());
- // Send the redirect response
- $response->send();
- return;
- }
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal/pending');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_all')->toString());
- // Send the redirect response
- $response->send();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirect('lab_migration.proposal_pending');
return;
}
+
/* delete proposal */
- if ($form_state->getValue(['delete_proposal']) == 1) {
- //\Drupal::database()->query("DELETE FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->delete('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $num_deleted = $query->execute();
- //\Drupal::database()->query("DELETE FROM {lab_migration_experiment} WHERE proposal_id = %d", $proposal_id);
- $query = \Drupal::database()->delete('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $num_deleted = $query->execute();
- \Drupal::messenger()->addmessage(t('Proposal Delete'), 'status');
- // RedirectResponse('lab-migration/manage-proposal');
- // $url = Url::fromRoute('lab_migration/manage-proposal/pending')->toString();
- // Redirect to the URL.
- $response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_all')->toString());
- // Send the redirect response
- $response->send();
+ if ($form_state->getValue('delete_proposal') == 1) {
+ $this->database->delete('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ $this->database->delete('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
+ $this->messenger->addMessage($this->t('Proposal Deleted'), 'status');
+ $form_state->setRedirect('lab_migration.proposal_pending');
return;
}
- if ($form_state->getValue(['open_solution']) == 1) {
- // $query = "UPDATE {lab_migration_proposal} SET solution_provider_uid = :solution_provider_uid, solution_status = :solution_status, solution_provider_name_title = '', solution_provider_name = '', solution_provider_contact_ph = '', solution_provider_department = '', solution_provider_university = '' WHERE id = :proposal_id";
- // $args= array(
- // ":solution_provider_uid" => 0,
- // ":solution_status" => 0,
- // ":proposal_id" => $proposal_id,
- // );
- // $result = \Drupal::database()->query($query, $args);
- $result = \Drupal::database()->update('lab_migration_proposal')->fields([
- 'solution_provider_uid' => 0,
- 'solution_status' => 0,
- 'solution_provider_name_title' => '',
- 'solution_provider_name' => '',
- 'solution_provider_contact_ph' => '',
- 'solution_provider_department' => '',
- 'solution_provider_university' => '',
- ])->condition('id', $proposal_id)->execute();
+
+ if ($form_state->getValue('open_solution') == 1) {
+ $result = $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'solution_provider_uid' => 0,
+ 'solution_status' => 0,
+ 'solution_provider_name_title' => '',
+ 'solution_provider_name' => '',
+ 'solution_provider_contact_ph' => '',
+ 'solution_provider_department' => '',
+ 'solution_provider_university' => '',
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
if (!$result) {
- \Drupal::messenger()->addmessage(t('Solution already open for everyone.'), 'error');
- return;
+ $this->messenger->addError($this->t('Solution already open for everyone.'));
}
}
- $solution_display = 0;
- if ($form_state->getValue(['solution_display']) == 1) {
- $solution_display = 1;
- }
- else {
- $solution_display = 0;
- }
+
+ $solution_display = ($form_state->getValue('solution_display') == 1) ? 1 : 0;
+
/* update proposal */
$v = $form_state->getValues();
- //$query = "UPDATE {lab_migration_proposal} SET name_title = :name_title, name = :name, contact_ph = :contact_ph, department = :department, university = :unversity, lab_title = :lab_title, solution_display = :solution_display WHERE id = :id";
- // $args= array(
- // ":name_title" => $v['name_title'],
- // ":name" => $v['name'],
- // "contact_ph" => $v['contact_ph'],
- // ":department" => $v['department'],
- // ":university" => $v['university'],
- // ":lab_title" => $v['lab_title'],
- // ":solution_display" => $solution_display,
- // ":id" => $proposal_id,
- // );
-
$lab_title = $v['lab_title'];
$proposar_name = $v['name_title'] . ' ' . $v['name'];
$university = $v['university'];
- $directory_names = \Drupal::service("lab_migration_global")->_lm_dir_name($lab_title, $proposar_name, $university);
- if (\Drupal::service("lab_migration_global")->LM_RenameDir($proposal_id, $directory_names)) {
+ $directory_names = $this->labGlobal->_lm_dir_name($lab_title, $proposar_name, $university);
+
+ if ($this->labGlobal->LM_RenameDir($proposal_id, $directory_names)) {
$directory_name = $directory_names;
}
else {
return;
}
- $query = \Drupal::database()->update('lab_migration_proposal')->fields([
- 'name_title' => $v['name_title'],
- 'name' => $v['name'],
- 'contact_ph' => $v['contact_ph'],
- 'department' => $v['department'],
- 'university' => $v['university'],
- 'city' => $v['city'],
- 'pincode' => $v['pincode'],
- 'state' => $v['all_state'],
- 'operating_system' => $v['operating_system'],
- 'version' => $form_state->getValue(['version']),
- 'lab_title' => $v['lab_title'],
- 'solution_display' => $solution_display,
- 'directory_name' => $directory_name,
- ])->condition('id', $proposal_id);
- $result1 = $query->execute();
- //$result=\Drupal::database()->query($query, $args);
+ $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'name_title' => $v['name_title'],
+ 'name' => $v['name'],
+ 'contact_ph' => $v['contact_ph'],
+ 'department' => $v['department'],
+ 'university' => $v['university'],
+ 'city' => $v['city'],
+ 'pincode' => $v['pincode'],
+ 'state' => $v['all_state'],
+ 'lab_title' => $v['lab_title'],
+ 'solution_display' => $solution_display,
+ 'directory_name' => $directory_name,
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
/* updating existing experiments */
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('id', 'ASC');
- $experiment_q = $query->execute();
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->orderBy('id', 'ASC')
+ ->execute();
+
for ($counter = 1; $counter <= 15; $counter++) {
$experiment_data = $experiment_q->fetchObject();
if ($experiment_data) {
$experiment_field_name = 'lab_experiment_update' . $experiment_data->id;
$experiment_description = 'lab_experiment_description_update' . $experiment_data->id;
- if (strlen(trim($form_state->getValue([$experiment_field_name]))) >= 1) {
- $query = "UPDATE {lab_migration_experiment} SET title = :title, description= :description WHERE id = :id";
- $args = [
- ":title" => trim($form_state->getValue([$experiment_field_name])),
- ":description" => trim($form_state->getValue([$experiment_description])),
- ":id" => $experiment_data->id,
- ];
- $result2 = \Drupal::database()->query($query, $args);
- if (!$result2) {
- \Drupal::messenger()->addmessage(t('Could not update Title of the Experiment : ') . trim($form_state->getValue([$experiment_field_name])), 'error');
- }
+
+ if (strlen(trim($form_state->getValue($experiment_field_name))) >= 1) {
+ $this->database->update('lab_migration_experiment')
+ ->fields([
+ 'title' => trim($form_state->getValue($experiment_field_name)),
+ 'description' => trim($form_state->getValue($experiment_description)),
+ ])
+ ->condition('id', $experiment_data->id)
+ ->execute();
}
else {
- $query = "DELETE FROM {lab_migration_experiment} WHERE id = :id LIMIT 1";
- $args = [":id" => $experiment_data->id];
- $result3 = \Drupal::database()->query($query, $args);
+ $this->database->delete('lab_migration_experiment')
+ ->condition('id', $experiment_data->id)
+ ->execute();
}
}
}
- /* foreach ($form_state['values']['lab_experiment']['update'] as $update_id => $update_value) {
- if (strlen(trim($update_value)) >= 1) {
- $description= $form_state['values']['lab_experiment_description']['update'];
- $query = "UPDATE {lab_migration_experiment} SET title = :title and description=:description WHERE id = :id";
- $args = array(
- ":title"=> trim($update_value),
- ":description"=>trim($description),
- ":id"=> $update_id,
- );
- $result2 = \Drupal::database()->query($query, $args);
- if (!$result2)
- {
- \Drupal::messenger()->addmessage(t('Could not update Title of the Experiment : ') . trim($update_value), 'error');
- }
- } else {
- $query = "DELETE FROM {lab_migration_experiment} WHERE id = :id LIMIT 1";
- $args = array(
- ":id" => $update_id
- );
- $result3 = \Drupal::database()->query($query, $args);
- }
- }*/
+
/* inserting new experiments */
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('number', 'DESC');
- $query->range(0, 1);
- $number_q = $query->execute();
+ $number_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->orderBy('number', 'DESC')
+ ->range(0, 1)
+ ->execute();
+
if ($number_data = $number_q->fetchObject()) {
$number = (int) $number_data->number;
$number++;
@@ -567,70 +555,26 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
else {
$number = 1;
}
+
for ($counter = 1; $counter <= 15; $counter++) {
$lab_experiment_insert = 'lab_experiment_insert' . $counter;
$lab_experiment_description_insert = 'lab_experiment_description_insert' . $counter;
- if (strlen(trim(!$form_state->getValue([$lab_experiment_insert]))) >= 1) {
- $query = "INSERT INTO {lab_migration_experiment} (proposal_id, number, title, description) VALUES (:proposal_id, :number, :title, :description)";
- $args = [
- ":proposal_id" => $proposal_id,
- ":number" => $number,
- ":title" => trim($form_state->getValue([$lab_experiment_insert])),
- ":description" => trim($form_state->getValue([$lab_experiment_description_insert])),
- ];
- $result4 = \Drupal::database()->query($query, $args);
- if (!$result4) {
- \Drupal::messenger()->addmessage(t('Could not insert Title of the Experiment : ') . trim($form_state->getValue([$lab_experiment_insert])), 'error');
- }
- else {
- $number++;
- }
+
+ if (strlen(trim($form_state->getValue($lab_experiment_insert))) >= 1) {
+ $this->database->insert('lab_migration_experiment')
+ ->fields([
+ 'proposal_id' => $proposal_id,
+ 'number' => $number,
+ 'title' => trim($form_state->getValue($lab_experiment_insert)),
+ 'description' => trim($form_state->getValue($lab_experiment_description_insert)),
+ ])
+ ->execute();
+ $number++;
}
}
- /* $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('number', 'DESC');
- $query->range(0, 1);
- $number_q = $query->execute();
- if ($number_data = $number_q->fetchObject()) {
- $number = (int)$number_data->number;
- $number++;
- } else {
- $number = 1;
- }
- $insertvalue = array($insert_id => $insert_value);
- $lab_experimentinsert = $form_state['values']['lab_experiment']['insert'];
- $lab_exp_descriptioninsert=$form_state['values']['lab_experiment_description']['insert'];
- if (is_array($lab_experimentinsert) || is_object($lab_experimentinsert))
- {
- foreach ($lab_experimentinsert as $insertvalue) {
- //foreach ($form_state['values']['lab_experiment']['insert'] as $insert_id => $insert_value) {
- if (strlen(trim($insert_value)) >= 1) {
- $query = "INSERT INTO {lab_migration_experiment} (proposal_id, number, title, description) VALUES :proposal_id, :number, :title, :description";
- $args = array(
- ":proposal_id" => $proposal_id,
- ":number" => $number,
- ":title" => trim($insert_value),
- ":description"=>""
- );
- $result4 = \Drupal::database()->query($query, $args);
- if (!$result4)
- {
- \Drupal::messenger()->addmessage(t('Could not insert Title of the Experiment : ') . trim($insert_value), 'error');
- } else {
- $number++;
- }
- }
- }
- }*/
- \Drupal::messenger()->addmessage(t('Proposal Updated'), 'status');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_pending')->toString());
- // Send the redirect response
- $response->send();
- return;
- }
+ $this->messenger->addMessage($this->t('Proposal Updated'), 'status');
+ $form_state->setRedirect('lab_migration.proposal_pending');
+ }
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalForm.php
index b2443e8..802ac4b 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalForm.php
@@ -9,23 +9,95 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-use Drupal\Core\Link;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
-use Drupal\Core\Routing\TrustedRedirectResponse;
-use Symfony\Component\HttpFoundation\Response;
+use Drupal\Core\Link;
use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\StringTranslation\StringTranslationTrait;
-use Drupal\Core\Database\Database;
-use Drupal\Core\Messenger\MessengerInterface;
-use Drupal\Core\Mail\MailManager;
-use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\DependencyInjection\ContainerInterface;
-use Drupal\user\Entity\User;
+use Drupal\Core\Form\EnforcedFormResponseException;
class LabMigrationProposalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * Constructs a new LabMigrationProposalForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ LabMigrationGlobalfunction $lab_global,
+ MailService $mail_service,
+ RequestStack $request_stack
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->labGlobal = $lab_global;
+ $this->mailService = $mail_service;
+ $this->requestStack = $request_stack;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('lab_migration_global'),
+ $container->get('lab_migration.mail_service'),
+ $container->get('request_stack')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -33,462 +105,340 @@ public function getFormId() {
return 'lab_migration_proposal_form';
}
+ /**
+ * {@inheritdoc}
+ */
public function buildForm(array $form, FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- $form = [];
- $state = \Drupal::service("lab_migration_global")->_lab_migration_list_of_states();
- $selected_state = $form_state->getValue('all_state') ?: key($state);
- // $selected_state = !$form_state->getValue(['all_state']) ? $form_state->getValue([
- // 'all_state'
- // :key($state);
- $district = \Drupal::service("lab_migration_global")->_lab_migration_list_of_district();
- $selected_district = $form_state->getValue('district') ?: key($district);
- // $selected_district = !$form_state->getValue(['district']) ? $form_state->getValue([
- // 'district'
- // ]):key($district);
- $city = \Drupal::service("lab_migration_global")->_lm_list_of_cities();
- $selected_city = $form_state->getValue('city') ?: key($city);
- // $selected_city = !$form_state->getValue(['city']) ? $form_state->getValue([
- // 'city'
- // ]):key($city);
- $pincode = \Drupal::service("lab_migration_global")->_lab_migration_list_of_city_pincode();
- $selected_pincode= $form_state->getValue('pincode') ?: key($pincode);
- // $selected_pincode = !$form_state->getValue(['picode'])?$form_state->getValue([
- // 'pincode'
- // ]):key($pincode);
- /************************ start approve book details ************************/
- if ($user->isAnonymous()) {
- // $msg = \Drupal::messenger()->addError(t('This is an error message, red in color'));
- $url = Link::fromTextAndUrl(t('login'), Url::fromRoute('user.page'))->toString();
-
- $msg = \Drupal::messenger()->addmessage(t('It is mandatory to ' . Link::fromTextAndUrl(t('login'), Url::fromRoute('user.page'))->toString() . ' on this website to access the lab proposal form. If you are new user please create a new account first.'));
-
- // RedirectResponse('lab-migration-project');
- // \Drupal::RedirectResponse('user');
- // $redirect = new RedirectResponse($url);
- // $redirect->send();
- // return $msg;
- // Redirect to the login page
- $response = new RedirectResponse(Url::fromRoute('user.page')->toString());
-
- $response->send();
- return $msg;
-
- // /lab-migration/proposal
+ if ($this->currentUser->isAnonymous()) {
+ $this->messenger->addMessage($this->t('It is mandatory to login to this website to access the lab proposal form. If you are a new user, please create an account first.'));
+ $response = new RedirectResponse(Url::fromRoute('user.page')->toString());
+ throw new EnforcedFormResponseException($response);
}
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('uid', $user->id());
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- if ($proposal_data) {
- if ($proposal_data->approval_status == 0 || $proposal_data->approval_status == 1) {
- \Drupal::messenger()->addmessage(t('We have already received your proposal.'));
- // Create a redirect response to the front page
-$response = new RedirectResponse(Url::fromRoute('')->toString());
-// Send the redirect response
-//$response->send();
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('uid', $this->currentUser->id())
+ ->orderBy('id', 'DESC')
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
- return $response;
+ if ($proposal_data) {
+ if ($proposal_data->approval_status == 0 || $proposal_data->approval_status == 1) {
+ $this->messenger->addMessage($this->t('We have already received your proposal.'));
+ $response = new RedirectResponse(Url::fromRoute('')->toString());
+ throw new EnforcedFormResponseException($response);
}
}
+
$form['#attributes'] = ['enctype' => "multipart/form-data"];
+
$form['name_title'] = [
'#type' => 'select',
- '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Title'),
+ '#title' => $this->t('Title'),
'#options' => [
'Dr' => 'Dr',
'Prof' => 'Prof',
-
],
'#required' => TRUE,
];
+
$form['name'] = [
'#type' => 'textfield',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Name of the Proposer'),
+ '#title' => $this->t('Name of the Proposer'),
'#size' => 100,
'#attributes' => [
- 'class' => ['form-control'],
- 'placeholder' => $this->t('Enter your full name')
- ],
+ 'placeholder' => $this->t('Enter your full name'),
+ ],
'#maxlength' => 200,
'#required' => TRUE,
];
+
$form['email_id'] = [
'#type' => 'textfield',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Email'),
+ '#title' => $this->t('Email'),
'#size' => 30,
- '#value' => $user ? $user->getEmail() : '',
+ '#value' => $this->currentUser->getEmail(),
'#disabled' => TRUE,
];
+
$form['contact_ph'] = [
'#type' => 'textfield',
- '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Contact No.'),
+ '#title' => $this->t('Contact No.'),
'#size' => 30,
'#attributes' => [
- 'placeholder' => t('Enter your contact number')
- ],
+ 'placeholder' => $this->t('Enter your contact number'),
+ ],
'#maxlength' => 15,
'#required' => TRUE,
];
+
$form['department'] = [
'#type' => 'select',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Department/Branch'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_departments(),
+ '#title' => $this->t('Department/Branch'),
+ '#options' => $this->labGlobal->_lm_list_of_departments(),
'#required' => TRUE,
-
];
+
$form['university'] = [
'#type' => 'textfield',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('University/ Institute'),
+ '#title' => $this->t('University/ Institute'),
'#size' => 50,
'#maxlength' => 200,
'#required' => TRUE,
'#attributes' => [
- 'placeholder' => 'Insert full name of your institute/ university.... '
- ],
+ 'placeholder' => $this->t('Insert full name of your institute/ university.... '),
+ ],
];
+
$form['country'] = [
'#type' => 'select',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Country'),
+ '#title' => $this->t('Country'),
'#options' => [
'India' => 'India',
'Others' => 'Others',
],
'#required' => TRUE,
- // '#attributes' => ['class' => ['form-control']],
'#tree' => TRUE,
'#validated' => TRUE,
];
+
$form['other_country'] = [
'#type' => 'textfield',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Other than India'),
+ '#title' => $this->t('Other than India'),
'#size' => 30,
'#attributes' => [
- 'placeholder' => $this->t('Enter your country name')
- ],
+ 'placeholder' => $this->t('Enter your country name'),
+ ],
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['other_state'] = [
'#type' => 'textfield',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => t('State other than India'),
+ '#title' => $this->t('State other than India'),
'#size' => 50,
'#attributes' => [
- 'placeholder' => t('Enter your state/region name')
- ],
+ 'placeholder' => $this->t('Enter your state/region name'),
+ ],
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['other_city'] = [
'#type' => 'textfield',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('City other than India'),
+ '#title' => $this->t('City other than India'),
'#size' => 50,
'#attributes' => [
- 'placeholder' => $this->t('Enter your city name')
- ],
+ 'placeholder' => $this->t('Enter your city name'),
+ ],
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['all_state'] = [
'#type' => 'select',
- '#attributes' => array('class' => array('form-control')),
-'#title' => t('State'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_states(),
+ '#title' => $this->t('State'),
+ '#options' => $this->labGlobal->_lm_list_of_states(),
'#validated' => TRUE,
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
+ 'value' => 'India',
+ ],
],
+ ],
];
+
$form['city'] = [
'#type' => 'select',
- '#attributes' => array('class' => array('form-control')),
-'#title' => t('City'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_cities(),
+ '#title' => $this->t('City'),
+ '#options' => $this->labGlobal->_lm_list_of_cities(),
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
+ 'value' => 'India',
+ ],
],
+ ],
];
+
$form['pincode'] = [
'#type' => 'textfield',
- '#attributes' => array('class' => array('form-control')),
-'#title' => t('Pincode'),
+ '#title' => $this->t('Pincode'),
'#size' => 30,
'#maxlength' => 6,
'#required' => TRUE,
'#attributes' => [
- 'placeholder' => 'Enter pincode....'
- ],
+ 'placeholder' => $this->t('Enter pincode....'),
+ ],
];
-
- /***************************************************************************/
+
$form['hr'] = [
'#type' => 'item',
'#markup' => ' ',
];
-
+
$form['version'] = [
'#type' => 'select',
- // '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('DWSIM Version'),
- '#options' =>\Drupal::service("lab_migration_global")->_lm_list_of_software_version(),
+ '#title' => $this->t('DWSIM Version'),
+ '#options' => $this->labGlobal->_lm_list_of_software_version(),
'#required' => TRUE,
];
+
$form['older'] = [
'#type' => 'textfield',
'#size' => 30,
'#maxlength' => 50,
- //'#required' => TRUE,
- '#description' => $this->t('Specify the Older version used'),
+ '#description' => $this->t('Specify the Older version used'),
'#states' => [
'visible' => [
':input[name="version"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
-
-
+
$form['lab_title'] = [
'#type' => 'textfield',
- '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Title of the Lab'),
+ '#title' => $this->t('Title of the Lab'),
'#size' => 100,
'#required' => TRUE,
];
- $first_experiemnt = TRUE;
+
for ($counter = 1; $counter <= 15; $counter++) {
- if ($counter <= 1) {
- $form['lab_experiment-' . $counter] = [
- '#type' => 'textfield',
- '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Title of the Experiment ') . $counter,
- '#size' => 100,
- '#required' => TRUE,
- ];
- $namefield = "lab_experiment-" . $counter;
- $form['lab_experiment_description-' . $counter] = [
- '#type' => 'textarea',
- '#required' => TRUE,
- '#attributes' => [
- 'placeholder' => $this->t('Enter Description for your experiment ' . $counter),
- 'cols' => 50,
- 'rows' => 4,
- ],
- '#attributes' => array('class' => array('form-control')),
-'#title' => t('Description for Experiment ') . $counter,
- '#states' => [
- 'invisible' => [
- ':input[name=' . $namefield . ']' => [
- 'value' => ""
- ]
- ]
+ $required = ($counter <= 1);
+ $form['lab_experiment-' . $counter] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Title of the Experiment @num', ['@num' => $counter]),
+ '#size' => 100,
+ '#required' => $required,
+ ];
+
+ $namefield = "lab_experiment-" . $counter;
+ $form['lab_experiment_description-' . $counter] = [
+ '#type' => 'textarea',
+ '#required' => $required,
+ '#attributes' => [
+ 'placeholder' => $this->t('Enter Description for your experiment @num', ['@num' => $counter]),
+ 'cols' => 50,
+ 'rows' => 4,
+ ],
+ '#title' => $this->t('Description for Experiment @num', ['@num' => $counter]),
+ '#states' => [
+ 'invisible' => [
+ ':input[name="' . $namefield . '"]' => [
+ 'value' => "",
],
- ];
- }
- else {
- $form['lab_experiment-' . $counter] = [
- '#type' => 'textfield',
- '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Title of the Experiment ') . $counter,
- '#size' => 100,
- '#required' => FALSE,
- ];
- $namefield = "lab_experiment-" . $counter;
- $form['lab_experiment_description-' . $counter] = [
- '#type' => 'textarea',
- '#required' => FALSE,
- '#attributes' => [
- 'placeholder' => $this->t('Enter Description for your experiment ' . $counter),
- 'cols' => 50,
- 'rows' => 4,
],
- '#attributes' => array('class' => array('form-control')),
-'#title' => $this->t('Description for Experiment ') . $counter,
- '#states' => [
- 'invisible' => [
- ':input[name=' . $namefield . ']' => [
- 'value' => ""
- ]
- ]
- ],
- ];
- }
- $first_experiemnt = FALSE;
+ ],
+ ];
}
+
$form['solution_provider_uid'] = [
'#type' => 'radios',
-// '#attributes' => ['class' => ['form-control']],
-'#title' => $this->t('Do you want to provide the solution'),
+ '#title' => $this->t('Do you want to provide the solution'),
'#options' => [
'1' => 'Yes',
'2' => 'No',
],
'#required' => TRUE,
'#default_value' => '1',
- '#description' => 'If you dont want to provide the solution then it will be opened for the community, anyone may come forward and provide the solution.',
+ '#description' => $this->t('If you do not want to provide the solution then it will be opened for the community, anyone may come forward and provide the solution.'),
];
-
-// $form['sample_syllabus_file'] = [
-// '#type' => 'item',
-// // '#attributes' => array('class' => array('form-control')),
-// '#title' => $this->t('Ideal Sample Lab Migration Submission '),
-// '#markup' => $this->t('Kindly refer to the ') . t('Sample Lab Migration (Statistical Quality Control using R) and Sample Lab Migration (Analysis using R) ') . '' . t(' to know the ideal submission.'),
-// ];
+
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state->getValue(['contact_ph']))) {
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state->getValue('contact_ph'))) {
$form_state->setErrorByName('contact_ph', $this->t('Invalid contact phone number'));
}
- if ($form_state->getValue(['country']) == 'Others') {
- if ($form_state->getValue(['other_country']) == '') {
+
+ if ($form_state->getValue('country') == 'Others') {
+ if ($form_state->getValue('other_country') == '') {
$form_state->setErrorByName('other_country', $this->t('Enter country name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
}
else {
- $form_state->setValue(['country'], $form_state->getValue([
- 'other_country'
- ]));
+ $form_state->setValue('country', $form_state->getValue('other_country'));
}
- if ($form_state->getValue(['other_state']) == '') {
+
+ if ($form_state->getValue('other_state') == '') {
$form_state->setErrorByName('other_state', $this->t('Enter state name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
}
else {
- $form_state->setValue(['all_state'], $form_state->getValue([
- 'other_state'
- ]));
+ $form_state->setValue('all_state', $form_state->getValue('other_state'));
}
- if ($form_state->getValue(['other_city']) == '') {
+
+ if ($form_state->getValue('other_city') == '') {
$form_state->setErrorByName('other_city', $this->t('Enter city name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
}
else {
- $form_state->setValue(['city'], $form_state->getValue(['other_city']));
+ $form_state->setValue('city', $form_state->getValue('other_city'));
}
}
else {
- if ($form_state->getValue(['country']) == '') {
+ if ($form_state->getValue('country') == '') {
$form_state->setErrorByName('country', $this->t('Select country name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
}
- if ($form_state->getValue(['all_state']) == '') {
+ if ($form_state->getValue('all_state') == '') {
$form_state->setErrorByName('all_state', $this->t('Select state name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
}
- if ($form_state->getValue(['city']) == '') {
+ if ($form_state->getValue('city') == '') {
$form_state->setErrorByName('city', $this->t('Select city name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
}
}
+
for ($counter = 1; $counter <= 15; $counter++) {
$experiment_field_name = 'lab_experiment-' . $counter;
$experiment_description = 'lab_experiment_description-' . $counter;
- if (strlen(trim($form_state->getValue([$experiment_field_name]))) >= 1) {
- if (strlen(trim($form_state->getValue([$experiment_description]))) <= 49) {
+ if (strlen(trim($form_state->getValue($experiment_field_name))) >= 1) {
+ if (strlen(trim($form_state->getValue($experiment_description))) <= 49) {
$form_state->setErrorByName($experiment_description, $this->t('Description should be minimum of 50 characters'));
}
}
}
- if ($form_state->getValue(['version']) == 'olderversion') {
- if ($form_state->getValue(['older']) == '') {
+
+ if ($form_state->getValue('version') == 'olderversion') {
+ if ($form_state->getValue('older') == '') {
$form_state->setErrorByName('older', $this->t('Please provide valid version'));
}
}
-
- if (isset($_FILES['files'])) {
- /* check if atleast one source or result file is uploaded */
- // if (!($_FILES['files']['name']['syllabus_copy_file'])) {
- // $form_state->setErrorByName('syllabus_copy_file', $this->t('Please upload pdf file.'));
- // }
- /* check for valid filename extensions */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- if ($file_name) {
- /* checking file type */
- if (strstr($file_form_name, 'syllabus')) {
- $file_type = 'S';
- }
- else {
- $file_type = 'U';
- }
- $allowed_extensions_str = '';
- switch ($file_type) {
- case 'S':
- $allowed_extensions_str = \Drupal::config('lab_migration.settings')->get('lab_migration_syllabus_file_extensions');
- break;
- } //$file_type
- $allowed_extensions = explode(',', $allowed_extensions_str);
- $allowd_file = strtolower($_FILES['files']['name'][$file_form_name]);
- $allowd_files = explode('.', $allowd_file);
- $temp_extension = end($allowd_files);
- if (!in_array($temp_extension, $allowed_extensions)) {
- $form_state->setErrorByName($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.'));
- }
- if ($_FILES['files']['size'][$file_form_name] <= 0) {
- $form_state->setErrorByName($file_form_name, t('File size cannot be zero.'));
- }
- // check if valid file name
- // if (!lab_migration_check_valid_filename($_FILES['files']['name'][$file_form_name])) {
- // $form_state->setErrorByName($file_form_name, $this->t('Invalid file name specified. Only alphabets and numbers are allowed as a valid filename.'));
- // }
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- } //isset($_FILES['files'])
-
- return;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- // $user = $this->currentUser->id();
-
- if (!$user->id()) {
- \Drupal::messenger()->addmessage('It is mandatory to login on this website to access the proposal form');
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ if (!$this->currentUser->id()) {
+ $this->messenger->addError($this->t('It is mandatory to login on this website to access the proposal form'));
return;
}
+
$solution_provider_uid = 0;
$solution_status = 0;
$solution_provider_name_title = '';
@@ -496,185 +446,109 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$solution_provider_contact_ph = '';
$solution_provider_department = '';
$solution_provider_university = '';
- if ($form_state->getValue(['solution_provider_uid']) == "1") {
- // $solution_provider_uid = $user->get('uid')->value;
- $solution_provider_uid =$user->id();
+
+ if ($form_state->getValue('solution_provider_uid') == "1") {
+ $solution_provider_uid = $this->currentUser->id();
$solution_status = 1;
- $solution_provider_name_title = $form_state->getValue(['name_title']);
- $solution_provider_name = $form_state->getValue(['name']);
- $solution_provider_contact_ph = $form_state->getValue(['contact_ph']);
- $solution_provider_department = $form_state->getValue(['department']);
- $solution_provider_university = $form_state->getValue(['university']);
+ $solution_provider_name_title = $form_state->getValue('name_title');
+ $solution_provider_name = $form_state->getValue('name');
+ $solution_provider_contact_ph = $form_state->getValue('contact_ph');
+ $solution_provider_department = $form_state->getValue('department');
+ $solution_provider_university = $form_state->getValue('university');
}
- else {
- $solution_provider_uid = 0;
- }
- $solution_display = 0;
- if ($form_state->getValue(['solution_display']) == "1") {
- $solution_display = 1;
- }
- else {
- $solution_display = 1;
- }
- if ($form_state->getValue(['version']) == 'olderversion') {
- $form_state->setValue(['version'], $form_state->getValue(['older']));
+
+ $solution_display = 1;
+
+ if ($form_state->getValue('version') == 'olderversion') {
+ $form_state->setValue('version', $form_state->getValue('older'));
}
- /* inserting the user proposal */
+
$v = $form_state->getValues();
$lab_title = $v['lab_title'];
$proposar_name = $v['name_title'] . ' ' . $v['name'];
$university = $v['university'];
- $directory_name = \Drupal::service("lab_migration_global")->_lm_dir_name($lab_title, $proposar_name, $university);
- $result = "INSERT INTO {lab_migration_proposal}
- (uid, approver_uid, name_title, name, contact_ph, department, university, city, pincode, state, country, operating_system, version, lab_title, approval_status, solution_status, solution_provider_uid, solution_display, creation_date, approval_date, solution_date, solution_provider_name_title, solution_provider_name, solution_provider_contact_ph, solution_provider_department, solution_provider_university, directory_name,) VALUES
- (:uid, :approver_uid, :name_title, :name, :contact_ph, :department, :university, :city, :pincode, :state, :country, :operating_system,
- :version, :lab_title, :approval_status, :solution_status, :solution_provider_uid, :solution_display, :creation_date,
- :approval_date, :solution_date, :solution_provider_name_title, :solution_provider_name,
- :solution_provider_contact_ph, :solution_provider_department, :solution_provider_university, :directory_name,)";
- $args = [
- // 'uid' => $user->get('uid')->value,
- 'uid' => $user->id(),
- 'approver_uid' => 0,
- 'name_title' => $v['name_title'],
- 'name' => $v['name'],
- 'contact_ph' => $v['contact_ph'],
- 'department' => $v['department'],
- 'university' => $v['university'],
- 'city' => $v['city'],
- 'pincode' => $v['pincode'],
- 'state' => $v['all_state'],
- 'country' => $v['country'],
- // 'operating_system' => $v['operating_system'],
- 'version' => $form_state->getValue(['version']),
- 'lab_title' => $v['lab_title'],
- 'approval_status' => 0,
- 'solution_status' => $solution_status,
- 'solution_provider_uid' => $solution_provider_uid,
- 'solution_display' => $solution_display,
- 'creation_date' => time(),
- 'approval_date' => 0,
- 'solution_date' => 0,
- 'solution_provider_name_title' => $solution_provider_name_title,
- 'solution_provider_name' => $solution_provider_name,
- 'solution_provider_contact_ph' => $solution_provider_contact_ph,
- 'solution_provider_department' => $solution_provider_department,
- 'solution_provider_university' => $solution_provider_university,
- 'directory_name' => $directory_name,
- ];
-
- // $connection = \Drupal::database();
-// $proposal_id = $connection->insert('lab_migration_proposal');
-$connection = Database::getConnection();
-$proposal_id= $connection->insert('lab_migration_proposal')->fields($args)->execute();
- // $proposal_insert = \Drupal::database()->query($result, $args);
- // $proposal_id= $connection->lastInsertId('lab_migration_proposal');
-
- $root_path = \Drupal::service("lab_migration_global")->lab_migration_path();
+ $directory_name = $this->labGlobal->_lm_dir_name($lab_title, $proposar_name, $university);
+
+ $proposal_id = $this->database->insert('lab_migration_proposal')
+ ->fields([
+ 'uid' => $this->currentUser->id(),
+ 'approver_uid' => 0,
+ 'name_title' => $v['name_title'],
+ 'name' => $v['name'],
+ 'contact_ph' => $v['contact_ph'],
+ 'department' => $v['department'],
+ 'university' => $v['university'],
+ 'city' => $v['city'],
+ 'pincode' => $v['pincode'],
+ 'state' => $v['all_state'],
+ 'country' => $v['country'],
+ 'version' => $form_state->getValue('version'),
+ 'lab_title' => $v['lab_title'],
+ 'approval_status' => 0,
+ 'solution_status' => $solution_status,
+ 'solution_provider_uid' => $solution_provider_uid,
+ 'solution_display' => $solution_display,
+ 'creation_date' => time(),
+ 'approval_date' => 0,
+ 'solution_date' => 0,
+ 'solution_provider_name_title' => $solution_provider_name_title,
+ 'solution_provider_name' => $solution_provider_name,
+ 'solution_provider_contact_ph' => $solution_provider_contact_ph,
+ 'solution_provider_department' => $solution_provider_department,
+ 'solution_provider_university' => $solution_provider_university,
+ 'directory_name' => $directory_name,
+ ])
+ ->execute();
+
+ if (!$proposal_id) {
+ $this->messenger->addError($this->t('Error receiving your proposal. Please try again.'));
+ return;
+ }
+
+ $root_path = $this->labGlobal->lab_migration_path();
$dest_path = $proposal_id . '/';
if (!is_dir($root_path . $dest_path)) {
mkdir($root_path . $dest_path);
}
- /* uploading files */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- if ($file_name) {
- /* checking file type */
- $file_type = 'S';
- if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- \Drupal::messenger()->addError(t("Error uploading file. File !filename already exists.", [
- '!filename' => $_FILES['files']['name'][$file_form_name]
- ]));
- return;
- } //file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
- /* uploading file */
- // if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- // $query = "UPDATE {lab_migration_proposal} SET syllabus_copy_file_path = :syllabus_copy_file_path WHERE id = :id";
- // $args = [
- // ":syllabus_copy_file_path" => $dest_path . $_FILES['files']['name'][$file_form_name],
- // ":id" => $proposal_id,
- // ];
- // $updateresult = \Drupal::database()->query($query, $args);
- // \Drupal::messenger()->addStatus($file_name . ' uploaded successfully.');
- // } //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
- // else {
- // \Drupal::messenger()->addError('Error uploading file : ' . $dest_path . '/' . $file_name);
- // }
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- if (!$proposal_id) {
- \Drupal::messenger()->addError($this->t('Error receiving your proposal. Please try again.'));
- return;
- }
- /* proposal id */
- //$proposal_id = db_last_insert_id('lab_migration_proposal', 'id');
- /* adding experiments */
+
$number = 1;
for ($counter = 1; $counter <= 15; $counter++) {
$experiment_field_name = 'lab_experiment-' . $counter;
$experiment_description = 'lab_experiment_description-' . $counter;
- if (strlen(trim($form_state->getValue([$experiment_field_name]))) >= 1) {
- //$query = "INSERT INTO {lab_migration_experiment} (proposal_id, directory_name, number, title,description) VALUES (:proposal_id, :directory_name, :number, :experiment_field_name,:description)";
- $query = "INSERT INTO {lab_migration_experiment} (proposal_id, number, title,description) VALUES (:proposal_id, :number, :experiment_field_name,:description)";
- $args = [
- ":proposal_id" => $proposal_id,
- // ":directory_name" => $directory_name,
- ":number" => $number,
- ":experiment_field_name" => trim($form_state->getValue([$experiment_field_name])),
- ":description" => trim($form_state->getValue([$experiment_description])),
- ];
- // $connection = \Drupal::database();
- // $result = $connection->query($query, $args);
- // // $result = $this::database()->query($query, $args);
- // if (!$result) {
- // \Drupal::messenger()->addError($this->t('Could not insert Title of the Experiment : ') . trim($form_state->getValue([$experiment_field_name])));
- // }
- // else {
- // $number++;
- // }
- try {
- $connection = \Drupal::database();
- $result = $connection->query($query, $args);
-
- if ($result) {
- $number++;
- }
- else {
- \Drupal::messenger()->addError($this->t('Could not insert Title of the Experiment: ') . trim($form_state->getValue($experiment_field_name)));
- }
- }
- catch (\Exception $e) {
- \Drupal::messenger()->addError($this->t('Database query failed: ') . $e->getMessage());
- }
-
+
+ if (strlen(trim($form_state->getValue($experiment_field_name))) >= 1) {
+ $this->database->insert('lab_migration_experiment')
+ ->fields([
+ 'proposal_id' => $proposal_id,
+ 'number' => $number,
+ 'title' => trim($form_state->getValue($experiment_field_name)),
+ 'description' => trim($form_state->getValue($experiment_description)),
+ ])
+ ->execute();
+ $number++;
}
}
-
- // Send email.
-$email_to = $user->getEmail();
-$form = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
-$bcc = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
-$cc = \Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
-$params['proposal_received']['proposal_id'] = $proposal_id;
-$params['proposal_received']['user_id'] = $user->id();
-$params['proposal_received']['headers'] = [
- 'From' => $form,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
-];
- $langcode = $user->getPreferredLangcode();
-if (!\Drupal::service('plugin.manager.mail')->mail('lab_migration', 'proposal_received', $email_to, 'en', $params, $form, TRUE));
- { \Drupal::messenger()->addMessage(' sending email message.');
-}
- \Drupal::messenger()->addmessage($this->t('We have received you Lab migration proposal. We will get back to you soon.'));
- $response = new RedirectResponse(Url::fromRoute('')->toString());
-
-
- // Redirect to front page.
- // $response = new RedirectResponse(\Drupal::url(''));
- // $response->send();
-}
-}
-?>
\ No newline at end of file
+
+ $email_to = $this->currentUser->getEmail();
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $params['proposal_received']['proposal_id'] = $proposal_id;
+ $params['proposal_received']['user_id'] = $this->currentUser->id();
+ $params['proposal_received']['headers'] = [
+ 'From' => $from,
+ 'Cc' => $cc,
+ 'Bcc' => $bcc,
+ ];
+
+ if ($this->mailService->sendMail('lab_migration', 'proposal_received', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Email notification sent.'));
+ }
+
+ $this->messenger->addMessage($this->t('We have received your Lab migration proposal. We will get back to you soon.'));
+ $form_state->setRedirect('');
+ }
+
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalStatusForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalStatusForm.php
index e85cf4d..82bb7b3 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalStatusForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationProposalStatusForm.php
@@ -9,19 +9,92 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\Core\Routing\TrustedRedirectResponse;
-use Drupal\user\Entity\User;
-use Drupal\Component\Utility\Xss;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
-use Drupal\Core\Mail\MailManager;
-use Drupal\Core\Mail\MailManagerInterface;
+class LabMigrationProposalStatusForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
-class LabMigrationProposalStatusForm extends FormBase {
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * Constructs a new LabMigrationProposalStatusForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ RequestStack $request_stack,
+ MailService $mail_service
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->requestStack = $request_stack;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('request_stack'),
+ $container->get('lab_migration.mail_service')
+ );
+ }
/**
* {@inheritdoc}
@@ -30,350 +103,296 @@ public function getFormId() {
return 'lab_migration_proposal_status_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('id');
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- //return new TrustedRedirectResponse('/lab-migration/manage-proposal');
- return;
- }
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- // return new RedirectResponse('/lab-migration/manage-proposal');
- return;
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ return $form;
}
$form['name'] = [
'#type' => 'item',
- '#markup' => Link::fromTextAndUrl($proposal_data->name_title . ' ' . $proposal_data->name,Url::fromRoute('entity.user.canonical', ['user' => $proposal_data->uid]))->toString(),
- '#title' => t('Name'),
+ '#markup' => Link::fromTextAndUrl(
+ $proposal_data->name_title . ' ' . $proposal_data->name,
+ Url::fromRoute('entity.user.canonical', ['user' => $proposal_data->uid])
+ )->toString(),
+ '#title' => $this->t('Name'),
];
- // $form['email_id'] = [
- // '#type' => 'item',
- // '#markup' => User::load($proposal_data->uid)->getEmail(),
- // '#title' => t('Email'),
- // ];
-
-$user = !empty($proposal_data->uid) ? User::load($proposal_data->uid) : NULL;
-$email = $user ? $user->getEmail() : 'Not available';
+ $proposal_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ $form['email_id'] = [
+ '#type' => 'item',
+ '#markup' => $proposal_user ? $proposal_user->getEmail() : $this->t('Not available'),
+ '#title' => $this->t('Email'),
+ ];
-$form['email_id'] = [
- '#type' => 'item',
- '#markup' => $email,
- '#title' => t('Email'),
-];
$form['contact_ph'] = [
'#type' => 'item',
'#markup' => $proposal_data->contact_ph,
- '#title' => t('Contact No.'),
+ '#title' => $this->t('Contact No.'),
];
+
$form['department'] = [
'#type' => 'item',
'#markup' => $proposal_data->department,
- '#title' => t('Department/Branch'),
+ '#title' => $this->t('Department/Branch'),
];
+
$form['university'] = [
'#type' => 'item',
'#markup' => $proposal_data->university,
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
];
+
$form['country'] = [
'#type' => 'item',
'#markup' => $proposal_data->country,
- '#title' => t('Country'),
+ '#title' => $this->t('Country'),
];
+
$form['all_state'] = [
'#type' => 'item',
'#markup' => $proposal_data->state,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
];
+
$form['city'] = [
'#type' => 'item',
'#markup' => $proposal_data->city,
- '#title' => t('City'),
+ '#title' => $this->t('City'),
];
+
$form['pincode'] = [
'#type' => 'item',
'#markup' => $proposal_data->pincode,
- '#title' => t('Pincode/Postal code'),
+ '#title' => $this->t('Pincode/Postal code'),
];
+
$form['operating_system'] = [
'#type' => 'item',
'#markup' => $proposal_data->operating_system,
- '#title' => t('Operating System'),
+ '#title' => $this->t('Operating System'),
];
- // $form['version'] = [
- // '#type' => 'item',
- // '#markup' => $proposal_data->version,
- // // '#markup' => Xss::filter($proposal_data->version),
- // '#title' => t('R Version'),
- // ];
+
$form['syllabus_link'] = [
'#type' => 'item',
'#markup' => $proposal_data->syllabus_link,
- '#title' => t('Syllabus Link'),
+ '#title' => $this->t('Syllabus Link'),
];
+
$form['lab_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->lab_title,
- '#title' => t('Title of the Lab'),
+ '#title' => $this->t('Title of the Lab'),
];
- // var_dump($form);die;
+
/* get experiment details */
$experiment_list = '';
- //$experiment_q = $injected_database->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY id ASC", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('id', 'ASC');
- $experiment_q = $query->execute();
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->orderBy('id', 'ASC')
+ ->execute();
+
while ($experiment_data = $experiment_q->fetchObject()) {
- $experiment_list .= '' . $experiment_data->title . ' Description of Experiment : ' . $experiment_data->description . ' ';
+ $experiment_list .= '' . htmlspecialchars($experiment_data->title) . ' Description of Experiment : ' . htmlspecialchars($experiment_data->description) . ' ';
}
$experiment_list .= ' ';
+
$form['experiment'] = [
'#type' => 'item',
'#markup' => $experiment_list,
- '#title' => t('Experiments'),
+ '#title' => $this->t('Experiments'),
];
+
if ($proposal_data->solution_provider_uid == 0) {
- $solution_provider = "User will not provide solution, we will have to provide solution";
+ $solution_provider = $this->t("User will not provide solution, we will have to provide solution");
}
else {
if ($proposal_data->solution_provider_uid == $proposal_data->uid) {
- $solution_provider = "Proposer will provide the solution of the lab";
+ $solution_provider = $this->t("Proposer will provide the solution of the lab");
}
else {
- $solution_provider_user_data = User::load($proposal_data->solution_provider_uid);
- if ($solution_provider_user_data) {
- //$solution_provider = "Solution will be provided by user " . Link::fromTextAndUrl($solution_provider_user_data->name, 'user/' . $proposal_data->solution_provider_uid);
+ $sol_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->solution_provider_uid);
+ if ($sol_user) {
+ $solution_provider = $this->t("Solution will be provided by user @user", ['@user' => $sol_user->getDisplayName()]);
}
else {
- $solution_provider = "User does not exists";
+ $solution_provider = $this->t("User does not exist");
}
}
}
+
$form['solution_provider_uid'] = [
'#type' => 'item',
- '#title' => t('Who will provide the solution'),
+ '#title' => $this->t('Who will provide the solution'),
'#markup' => $solution_provider,
];
- /*$form['solution_display'] = array(
- '#type' => 'item',
- '#title' => t('Display the solution on the www.r.fossee.in website'),
- '#markup' => ($proposal_data->solution_display == 1) ? "Yes" : "No",
- );*/
+
$proposal_status = '';
switch ($proposal_data->approval_status) {
case 0:
- $proposal_status = t('Pending');
+ $proposal_status = $this->t('Pending');
break;
case 1:
- $proposal_status = t('Approved');
+ $proposal_status = $this->t('Approved');
break;
case 2:
- $proposal_status = t('Dis-approved');
+ $proposal_status = $this->t('Dis-approved');
break;
case 3:
- $proposal_status = t('Completed');
+ $proposal_status = $this->t('Completed');
break;
default:
- $proposal_status = t('Unkown');
+ $proposal_status = $this->t('Unknown');
break;
}
+
$form['proposal_status'] = [
'#type' => 'item',
'#markup' => $proposal_status,
- '#title' => t('Proposal Status'),
+ '#title' => $this->t('Proposal Status'),
];
- if ($proposal_data->approval_status == 0) {
- if ($proposal_data->expected_completion_date == 0) {
- $form['completion_date'] = [
- '#type' => 'item',
- '#markup' => 'Expecting date of completion soon',
- '#title' => t('Date of Completion'),
- ];
- }
- else {
- $form['completion_date'] = [
- '#type' => 'item',
- '#markup' => date('d-m-Y', $proposal_data->expected_completion_date),
- '#title' => t('Expected date of completion'),
- ];
- }
- }
- if ($proposal_data->approval_status == 1) {
+
+ if ($proposal_data->approval_status == 0 || $proposal_data->approval_status == 1) {
if ($proposal_data->expected_completion_date == 0) {
$form['completion_date'] = [
'#type' => 'item',
- '#markup' => 'Expecting date of completion soon',
- '#title' => t('Date of Completion'),
+ '#markup' => $this->t('Expecting date of completion soon'),
+ '#title' => ($proposal_data->approval_status == 0) ? $this->t('Expected date of completion') : $this->t('Date of Completion'),
];
}
else {
$form['completion_date'] = [
'#type' => 'item',
'#markup' => date('d-m-Y', $proposal_data->expected_completion_date),
- '#title' => t('Date of Completion'),
+ '#title' => ($proposal_data->approval_status == 0) ? $this->t('Expected date of completion') : $this->t('Date of Completion'),
];
}
}
+
if ($proposal_data->approval_status == 0) {
$form['approve'] = [
'#type' => 'item',
- //'#markup' => Link::fromTextAndUrl('Click here', 'lab-migration/manage-proposal/approve/' . $proposal_id),
- '#title' => t('Approve'),
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Click here to approve'),
+ Url::fromRoute('lab_migration.proposal_approval_form', ['id' => $proposal_id])
+ )->toString(),
+ '#title' => $this->t('Approve'),
];
}
+
if ($proposal_data->approval_status == 1) {
$form['completed'] = [
'#type' => 'checkbox',
- '#title' => t('Completed'),
- '#description' => t('Check if user has provided all experiment solutions.'),
+ '#title' => $this->t('Completed'),
+ '#description' => $this->t('Check if user has provided all experiment solutions.'),
];
}
+
if ($proposal_data->approval_status == 2) {
$form['message'] = [
'#type' => 'item',
'#markup' => $proposal_data->message,
- '#title' => t('Reason for disapproval'),
+ '#title' => $this->t('Reason for disapproval'),
];
}
- //DATE OF COMPLETION
+
if ($proposal_data->approval_status == 3) {
$form['completion_date'] = [
'#type' => 'item',
'#markup' => date('d-m-Y', $proposal_data->expected_completion_date),
- '#title' => t('Date of Completion'),
+ '#title' => $this->t('Date of Completion'),
];
}
+
if ($proposal_data->approval_status == 2) {
$form['completion_date'] = [
'#type' => 'item',
- '#markup' => "Proposal is disapproved",
- '#title' => t('Date of Completion'),
+ '#markup' => $this->t('Proposal is disapproved'),
+ '#title' => $this->t('Date of Completion'),
];
}
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
+
$form['cancel'] = [
'#type' => 'markup',
- // '#markup' => Link::fromTextAndUrl(t('Cancel'), 'lab-migration/manage-proposal/all'),
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Cancel'),
+ Url::fromRoute('lab_migration.proposal_all')
+ )->toString(),
];
+
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('id');
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse('/lab-migration/manage-proposal');
- $response->send();
- return;
- }
- }
- else {
- \Drupal::messenger()->addmessage(t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse('lab_migration.proposal_pending_solution');
-$response->send();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirect('lab_migration.proposal_all');
return;
}
- /* set the book status to completed */
- if ($form_state->getValue(['completed']) == 1) {
- $up_query = "UPDATE lab_migration_proposal SET approval_status = :approval_status , expected_completion_date = :expected_completion_date WHERE id = :proposal_id";
- $args = [
- ":approval_status" => '3',
- ":proposal_id" => $proposal_id,
- ":expected_completion_date" => time(),
- ];
- $result = \Drupal::database()->query($up_query, $args);
-
-/* Sending email */
-$user_data = User::load($proposal_data->uid);
-
-if ($user_data && $user_data->getEmail()) {
-
- $email_to = $user_data->getEmail();
-
- $config = \Drupal::config('lab_migration.settings');
- $from = $config->get('lab_migration_from_email');
- $bcc = $user->getEmail() . ', ' . $config->get('lab_migration_emails');
- $cc = $config->get('lab_migration_cc_emails');
-
- $params['proposal_completed']['proposal_id'] = $proposal_id;
- $params['proposal_completed']['user_id'] = $proposal_data->uid;
- $params['proposal_completed']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
-
- $langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
-
- $mailManager = \Drupal::service('plugin.manager.mail');
-
- $result = $mailManager->mail(
- 'lab_migration',
- 'proposal_completed',
- $email_to,
- $langcode,
- $params,
- $from,
- TRUE
- );
-
- if (empty($result['result'])) {
- \Drupal::messenger()->addMessage(t('Mail sent successfully.'));
- }
- \Drupal::messenger()->addmessage('Congratulations! Lab Migration proposal has been marked as completed. User has been notified of the completion.', 'status');
+
+ if ($form_state->getValue('completed') == 1) {
+ $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'approval_status' => 3,
+ 'expected_completion_date' => time(),
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ if ($user_data && $user_data->getEmail()) {
+ $email_to = $user_data->getEmail();
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $this->currentUser->getEmail() . ', ' . $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $params['proposal_completed']['proposal_id'] = $proposal_id;
+ $params['proposal_completed']['user_id'] = $proposal_data->uid;
+ $params['proposal_completed']['headers'] = [
+ 'From' => $from,
+ 'Cc' => $cc,
+ 'Bcc' => $bcc,
+ ];
+
+ if ($this->mailService->sendMail('lab_migration', 'proposal_completed', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail sent successfully.'));
+ }
+ }
+
+ $this->messenger->addMessage($this->t('Congratulations! Lab Migration proposal has been marked as completed. User has been notified of the completion.'), 'status');
+ $form_state->setRedirect('lab_migration.proposal_all');
}
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_all')->toString());
-
- // // // Send the redirect response
- $response->send();
- return;
- }
}
-}
-?>
\ No newline at end of file
+
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationRunForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationRunForm.php
index 38113c3..84b4932 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationRunForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationRunForm.php
@@ -4,577 +4,357 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Ajax\AjaxResponse;
-use Drupal\Core\Ajax\HtmlCommand;
-use Drupal\Core\Ajax\ReplaceCommand;
-use Drupal\Core\Database\Database;
-use Drupal\Core\Render\Element;
-use Drupal\Core\Render\Markup;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\user\Entity\User;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
-use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\Core\Render\BubbleableMetadata;
-use Drupal\Core\Render\RendererInterface;
-use ZipArchieve;
+use Drupal\Core\Form\EnforcedFormResponseException;
class LabMigrationRunForm extends FormBase {
/**
- * {@inheritdoc}
- */
- public function getFormId() {
- return 'lab_migration_run_form';
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * Constructs a new LabMigrationRunForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ LabMigrationGlobalfunction $lab_global,
+ RequestStack $request_stack
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->labGlobal = $lab_global;
+ $this->requestStack = $request_stack;
}
-
+
/**
- * {@inheritdoc}
- */
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state)
-
- {
- $options_first =$this->_list_of_labs();
- $options_two = $this->_ajax_get_experiment_list();
- // $select_two = isset($form_state['values']['lab_experiment_list']) ? $form_state['values']['lab_experiment_list'] : key($options_two);
- $select_two = $form_state->getValue('lab_experiment_list') ?: key($options_two);
- // $url_lab_id = (int) arg(2);
- $route_match = \Drupal::routeMatch();
- $url_lab_id = (int) $route_match->getParameter('url_lab_id');
- if (!$url_lab_id)
- {
- // $selected = isset($form_state['values']['lab']) ? $form_state['values']['lab'] : key($options_first);
- $selected = $form_state->getValue('lab') ?: key($options_first);
- }
- elseif ($url_lab_id == '')
- {
- $selected = 0;
- }
- else
- {
- $selected = $url_lab_id;
- }
- $form = [];
- $form['lab'] = array(
- '#type' => 'select',
- '#title' => t('Title of the lab'),
- '#options' => $this->_list_of_labs(),
- '#default_value' => $selected,
- '#ajax' => [
- 'callback' => '::ajax_experiment_list_callback',
- 'wrapper' => 'ajax_selected_lab'
- ]
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('lab_migration_global'),
+ $container->get('request_stack')
);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'lab_migration_run_form';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $options_first = $this->_list_of_labs();
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $url_lab_id = $route_match ? $route_match->getParameter('url_lab_id') : NULL;
+
+ if ($url_lab_id !== NULL && $url_lab_id !== '') {
+ $selected = (int) $url_lab_id;
+ }
+ else {
+ $selected = $form_state->getValue('lab', !empty($options_first) ? key($options_first) : 0);
+ }
+
+ $form['lab'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Title of the lab'),
+ '#options' => $options_first,
+ '#default_value' => $selected,
+ '#ajax' => [
+ 'callback' => '::ajax_experiment_list_callback',
+ 'wrapper' => 'ajax_selected_lab',
+ ],
+ ];
+
$form['download_lab_wrapper'] = [
'#type' => 'container',
'#attributes' => ['id' => 'ajax_selected_lab'],
];
- $lab_default_value = $form_state->getValue('lab') ?: $url_lab_id;
- //var_dump($lab_default_value);die;
- $form['download_lab_wrapper']['selected_lab'] = [
- '#type' => 'markup',
- '#markup' =>
- Link::fromTextAndUrl(
- $this->t('Download Lab Solutions'),
- Url::fromUri('internal:/lab-migration/download/lab/' . $lab_default_value)
- )->toString()
- ];
- $form['download_lab_wrapper']['lab_details'] = array(
- '#type' => 'item',
- '#markup' => $this->_lab_details($lab_default_value)
- );
- $form['download_lab_wrapper']['lab_experiment_list'] = array(
- '#type' => 'select',
- '#title' => t('Title of the experiment'),
- '#options' => $this->_ajax_get_experiment_list($lab_default_value),
- // '#default_value' => isset($form_state['values']['lab_experiment_list']) ? $form_state['values']['lab_experiment_list'] : '',
- '#ajax' => [
- 'callback' => '::ajax_solution_list_callback',
- 'wrapper' => 'ajax_download_experiments'
- ],
- '#prefix' => '',
- '#suffix' => '
',
- '#states' => array(
- 'invisible' => array(
- ':input[name="lab"]' => array(
- 'value' => 0
- )
- )
- )
- );
- $form['download_experiment_wrapper'] = [
- '#type' => 'container',
- '#attributes' => ['id' => 'ajax_download_experiments'],
- ];
- $form['download_experiment_wrapper']['download_experiment'] = [
- '#type' => 'item',
- '#markup' => Link::fromTextAndUrl('Download Experiment', Url::fromUri('internal:/lab-migration/download/experiment/' . $form_state->getValue('lab_experiment_list')))->toString()
- ];
- $form['download_experiment_wrapper']['solution_list'] = [
- '#type' => 'select',
- '#title' => t('Title of the solution'),
- '#options' => $this->_ajax_get_solution_list($form_state->getValue('lab_experiment_list')),
- '#ajax' => [
- 'callback' => '::ajax_solution_files_callback',
- 'wrapper' => 'ajax_download_solution_file'
- ],
- ];
- //for download solution
- $form['download_solution_wrapper'] = [
- '#type' => 'container',
- '#attributes' => ['id' => 'ajax_download_solution_file'],
- ];
- $form['download_solution_wrapper']['download_solution'] = [
- '#type' => 'item',
- '#markup' => Link::fromTextAndUrl('Download Solution', Url::fromUri('internal:/lab-migration/download/solution/' . $form_state->getValue('solution_list')))->toString()
- ];
-
-$query = \Drupal::database()->select('lab_migration_solution_files', 's');
- $query->fields('s');
- $query->condition('solution_id', $form_state->getValue('solution_list'));
- $solution_list_q = $query->execute();
- if ($solution_list_q) {
- $solution_files_rows = [];
- while ($solution_list_data = $solution_list_q->fetchObject()) {
-
-//var_dump($solution_list_data);die;
- // $solution_file_type = [];
- // var_dump($solution_list_data->filetype);die;
- switch ($solution_list_data->filetype) {
- case 'S':
- $solution_file_type = 'Source or Main file';
- break;
- case 'R':
- $solution_file_type = 'Result file';
- break;
- case 'X':
- $solution_file_type = 'xcos file';
- break;
- default:
- $solution_file_type = 'Unknown';
- break;
- }
-
- // Create file download link
- $items = [
-
- Link::fromTextAndUrl($solution_list_data->filename, Url::fromUri('internal:/lab-migration/download/file/' . $solution_list_data->id))->toString(),
- "{$solution_file_type}"
- ];
+ $lab_default_value = $form_state->getValue('lab', $selected);
+
+ $form['download_lab_wrapper']['selected_lab'] = [
+ '#type' => 'markup',
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Download Lab Solutions'),
+ Url::fromUri('internal:/lab-migration/download/lab/' . $lab_default_value)
+ )->toString(),
+ ];
+
+ $form['download_lab_wrapper']['lab_details'] = [
+ '#type' => 'item',
+ '#markup' => $this->_lab_details($lab_default_value),
+ ];
+
+ $form['download_lab_wrapper']['lab_experiment_list'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Title of the experiment'),
+ '#options' => $this->_ajax_get_experiment_list($lab_default_value),
+ '#default_value' => $form_state->getValue('lab_experiment_list', ''),
+ '#ajax' => [
+ 'callback' => '::ajax_solution_list_callback',
+ 'wrapper' => 'ajax_download_experiments',
+ ],
+ '#prefix' => '',
+ '#suffix' => '
',
+ '#states' => [
+ 'invisible' => [
+ ':input[name="lab"]' => ['value' => 0],
+ ],
+ ],
+ ];
+
+ $form['download_experiment_wrapper'] = [
+ '#type' => 'container',
+ '#attributes' => ['id' => 'ajax_download_experiments'],
+ ];
+
+ $form['download_experiment_wrapper']['download_experiment'] = [
+ '#type' => 'item',
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Download Experiment'),
+ Url::fromUri('internal:/lab-migration/download/experiment/' . $form_state->getValue('lab_experiment_list'))
+ )->toString(),
+ ];
+
+ $form['download_experiment_wrapper']['solution_list'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Title of the solution'),
+ '#options' => $this->_ajax_get_solution_list($form_state->getValue('lab_experiment_list')),
+ '#default_value' => $form_state->getValue('solution_list', ''),
+ '#ajax' => [
+ 'callback' => '::ajax_solution_files_callback',
+ 'wrapper' => 'ajax_download_solution_file',
+ ],
+ ];
+
+ $form['download_solution_wrapper'] = [
+ '#type' => 'container',
+ '#attributes' => ['id' => 'ajax_download_solution_file'],
+ ];
+
+ $form['download_solution_wrapper']['download_solution'] = [
+ '#type' => 'item',
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Download Solution'),
+ Url::fromUri('internal:/lab-migration/download/solution/' . $form_state->getValue('solution_list'))
+ )->toString(),
+ ];
+
+ $solution_files_rows = [];
+ if ($form_state->getValue('solution_list')) {
+ $solution_list_q = $this->database->select('lab_migration_solution_files', 's')
+ ->fields('s')
+ ->condition('solution_id', $form_state->getValue('solution_list'))
+ ->execute();
+
+ while ($solution_list_data = $solution_list_q->fetchObject()) {
+ switch ($solution_list_data->filetype) {
+ case 'S':
+ $solution_file_type = $this->t('Source or Main file');
+ break;
+ case 'R':
+ $solution_file_type = $this->t('Result file');
+ break;
+ case 'X':
+ $solution_file_type = $this->t('xcos file');
+ break;
+ default:
+ $solution_file_type = $this->t('Unknown');
+ break;
}
- }
- array_push($solution_files_rows, $items);
- //var_dump($solution_rows);die;
- $form['download_solution_wrapper']['solution_files'] = [
- '#type' => 'fieldset',
- '#title' => t('List of solution files'),
+
+ $solution_files_rows[] = [
+ Link::fromTextAndUrl($solution_list_data->filename, Url::fromUri('internal:/lab-migration/download/file/' . $solution_list_data->id))->toString(),
+ $solution_file_type,
];
- $solution_files_header = ['Filename', 'Type']; // Table headers
-
- $table = [
- '#type' => 'table',
- '#header' => $solution_files_header,
- '#rows' => $solution_files_rows,
-
- '#attributes' => [
- 'style' => 'width: 100%;',
-
- ],
- ];
- // Add the table to the fieldset
-$form['download_solution_wrapper']['solution_files']['table'] = $table;
-
-
-
-
-
-
- return $form;
-}
-
-
-
-
+ }
+ }
+
+ $form['download_solution_wrapper']['solution_files'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('List of solution files'),
+ ];
+
+ $form['download_solution_wrapper']['solution_files']['table'] = [
+ '#type' => 'table',
+ '#header' => [$this->t('Filename'), $this->t('Type')],
+ '#rows' => $solution_files_rows,
+ '#attributes' => [
+ 'style' => 'width: 100%;',
+ ],
+ ];
+
+ return $form;
+ }
+
public function ajax_experiment_list_callback(array &$form, FormStateInterface $form_state) {
return $form['download_lab_wrapper'];
-
}
+
public function ajax_solution_list_callback(array &$form, FormStateInterface $form_state) {
return $form['download_experiment_wrapper'];
-
-// $response = new AjaxResponse();
-// $experiment_list_default_value = $form_state->getValue('lab_experiment_list');
-// // var_dump($experiment_list_default_value);die;
-// if ($experiment_list_default_value != 0) {
-// $exp_download_link = Link::fromTextAndUrl(
-// $this->t('Download Experiment'),
-// Url::fromRoute('lab_migration.download_experiment', ['experiment_id' => $experiment_list_default_value])
-// )->toString();
-// // Update the solution list options
-
-
-// // Add the commands to update the DOM
-
-// $response->addCommand(new HtmlCommand('#ajax_download_experiments', Link::fromTextAndUrl('Download Experiment', Url::fromUri('internal:/lab-migration/download/experiment/' . $experiment_list_default_value))->toString()));
-// $response->addCommand(new HtmlCommand('#ajax_selected_experiment', \Drupal::service('renderer')->render($form['lab_experiment_list'])));
-// //$form['lab_solution_list']['#options'] = $this->_ajax_get_solution_list($experiment_list_default_value);
-// //$response->addCommand(new HtmlCommand('#ajax_download_experiments'), $exp_download_link);
-// //$response->addCommand(new HtmlCommand('#ajax_selected_solution', \Drupal::service('renderer')->render($form['lab_solution_list'])));
-// $form_state->setRebuild(TRUE);
-// }
-// // else {
-// // // Default options when no experiment is selected
-// // $form['lab_solution_list']['#options'] = $this->_ajax_get_solution_list();
-
-// // // Clear the DOM elements
-// // $commands = [];
-// // $response->addCommand(new HtmlCommand('#ajax_selected_solution', \Drupal::service('renderer')->render($form['lab_solution_list'])));
-// // $commands[] = new HtmlCommand('#ajax_download_experiments', '');
-// // $commands[] = new HtmlCommand('#ajax_selected_solution', '');
-// // $commands[] = new HtmlCommand('#ajax_solution_files', '');
-// // $commands[] = new HtmlCommand('#ajax_download_experiment_solution', '');
-// // $commands[] = new HtmlCommand('#ajax_edit_experiment_solution', '');
-// // // Uncomment if needed
-// // // $commands[] = new ReplaceCommand('#ajax_selected_experiment', \Drupal::service('renderer')->render($form['lab_experiment_list']));
-// // }
-
-// // Return the response with commands
-// // $response = new AjaxResponse();
-// // $response->addCommand(new AppendCommand('#element-id', 'Updated content'));
-// //return $response;
-
-
-// return $response;
}
-
- public function ajax_solution_files_callback(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
-
-return $form['download_solution_wrapper'];
- // $response = new AjaxResponse();
-// // $commands = [];
-// // var_dump("hi");die;
- // $solution_list_default_value = $form_state->getValue('lab_solution_list');
-
-// if ($solution_list_default_value != 0) {
-// // Render experiment solution actions
-// $response->addCommand(new HtmlCommand('#ajax_selected_lab_experiment_solution_action', \Drupal::service('renderer')->render($form['lab_experiment_solution_actions'])));
-
-// // Query solution files
-// $query = \Drupal::database()->select('lab_migration_solution_files', 's');
-// $query->fields('s');
-// $query->condition('solution_id', $solution_list_default_value);
-// $solution_list_q = $query->execute();
-
-// if ($solution_list_q) {
-// $solution_files_rows = [];
-// while ($solution_list_data = $solution_list_q->fetchObject()) {
-// $solution_file_type = '';
-// switch ($solution_list_data->filetype) {
-// case 'S':
-// $solution_file_type = 'Source or Main file';
-// break;
-// case 'R':
-// $solution_file_type = 'Result file';
-// break;
-// case 'X':
-// $solution_file_type = 'xcos file';
-// break;
-// default:
-// $solution_file_type = 'Unknown';
-// break;
-// }
-// // Create file download link
-// $solution_files_rows[] = [
-// Link::fromTextAndUrl($solution_list_data->filename, Url::fromUri('internal:/lab-migration/download/file/' . $solution_list_data->id))->toString(),
-// $solution_file_type
-// ];
-// }
-
-// // Query dependencies
-
-// // Build the table of files
-// $solution_files_header = ['Filename', 'Type'];
-// $solution_files = \Drupal::service('renderer')->render([
-// '#theme' => 'table',
-// '#header' => $solution_files_header,
-// '#rows' => $solution_files_rows
-// ]);
-// }
-
-
-
-// // Add the download and edit links
-
-// $link = Link::fromTextAndUrl(
-// $this->t('Download Solution'),
-// Url::fromRoute('lab_migration.download_solution', ['solution' => $solution_list_default_value])
-// )->toString();
-// // Add the AJAX command to update the element with ID `#ajax_download_experiment_solution`.
-// $response->addCommand(new HtmlCommand('#ajax_download_experiment_solution', $link));
-// // Uncomment if needed
-// // $commands[] = new HtmlCommand('#ajax_edit_experiment_solution', Link::fromTextAndUrl('Edit Solution', Url::fromUri('internal:/code_approval/editcode/' . $solution_list_default_value))->toString());
-
-// // Add the solution files table to the page
-// $response->addCommand(new HtmlCommand('#ajax_solution_files', \Drupal::service('renderer')->render($form['solution_files'])));
-// } else {
-// // If no solution is selected, clear the areas
-// $commands[] = new HtmlCommand('#ajax_selected_lab_experiment_solution_action', '');
-// $commands[] = new HtmlCommand('#ajax_download_experiment_solution', '');
-// $commands[] = new HtmlCommand('#ajax_edit_experiment_solution', '');
-// $commands[] = new HtmlCommand('#ajax_solution_files', '');
-// }
-
- // Return the AJAX response
- // $response->addCommands($commands);
- // return $response;
+
+ public function ajax_solution_files_callback(array &$form, FormStateInterface $form_state) {
+ return $form['download_solution_wrapper'];
}
-
- public function bootstrap_table_format(array $headers, array $rows) {
- // Define the table header and rows.
- $table_header = [];
- foreach ($headers as $header) {
- $table_header[] = ['data' => $header, 'header' => TRUE];
- }
-
- // Define the table rows.
- $table_rows = [];
- foreach ($rows as $row) {
- $table_row = [];
- foreach ($row as $data) {
- $table_row[] = ['data' => $data];
- }
- $table_rows[] = $table_row;
- }
-
- // Create a table render array with Drupal's table theming.
- $table = [
- '#theme' => 'table',
- '#header' => $table_header,
- '#rows' => $table_rows,
- '#attributes' => ['class' => ['table', 'table-bordered', 'table-hover']],
+
+ public function _list_of_labs() {
+ $lab_titles = [
+ '0' => $this->t('Please select...'),
];
-
- // Render the table using Drupal's renderer.
- $renderer = \Drupal::service('renderer');
- return $renderer->render($table);
- }
-
-/*****************************************************/
-public function _list_of_labs()
- {
- $lab_titles = array(
- '0' => 'Please select...'
- );
- //$lab_titles_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE solution_display = 1 ORDER BY lab_title ASC");
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('solution_display', 1);
- $query->condition('approval_status', 3);
- $query->orderBy('lab_title', 'ASC');
- $lab_titles_q = $query->execute();
- while ($lab_titles_data = $lab_titles_q->fetchObject())
- {
- $lab_titles[$lab_titles_data->id] = $lab_titles_data->lab_title . ' (Proposed by ' . $lab_titles_data->name_title .' '.$lab_titles_data->name . ')';
- }
+
+ $results = $this->database->select('lab_migration_proposal', 'lmp')
+ ->fields('lmp', ['id', 'lab_title', 'name_title', 'name'])
+ ->condition('solution_display', 1)
+ ->condition('approval_status', 3)
+ ->orderBy('lab_title', 'ASC')
+ ->execute();
+
+ foreach ($results as $row) {
+ $lab_titles[$row->id] = $row->lab_title . ' (Proposed by ' . $row->name_title . ' ' . $row->name . ')';
+ }
+
return $lab_titles;
}
-public function _ajax_get_experiment_list($lab_default_value = '')
- {
- $experiments = array(
- '0' => 'Please select...'
- );
- //$experiments_q = db_query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY number ASC", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $lab_default_value);
- $query->orderBy('number', 'ASC');
- $experiments_q = $query->execute();
- while ($experiments_data = $experiments_q->fetchObject())
- {
- $experiments[$experiments_data->id] = $experiments_data->number . '. ' . $experiments_data->title;
- }
+
+ public function _ajax_get_experiment_list($lab_default_value = '') {
+ $experiments = [
+ '0' => $this->t('Please select...'),
+ ];
+
+ if (empty($lab_default_value)) {
+ return $experiments;
+ }
+
+ $results = $this->database->select('lab_migration_experiment', 'lme')
+ ->fields('lme', ['id', 'number', 'title'])
+ ->condition('proposal_id', $lab_default_value)
+ ->orderBy('number', 'ASC')
+ ->execute();
+
+ foreach ($results as $row) {
+ $experiments[$row->id] = $row->number . '. ' . $row->title;
+ }
+
return $experiments;
}
+
public function _ajax_get_solution_list($lab_experiment_list = '') {
- // var_dump("Hii");
$solutions = [
- '0' => t('Please select...'),
+ '0' => $this->t('Please select...'),
];
-
+
if (empty($lab_experiment_list)) {
return $solutions;
}
-
- // Query the database to get solutions for the given experiment.
- $connection = Database::getConnection();
- $query = $connection->select('lab_migration_solution', 'lms');
- $query->fields('lms', ['id', 'code_number', 'caption']);
- $query->condition('experiment_id', $lab_experiment_list);
- $results = $query->execute();
-
- // Process the query results and populate the solutions array.
- foreach ($results as $record) {
- $solutions[$record->id] = $record->code_number . ' (' . $record->caption . ')';
+
+ $results = $this->database->select('lab_migration_solution', 'lms')
+ ->fields('lms', ['id', 'code_number', 'caption'])
+ ->condition('experiment_id', $lab_experiment_list)
+ ->execute();
+
+ foreach ($results as $row) {
+ $solutions[$row->id] = $row->code_number . ' (' . $row->caption . ')';
}
-
+
return $solutions;
}
-public function _lab_information($proposal_id)
- {
- //var_dump($proposal_id);die;
- //$lab_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal', 'l')
- ->fields('l')
- // ->fields('e',[])
- ->condition('l.id', $proposal_id)
- ->condition('l.approval_status', 3);
-
-$lab_q = $query->execute();
-$lab_data = $lab_q->fetchObject();
-//var_dump($lab_data);die;
-// Get the database connection.
-if ($lab_data) {
- return $lab_data;
-} else {
- return;
-}
-}
- public function _lab_experiment_information($proposal_id){
- $database = \Drupal::database();
- $query = $database->query ("SELECT title FROM lab_migration_proposal
- INNER JOIN lab_migration_experiment
- ON lab_migration_proposal.id = lab_migration_experiment.proposal_id");
- $result = $query->fetchAll();$database = \Drupal::database();
- $query = $database->query ("SELECT title
- FROM lab_migration_proposal
- INNER JOIN lab_migration_experiment
- ON lab_migration_proposal.id = lab_migration_experiment.proposal_id where lab_migration_proposal.id = :proposal_id", [":proposal_id" => $proposal_id]);
- // $result = $query->fetchAll();
- // if ($result) {
- $experiment_details = 'Experiment Details ';
- while ($row = $query->fetchObject()){
- //$row['title'];
- $experiment_details .= 'Title of the Experiment: ' . $row->title . ' ';
- }
-
- return $experiment_details;
- //var_dump($result);die;
+
+ public function _lab_information($proposal_id) {
+ $lab_data = $this->database->select('lab_migration_proposal', 'l')
+ ->fields('l')
+ ->condition('l.id', $proposal_id)
+ ->condition('l.approval_status', 3)
+ ->execute()
+ ->fetchObject();
+
+ return $lab_data ?: NULL;
}
-public function _lab_details($lab_default_value)
- {
- // $lab_default_value = $form_state['values']['lab'];
+ public function _lab_details($lab_default_value) {
$lab_details = $this->_lab_information($lab_default_value);
- //$experiment_details = $this->_lab_experiment_information($lab_default_value);
- //var_dump($experiment_details);die;
- if ($lab_default_value != 0)
- {
- if ($lab_details){
- if ($lab_details->solution_provider_uid > 0)
- {
- $user_solution_provider = User::load($lab_details->solution_provider_uid);
- if ($user_solution_provider)
- {
- $solution_provider = 'Solution Provider ' . '' . 'Solution Provider Name: ' . $lab_details->solution_provider_name_title . ' ' . $lab_details->solution_provider_name . ' ' . 'Department: ' . $lab_details->solution_provider_department . ' ' . 'University: ' . $lab_details->solution_provider_university . ' ' . ' ';
- }
- else
- {
- $solution_provider = 'Solution Provider ' . '' . 'Solution Provider: (Open) ' . ' ';
- }
- }
- else
- {
- $solution_provider = 'Solution Provider ' . '' . 'Solution Provider: (Open) ' . ' ';
- }}
- else{
- // drupal_goto('lab-migration/lab-migration-run');
- $url = Url::fromRoute('lab_migration.run_form');
-
-// Create a RedirectResponse and send it.
-$response = new RedirectResponse($url->toString());
-$response->send();
-
+ if ($lab_default_value != 0) {
+ if (!$lab_details) {
+ $response = new RedirectResponse(Url::fromRoute('lab_migration.run_form')->toString());
+ throw new EnforcedFormResponseException($response);
}
-
- $form['lab_details']['#markup'] = 'About the Lab ' . '' . 'Proposer Name: ' . $lab_details->name_title . ' ' . $lab_details->name . ' ' . 'Title of the Lab: ' . $lab_details->lab_title . ' ' . 'Department: ' . $lab_details->department . ' ' . 'University: ' . $lab_details->university . ' ' . 'Version: ' . $lab_details->version . ' ' . 'Operating System: ' . $lab_details->operating_system . ' ' . ' ' . $solution_provider;
- $details = $form['lab_details']['#markup'];
- return $details;
-
+ $solution_provider = '';
+ if ($lab_details->solution_provider_uid > 0) {
+ $user_solution_provider = User::load($lab_details->solution_provider_uid);
+ if ($user_solution_provider) {
+ $solution_provider = 'Solution Provider ' . '' . 'Solution Provider Name: ' . $lab_details->solution_provider_name_title . ' ' . $lab_details->solution_provider_name . ' ' . 'Department: ' . $lab_details->solution_provider_department . ' ' . 'University: ' . $lab_details->solution_provider_university . ' ' . ' ';
+ }
+ else {
+ $solution_provider = 'Solution Provider ' . '' . 'Solution Provider: (Open) ' . ' ';
+ }
}
-
- }
-
-
- public function ajax_bulk_experiment_list_callback(array &$form,\Drupal\Core\Form\FormStateInterface $form_state) {
- $response = new AjaxResponse();
-
- // Get the selected lab value.
- $lab_default_value = $form_state->getValue('lab');
-
- if ($lab_default_value != 0) {
- // Generate a link for download.
- $download_url = Url::fromUserInput('/lab-migration/full-download/lab/' . $lab_default_value);
- $download_link = Link::fromTextAndUrl(t('Download'), $download_url)->toString();
- $response->addCommand(new HtmlCommand('#ajax_selected_lab', $download_link . ' ' . t('(Download all the approved and unapproved solutions of the entire lab)')));
- // var_dump(hii);die;
- // Update lab actions and experiment list.
- $form['lab_actions']['#options'] = _bulk_list_lab_actions();
- $form['lab_experiment_list']['#options'] = $this->_ajax_bulk_get_experiment_list($lab_default_value);
-
- $renderer = \Drupal::service('renderer');
- $response->addCommand(new ReplaceCommand('#ajax_selected_experiment', $renderer->render($form['lab_experiment_list'])));
- $response->addCommand(new ReplaceCommand('#ajax_selected_lab_action', $renderer->render($form['lab_actions'])));
-
- // Clear other sections.
- $response->addCommand(new HtmlCommand('#ajax_selected_solution', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_lab_experiment_action', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_lab_experiment_solution_action', ''));
- $response->addCommand(new HtmlCommand('#ajax_solution_files', ''));
- $response->addCommand(new HtmlCommand('#ajax_download_experiment_solution', ''));
- $response->addCommand(new HtmlCommand('#ajax_edit_experiment_solution', ''));
- } else {
- // Clear all sections if no lab is selected.
- $response->addCommand(new HtmlCommand('#ajax_selected_lab', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_lab_pdf', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_experiment', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_lab_action', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_lab_experiment_action', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_lab_experiment_solution_action', ''));
- $response->addCommand(new HtmlCommand('#ajax_solution_files', ''));
- $response->addCommand(new HtmlCommand('#ajax_download_experiment_solution', ''));
- $response->addCommand(new HtmlCommand('#ajax_edit_experiment_solution', ''));
- }
-
- return $response;
- }
-
- public function _ajax_bulk_get_experiment_list($lab_default_value = '') {
- $experiments = [
- '0' => 'Please select...',
- ];
-
- // Get the database connection.
- $connection = Database::getConnection();
-
- // Prepare the query.
- $query = $connection->select('lab_migration_experiment', 'lme')
- ->fields('lme', ['id', 'number', 'title'])
- ->condition('proposal_id', $lab_default_value)
- ->orderBy('number', 'ASC');
-
- // Execute the query and fetch results.
- $experiments_q = $query->execute();
- // var_dump($experiment_q);die;
- foreach ($experiments_q as $experiments_data) {
- $experiments[$experiments_data->id] = $experiments_data->number . '. ' . $experiments_data->title;
+ else {
+ $solution_provider = 'Solution Provider ' . '' . 'Solution Provider: (Open) ' . ' ';
+ }
+
+ return 'About the Lab ' . '' . 'Proposer Name: ' . $lab_details->name_title . ' ' . $lab_details->name . ' ' . 'Title of the Lab: ' . $lab_details->lab_title . ' ' . 'Department: ' . $lab_details->department . ' ' . 'University: ' . $lab_details->university . ' ' . 'Version: ' . $lab_details->version . ' ' . 'Operating System: ' . $lab_details->operating_system . ' ' . ' ' . $solution_provider;
}
-
- return $experiments;
+ return '';
}
-
-
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ // No submit actions needed for download/display run form.
}
+
}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSettingsForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSettingsForm.php
index d9aa8c9..92c6707 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSettingsForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSettingsForm.php
@@ -7,10 +7,8 @@
namespace Drupal\lab_migration\Form;
-use Drupal\Core\Form\FormBase;
-use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
use Drupal\Core\Form\ConfigFormBase;
+use Drupal\Core\Form\FormStateInterface;
class LabMigrationSettingsForm extends ConfigFormBase {
@@ -21,12 +19,19 @@ public function getFormId() {
return 'lab_migration_settings_form';
}
+ /**
+ * {@inheritdoc}
+ */
protected function getEditableConfigNames() {
return [
'lab_migration.settings',
];
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('lab_migration.settings');
$form['emails'] = [
@@ -38,33 +43,37 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_emails', ''),
];
+
$form['cc_emails'] = [
'#type' => 'textfield',
- '#title' => t('(Cc) Notification emails'),
+ '#title' => $this->t('(Cc) Notification emails'),
'#description' => $this->t('Specify emails id for Cc option of mail system with comma separated'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_cc_emails', ''),
];
+
$form['from_email'] = [
'#type' => 'textfield',
- '#title' => t('Outgoing from email address'),
+ '#title' => $this->t('Outgoing from email address'),
'#description' => $this->t('Email address to be display in the from field of all outgoing messages'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_from_email', ''),
];
+
$form['extensions']['source'] = [
'#type' => 'textfield',
- '#title' => t('Allowed source file extensions'),
+ '#title' => $this->t('Allowed source file extensions'),
'#description' => $this->t('A comma separated list WITHOUT SPACE of source file extensions that are permitted to be uploaded on the server'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_source_extensions', ''),
];
+
$form['extensions']['dependency'] = [
'#type' => 'textfield',
'#title' => $this->t('Allowed dependency file extensions'),
@@ -74,60 +83,58 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_dependency_extensions', ''),
];
+
$form['extensions']['result'] = [
'#type' => 'textfield',
- '#title' => t('Allowed result file extensions'),
+ '#title' => $this->t('Allowed result file extensions'),
'#description' => $this->t('A comma separated list WITHOUT SPACE of result file extensions that are permitted to be uploaded on the server'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_result_extensions', ''),
];
+
$form['extensions']['xcos'] = [
'#type' => 'textfield',
- '#title' => t('Allowed xcos file extensions'),
+ '#title' => $this->t('Allowed xcos file extensions'),
'#description' => $this->t('A comma separated list WITHOUT SPACE of xcos file extensions that are permitted to be uploaded on the server'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_xcos_extensions', ''),
];
+
$form['extensions']['pdf'] = [
'#type' => 'textfield',
- '#title' => t('Allowed pdf file extensions'),
+ '#title' => $this->t('Allowed pdf file extensions'),
'#description' => $this->t('A comma separated list WITHOUT SPACE of pdf file extensions that are permitted to be uploaded on the server'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $config->get('lab_migration_pdf_extensions', ''),
];
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => $this->t('Submit'),
- ];
- return $form;
- }
- public function validateForm(array &$form, FormStateInterface $form_state) {
- parent::validateForm($form, $form_state);
-
- return;
+ return parent::buildForm($form, $form_state);
}
+ /**
+ * {@inheritdoc}
+ */
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
+
$this->config('lab_migration.settings')
- ->set('lab_migration_emails', $form_state->getValue('emails'))
- ->set('lab_migration_cc_emails', $form_state->getValue('cc_emails'))
- ->set('lab_migration_from_email', $form_state->getValue('from_email'))
- ->set('lab_migration_source_extensions', $form_state->getValue('source'))
- ->set('lab_migration_dependency_extensions', $form_state->getValue('dependency'))
- ->set('lab_migration_result_extensions', $form_state->getValue('result'))
- ->set('lab_migration_xcos_extensions', $form_state->getValue('xcos'))
- ->set('lab_migration_pdf_extensions', $form_state->getValue('pdf'))
- ->save();
- \Drupal::messenger()->addMessage(t('Settings updated'), 'status');
+ ->set('lab_migration_emails', $form_state->getValue('emails'))
+ ->set('lab_migration_cc_emails', $form_state->getValue('cc_emails'))
+ ->set('lab_migration_from_email', $form_state->getValue('from_email'))
+ ->set('lab_migration_source_extensions', $form_state->getValue('source'))
+ ->set('lab_migration_dependency_extensions', $form_state->getValue('dependency'))
+ ->set('lab_migration_result_extensions', $form_state->getValue('result'))
+ ->set('lab_migration_xcos_extensions', $form_state->getValue('xcos'))
+ ->set('lab_migration_pdf_extensions', $form_state->getValue('pdf'))
+ ->save();
+
+ $this->messenger()->addMessage($this->t('Settings updated'));
}
}
-?>
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalApprovalForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalApprovalForm.php
index f5c4239..f2ce1a1 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalApprovalForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalApprovalForm.php
@@ -9,17 +9,85 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\Url;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Symfony\Component\HttpFoundation\Response;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\user\Entity\User;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\Core\Url;
use Drupal\Core\Link;
-use Drupal\Core\Config\ConfigFactoryInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedFormResponseException;
class LabMigrationSolutionProposalApprovalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * Constructs a new LabMigrationSolutionProposalApprovalForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ MailService $mail_service,
+ RequestStack $request_stack
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->mailService = $mail_service;
+ $this->requestStack = $request_stack;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('lab_migration.mail_service'),
+ $container->get('request_stack')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -27,298 +95,272 @@ public function getFormId() {
return 'lab_migration_solution_proposal_approval_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('proposal_id');
- // $proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- \Drupal::messenger()->addmessage($this->t('Invalid proposal selected. Please try again.'), 'error');
- // RedirectResponse('lab-migration/manage-proposal/pending-solution-proposal');
- // $url = Url::fromRoute('lab_migration.proposal_pending_solution');
- // $response = new RedirectResponse($url->toString());
- $form_state->setRedirect('lab_migration.manage_proposal.pending_solution_proposal');
- // Send the response back to the client
-
- return;
- }
- }
- else {
- \Drupal::messenger()->addMessage($this->t('Invalid proposal selected. Please try again.'), 'error');
- $form_state->setRedirect('lab_migration.manage_proposal.pending_solution_proposal'); return;
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('proposal_id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $response = new RedirectResponse(Url::fromRoute('lab_migration.solution_proposal_pending')->toString());
+ throw new EnforcedFormResponseException($response);
}
+
$form['name'] = [
'#type' => 'item',
- '#markup' => Link::fromTextAndUrl($proposal_data->solution_provider_name_title . ' ' . $proposal_data->solution_provider_name, 'user/' . $proposal_data->solution_provider_uid),
- '#title' => t('Solution Provider Name'),
+ '#markup' => Link::fromTextAndUrl(
+ $proposal_data->solution_provider_name_title . ' ' . $proposal_data->solution_provider_name,
+ Url::fromUri('internal:/user/' . $proposal_data->solution_provider_uid)
+ )->toString(),
+ '#title' => $this->t('Solution Provider Name'),
];
+
+ $solution_provider_user = User::load($proposal_data->solution_provider_uid);
$form['email_id'] = [
'#type' => 'item',
- '#markup' => loadMultiple($proposal_data->solution_provider_uid)->mail,
- '#title' => t('Solution Provider Email'),
+ '#markup' => $solution_provider_user ? $solution_provider_user->getEmail() : '',
+ '#title' => $this->t('Solution Provider Email'),
];
+
$form['contact_ph'] = [
'#type' => 'item',
'#markup' => $proposal_data->solution_provider_contact_ph,
- '#title' => t('Solution Provider Contact No.'),
+ '#title' => $this->t('Solution Provider Contact No.'),
];
+
$form['department'] = [
'#type' => 'item',
'#markup' => $proposal_data->solution_provider_department,
- '#title' => t('Department/Branch'),
+ '#title' => $this->t('Department/Branch'),
];
+
$form['university'] = [
'#type' => 'item',
'#markup' => $proposal_data->solution_provider_university,
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
];
$form['country'] = [
'#type' => 'item',
'#markup' => $proposal_data->solution_provider_country,
- '#title' => t('Country'),
+ '#title' => $this->t('Country'),
];
+
$form['all_state'] = [
'#type' => 'item',
'#markup' => $proposal_data->solution_provider_state,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
];
+
$form['city'] = [
'#type' => 'item',
'#markup' => $proposal_data->solution_provider_city,
- '#title' => t('City'),
+ '#title' => $this->t('City'),
];
+
$form['pincode'] = [
'#type' => 'item',
'#markup' => $proposal_data->solution_provider_pincode,
- '#title' => t('Pincode/Postal code'),
+ '#title' => $this->t('Pincode/Postal code'),
];
-
$form['dwsim_version'] = [
'#type' => 'item',
- '#title' => t('dwsim version used'),
+ '#title' => $this->t('dwsim version used'),
'#markup' => $proposal_data->dwsim_version,
];
-
$form['lab_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->lab_title,
- '#title' => t('Title of the Lab'),
+ '#title' => $this->t('Title of the Lab'),
];
+
/* get experiment details */
$experiment_list = '';
- //$experiment_q = $injected_database->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY id ASC", $proposal_id);
- $query = $injected_database->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('id', 'ASC');
- $experiment_q = $query->execute();
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->orderBy('id', 'ASC')
+ ->execute();
+
while ($experiment_data = $experiment_q->fetchObject()) {
$experiment_list .= '' . $experiment_data->title . ' Description of Experiment : ' . $experiment_data->description . ' ';
- ;
}
$experiment_list .= ' ';
+
$form['experiment'] = [
'#type' => 'item',
'#markup' => $experiment_list,
- '#title' => t('Experiments'),
+ '#title' => $this->t('Experiments'),
];
+
$form['solution_display'] = [
'#type' => 'item',
- '#title' => t('Display the solution on the www.dwsim.fossee.in website'),
- '#markup' => ($proposal_data->solution_display == 1) ? "Yes" : "No",
+ '#title' => $this->t('Display the solution on the website'),
+ '#markup' => ($proposal_data->solution_display == 1) ? $this->t('Yes') : $this->t('No'),
];
- /*if ($proposal_data->solution_provider_uid == 0)
- {
- $solution_provider = "Open";
- }
- else if ($proposal_data->solution_provider_uid == $proposal_data->uid)
- {
- $solution_provider = "Proposer will provide the solution of the lab";
- }
- else
- {
- $solution_provider_user_data = loadMultiple($proposal_data->solution_provider_uid);
- if ($solution_provider_user_data)
- {
- $solution_provider .= '' . 'Solution Provider: ' . l($solution_provider_user_data->name, 'user/' . $proposal_data->solution_provider_uid) . ' ' . 'Solution Provider Name: ' . $proposal_data->solution_provider_name_title . ' ' . $proposal_data->solution_provider_name . ' ' . 'Department: ' . $proposal_data->solution_provider_department . ' ' . 'University: ' . $proposal_data->solution_provider_university . ' ' . ' ';
- }
- else
- {
- $solution_provider = "User does not exists";
- }
- }*/
-
- $proposer .= '' . 'Proposer: ' . Link::fromTextAndUrl($proposal_data->name, 'user/' . $proposal_data->uid) . ' ' . 'Proposer Name: ' . $proposal_data->name_title . ' ' . $proposal_data->name . ' ' . 'Contact No: ' . $proposal_data->contact_ph . ' ' . 'Email: ' . loadMultiple($proposal_data->uid)->mail . ' ' . 'Department: ' . $proposal_data->department . ' ' . 'University: ' . $proposal_data->university . ' ' . 'Country: ' . $proposal_data->country . ' ' . 'State: ' . $proposal_data->state . ' ' . 'City: ' . $proposal_data->city . ' ' . 'Pincode: ' . $proposal_data->pincode . ' ' . ' ';
+
+ $proposer_user = User::load($proposal_data->uid);
+ $proposer_email = $proposer_user ? $proposer_user->getEmail() : '';
+
+ $proposer = '' . 'Proposer: ' . Link::fromTextAndUrl($proposal_data->name, Url::fromUri('internal:/user/' . $proposal_data->uid))->toString() . ' ' . 'Proposer Name: ' . $proposal_data->name_title . ' ' . $proposal_data->name . ' ' . 'Contact No: ' . $proposal_data->contact_ph . ' ' . 'Email: ' . $proposer_email . ' ' . 'Department: ' . $proposal_data->department . ' ' . 'University: ' . $proposal_data->university . ' ' . 'Country: ' . $proposal_data->country . ' ' . 'State: ' . $proposal_data->state . ' ' . 'City: ' . $proposal_data->city . ' ' . 'Pincode: ' . $proposal_data->pincode . ' ' . ' ';
+
$form['proposer_details'] = [
'#type' => 'item',
- '#title' => t('Proposer of Lab :'),
+ '#title' => $this->t('Proposer of Lab :'),
'#markup' => $proposer,
];
- /*$form['solution_provider_uid'] = array(
- '#type' => 'item',
- '#title' => t('Solution Provider'),
- '#markup' => $solution_provider
- );*/
+
$form['approval'] = [
'#type' => 'radios',
- '#title' => t('Solution Provider'),
+ '#title' => $this->t('Solution Provider'),
'#options' => [
- '1' => 'Approve',
- '2' => 'Disapprove',
+ '1' => $this->t('Approve'),
+ '2' => $this->t('Disapprove'),
],
'#required' => TRUE,
];
+
$form['message'] = [
'#type' => 'textarea',
- '#title' => t('Reason for disapproval'),
+ '#title' => $this->t('Reason for disapproval'),
];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
+
$form['cancel'] = [
'#type' => 'markup',
- '#value' => Link::fromTextAndUrl(t('Cancel'), 'lab-migration/manage-proposal/pending-solution-proposal'),
+ '#markup' => Link::fromTextAndUrl($this->t('Cancel'), Url::fromRoute('lab_migration.solution_proposal_pending'))->toString(),
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('proposal_id');
-
- // $solution_provider_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = $injected_database->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $solution_provider_q = $query->execute();
- $solution_provider_data = $solution_provider_q->fetchObject();
- // $solution_provider_present_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE solution_provider_uid = %d AND approval_status IN (0, 1) AND id != %d", $solution_provider_data->uid, $proposal_id);
- $query = $injected_database->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('solution_provider_uid', $solution_provider_data->uid);
- $query->condition('approval_status', [
- 0,
- 1,
- ], 'IN');
- $query->condition('id', $proposal_id, '<>');
- $solution_provider_present_q = $query->execute();
- if ($x = $solution_provider_present_q->fetchObject()) {
- add_message($proposal_id);
- $form_state->setErrorByName('', t('Solution provider has already one proposal active'));
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('proposal_id') : 0;
+
+ $solution_provider_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if ($solution_provider_data) {
+ $solution_provider_present_q = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('solution_provider_uid', $solution_provider_data->uid)
+ ->condition('approval_status', [0, 1], 'IN')
+ ->condition('id', $proposal_id, '<>')
+ ->execute();
+
+ if ($solution_provider_present_q->fetchObject()) {
+ $form_state->setErrorByName('', $this->t('Solution provider already has one active proposal.'));
+ }
}
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
-$proposal_id = (int) $route_match->getParameter('proposal_id');
-
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = $injected_database->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- }
- else {
- add_message(t('Invalid proposal selected. Please try again.'), 'error');
- RedirectResponse('lab-migration/manage-proposal/pending-solution-proposal');
- return;
- }
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('proposal_id') : 0;
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirect('lab_migration.solution_proposal_pending');
+ return;
}
- else {
- add_message(t('Invalid proposal selected. Please try again.'), 'error');
- RedirectResponse('lab-migration/manage-proposal/pending-solution-proposal');
+
+ $user_data = User::load($proposal_data->solution_provider_uid);
+ if (!$user_data) {
+ $this->messenger->addError($this->t('Solution provider user account does not exist.'));
+ $form_state->setRedirect('lab_migration.solution_proposal_pending');
return;
}
- $user_data = loadMultiple($proposal_data->solution_provider_uid);
- if ($form_state->getValue(['approval']) == 1) {
- $query = "UPDATE {lab_migration_proposal} SET solution_status = 2 WHERE id =:proposal_id";
- $args = [":proposal_id" => $proposal_id];
- $injected_database->query($query, $args);
+
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $this->currentUser->getEmail() . ', ' . $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ if ($form_state->getValue('approval') == 1) {
+ $this->database->update('lab_migration_proposal')
+ ->fields(['solution_status' => 2])
+ ->condition('id', $proposal_id)
+ ->execute();
+
/* sending email */
- $email_to = $user_data->mail;
- $from = $config->get('lab_migration_from_email', '');
- $bcc = $user->mail . ', ' . $config->get('lab_migration_emails', '');
- $cc = $config->get('lab_migration_cc_emails', '');
- $param['solution_proposal_approved']['proposal_id'] = $proposal_id;
- $param['solution_proposal_approved']['user_id'] = $proposal_data->solution_provider_uid;
- $param['solution_proposal_approved']['headers'] = [
+ $email_to = $user_data->getEmail();
+ $params['solution_proposal_approved']['proposal_id'] = $proposal_id;
+ $params['solution_proposal_approved']['user_id'] = $proposal_data->solution_provider_uid;
+ $params['solution_proposal_approved']['headers'] = [
'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
'Cc' => $cc,
'Bcc' => $bcc,
];
- if (!drupal_mail('lab_migration', 'solution_proposal_approved', $email_to, language_default(), $param, $from, TRUE)) {
- add_message('Error sending email message.', 'error');
+
+ if ($this->mailService->sendMail('lab_migration', 'solution_proposal_approved', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail notification sent successfully.'));
}
- /*$email_to = $user->mail . ', ' . $config->get('lab_migration_emails', '');
- if (!drupal_mail('lab_migration', 'solution_proposal_approved', $email_to , language_default(), $param, $config->get('lab_migration_from_email', NULL), TRUE))
- add_message('Error sending email message.', 'error');*/
- add_message('Lab migration solution proposal approved. User has been notified of the approval.', 'status');
- RedirectResponse('lab-migration/manage-proposal/pending-solution_proposal');
- return;
+
+ $this->messenger->addMessage($this->t('Lab migration solution proposal approved. User has been notified of the approval.'), 'status');
}
- else {
- if ($form_state->getValue(['approval']) == 2) {
- $query = "UPDATE {lab_migration_proposal} SET solution_provider_uid = :solution_provider_uid, solution_status = :solution_status, solution_provider_name_title = '', solution_provider_name = '', solution_provider_contact_ph = '', solution_provider_department = '', solution_provider_university = '' WHERE id = :proposal_id";
- $args = [
- ":solution_provider_uid" => 0,
- ":solution_status" => 0,
- ":proposal_id" => $proposal_id,
- ];
- $injected_database->query($query, $args);
- /* sending email */
- $email_to = $user_data->mail;
- $from = $config->get('lab_migration_from_email', '');
- $bcc = $user->mail . ', ' . $config->get('lab_migration_emails', '');
- $cc = $config->get('lab_migration_cc_emails', '');
- $param['solution_proposal_disapproved']['proposal_id'] = $proposal_id;
- $param['solution_proposal_disapproved']['user_id'] = $proposal_data->solution_provider_uid;
- $param['solution_proposal_disapproved']['message'] = $form_state->getValue(['message']);
- $param['solution_proposal_disapproved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('lab_migration', 'solution_proposal_disapproved', $email_to, language_default(), $param, $from, TRUE)) {
- add_message('Error sending email message.', 'error');
- }
- add_message('Lab migration solution proposal dis-approved. User has been notified of the dis-approval.', 'status');
- RedirectResponse('lab-migration/manage-proposal/pending-solution-proposal');
- return;
+ elseif ($form_state->getValue('approval') == 2) {
+ $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'solution_provider_uid' => 0,
+ 'solution_status' => 0,
+ 'solution_provider_name_title' => '',
+ 'solution_provider_name' => '',
+ 'solution_provider_contact_ph' => '',
+ 'solution_provider_department' => '',
+ 'solution_provider_university' => '',
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ /* sending email */
+ $email_to = $user_data->getEmail();
+ $params['solution_proposal_disapproved']['proposal_id'] = $proposal_id;
+ $params['solution_proposal_disapproved']['user_id'] = $proposal_data->solution_provider_uid;
+ $params['solution_proposal_disapproved']['message'] = $form_state->getValue('message');
+ $params['solution_proposal_disapproved']['headers'] = [
+ 'From' => $from,
+ 'Cc' => $cc,
+ 'Bcc' => $bcc,
+ ];
+
+ if ($this->mailService->sendMail('lab_migration', 'solution_proposal_disapproved', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail notification sent successfully.'));
}
+
+ $this->messenger->addMessage($this->t('Lab migration solution proposal dis-approved. User has been notified of the dis-approval.'), 'status');
}
+
+ $form_state->setRedirect('lab_migration.solution_proposal_pending');
}
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalForm.php
index 5950388..b3c751a 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationSolutionProposalForm.php
@@ -9,13 +9,96 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\user\Entity\User;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Symfony\Component\HttpFoundation\RedirectResponse;
-use Symfony\Component\HttpFoundation\Response;
+use Drupal\Core\Form\EnforcedFormResponseException;
+
class LabMigrationSolutionProposalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * Constructs a new LabMigrationSolutionProposalForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ LabMigrationGlobalfunction $lab_global,
+ MailService $mail_service,
+ RequestStack $request_stack
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->labGlobal = $lab_global;
+ $this->mailService = $mail_service;
+ $this->requestStack = $request_stack;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('lab_migration_global'),
+ $container->get('lab_migration.mail_service'),
+ $container->get('request_stack')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -23,426 +106,379 @@ public function getFormId() {
return 'lab_migration_solution_proposal_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- // $proposal_id = (int) arg(2);
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
- $route_match = \Drupal::routeMatch();
- $proposal_id = (int) $route_match->getParameter('id');
-
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
if (!$proposal_data) {
- \Drupal::messenger()->addmessage("Invalid proposal.", 'error');
- // RedirectResponse('');
-// $url = Url::fromRoute('lab_migration.proposal_pending'); // Replace with your actual route name
-// $response = new RedirectResponse($url->toString());
-
-// // Return the response
-// return $response;
+ $this->messenger->addError($this->t("Invalid proposal."));
+ $response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_open')->toString());
+ throw new EnforcedFormResponseException($response);
}
- $proposer_link = Link::fromTextAndUrl(
+ $proposer_link = Link::fromTextAndUrl(
$proposal_data->name_title . ' ' . $proposal_data->name,
Url::fromUri('internal:/user/' . $proposal_data->uid)
)->toRenderable();
-
-
+
$form['name'] = [
'#type' => 'item',
'#title' => $this->t('Proposer Name'),
'link' => $proposer_link,
];
-
+
$form['lab_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->lab_title,
- '#title' => t('Title of the Lab'),
+ '#title' => $this->t('Title of the Lab'),
];
+
$experiment_html = '';
- //$experiment_q = $injected_database->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_id);
- $experiment_q = $query->execute();
+ $experiment_q = $this->database->select('lab_migration_experiment')
+ ->fields('lab_migration_experiment')
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
while ($experiment_data = $experiment_q->fetchObject()) {
- $experiment_html .= $experiment_data->title ;
+ $experiment_html .= $experiment_data->title . ' ';
}
+
$form['experiment'] = [
'#type' => 'item',
'#markup' => $experiment_html,
'#title' => $this->t('Experiment List'),
];
+
$form['solution_provider_name_title'] = [
'#type' => 'select',
- '#title' => t('Title'),
+ '#title' => $this->t('Title'),
'#options' => [
- 'Mr' => 'Mr',
- 'Ms' => 'Ms',
- 'Mrs' => 'Mrs',
- 'Dr' => 'Dr',
- 'Prof' => 'Prof',
+ 'Mr' => $this->t('Mr'),
+ 'Ms' => $this->t('Ms'),
+ 'Mrs' => $this->t('Mrs'),
+ 'Dr' => $this->t('Dr'),
+ 'Prof' => $this->t('Prof'),
],
'#required' => TRUE,
];
+
$form['solution_provider_name'] = [
'#type' => 'textfield',
- '#title' => t('Name of the Solution Provider'),
+ '#title' => $this->t('Name of the Solution Provider'),
'#size' => 30,
'#maxlength' => 50,
'#required' => TRUE,
];
+
+ $user_email = '';
+ $user = User::load($this->currentUser->id());
+ if ($user) {
+ $user_email = $user->getEmail();
+ }
+
$form['solution_provider_email_id'] = [
'#type' => 'textfield',
- '#title' => t('Email'),
+ '#title' => $this->t('Email'),
'#size' => 30,
- '#value' => $user->getEmail(),
+ '#value' => $user_email,
'#disabled' => TRUE,
];
+
$form['solution_provider_contact_ph'] = [
'#type' => 'textfield',
- '#title' => t('Contact No.'),
+ '#title' => $this->t('Contact No.'),
'#size' => 30,
'#maxlength' => 15,
'#required' => TRUE,
];
+
$form['solution_provider_department'] = [
'#type' => 'select',
- '#title' => t('Department/Branch'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_departments(),
+ '#title' => $this->t('Department/Branch'),
+ '#options' => $this->labGlobal->_lm_list_of_departments(),
'#required' => TRUE,
];
+
$form['solution_provider_university'] = [
'#type' => 'textfield',
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
'#size' => 30,
'#maxlength' => 50,
'#required' => TRUE,
];
+
$form['country'] = [
'#type' => 'select',
- '#title' => t('Country'),
+ '#title' => $this->t('Country'),
'#options' => [
- 'India' => 'India',
- 'Others' => 'Others',
+ 'India' => $this->t('India'),
+ 'Others' => $this->t('Others'),
],
'#required' => TRUE,
'#tree' => TRUE,
'#validated' => TRUE,
];
+
$form['other_country'] = [
'#type' => 'textfield',
- '#title' => t('Other than India'),
+ '#title' => $this->t('Other than India'),
'#size' => 100,
'#attributes' => [
- 'placeholder' => t('Enter your country name')
- ],
+ 'placeholder' => $this->t('Enter your country name'),
+ ],
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['other_state'] = [
'#type' => 'textfield',
- '#title' => t('State other than India'),
+ '#title' => $this->t('State other than India'),
'#size' => 100,
'#attributes' => [
- 'placeholder' => t('Enter your state/region name')
- ],
+ 'placeholder' => $this->t('Enter your state/region name'),
+ ],
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['other_city'] = [
'#type' => 'textfield',
- '#title' => t('City other than India'),
+ '#title' => $this->t('City other than India'),
'#size' => 100,
'#attributes' => [
- 'placeholder' => t('Enter your city name')
- ],
+ 'placeholder' => $this->t('Enter your city name'),
+ ],
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
+ 'value' => 'Others',
+ ],
],
+ ],
];
+
$form['all_state'] = [
'#type' => 'select',
- '#title' => t('State'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_states(),
+ '#title' => $this->t('State'),
+ '#options' => $this->labGlobal->_lm_list_of_states(),
'#validated' => TRUE,
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
+ 'value' => 'India',
+ ],
],
+ ],
];
+
$form['city'] = [
'#type' => 'select',
- '#title' => t('City'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_cities(),
+ '#title' => $this->t('City'),
+ '#options' => $this->labGlobal->_lm_list_of_cities(),
'#states' => [
'visible' => [
':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
+ 'value' => 'India',
+ ],
],
+ ],
];
+
$form['pincode'] = [
'#type' => 'textfield',
- '#title' => t('Pincode'),
+ '#title' => $this->t('Pincode'),
'#size' => 30,
'#maxlength' => 6,
'#required' => FALSE,
'#attributes' => [
- 'placeholder' => 'Enter pincode....'
- ],
+ 'placeholder' => $this->t('Enter pincode....'),
+ ],
];
+
$form['version'] = [
'#type' => 'select',
- '#title' => t('Version'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_software_version(),
+ '#title' => $this->t('Version'),
+ '#options' => $this->labGlobal->_lm_list_of_software_version(),
'#required' => TRUE,
];
+
$form['older'] = [
'#type' => 'textfield',
'#size' => 30,
'#maxlength' => 50,
- //'#required' => TRUE,
- '#description' => t('Specify the Older version used'),
+ '#description' => $this->t('Specify the Older version used'),
'#states' => [
'visible' => [
':input[name="version"]' => [
- 'value' => 'olderversion'
- ]
- ]
+ 'value' => 'olderversion',
+ ],
],
+ ],
];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Apply for Solution'),
+ '#value' => $this->t('Apply for Solution'),
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- if ($form_state->getValue(['country']) == 'Others') {
- if ($form_state->getValue(['other_country']) == '') {
- $form_state->setErrorByName('other_country', t('Enter country name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if ($form_state->getValue('country') == 'Others') {
+ if ($form_state->getValue('other_country') == '') {
+ $form_state->setErrorByName('other_country', $this->t('Enter country name'));
}
else {
- $form_state->setValue(['country'], $form_state->getValue([
- 'other_country'
- ]));
+ $form_state->setValue('country', $form_state->getValue('other_country'));
}
- if ($form_state->getValue(['other_state']) == '') {
- $form_state->setErrorByName('other_state', t('Enter state name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
+
+ if ($form_state->getValue('other_state') == '') {
+ $form_state->setErrorByName('other_state', $this->t('Enter state name'));
}
else {
- $form_state->setValue(['all_state'], $form_state->getValue([
- 'other_state'
- ]));
+ $form_state->setValue('all_state', $form_state->getValue('other_state'));
}
- if ($form_state->getValue(['other_city']) == '') {
- $form_state->setErrorByName('other_city', t('Enter city name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
+
+ if ($form_state->getValue('other_city') == '') {
+ $form_state->setErrorByName('other_city', $this->t('Enter city name'));
}
else {
- $form_state->setValue(['city'], $form_state->getValue(['other_city']));
+ $form_state->setValue('city', $form_state->getValue('other_city'));
}
}
else {
- if ($form_state->getValue(['country']) == '') {
- $form_state->setErrorByName('country', t('Select country name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
+ if ($form_state->getValue('country') == '') {
+ $form_state->setErrorByName('country', $this->t('Select country name'));
}
- if ($form_state->getValue(['all_state']) == '') {
- $form_state->setErrorByName('all_state', t('Select state name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
+ if ($form_state->getValue('all_state') == '') {
+ $form_state->setErrorByName('all_state', $this->t('Select state name'));
}
- if ($form_state->getValue(['city']) == '') {
- $form_state->setErrorByName('city', t('Select city name'));
- // $form_state['values']['country'] = $form_state['values']['other_country'];
+ if ($form_state->getValue('city') == '') {
+ $form_state->setErrorByName('city', $this->t('Select city name'));
}
}
- if ($form_state->getValue(['version']) == 'olderversion') {
- if ($form_state->getValue(['older']) == '') {
- $form_state->setErrorByName('older', t('Please provide valid version'));
+ if ($form_state->getValue('version') == 'olderversion') {
+ if ($form_state->getValue('older') == '') {
+ $form_state->setErrorByName('older', $this->t('Please provide valid version'));
}
}
- return;
- //$solution_provider_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE solution_provider_uid = ".$user->uid." AND approval_status IN (0, 1) AND solution_status IN (0, 1, 2)");
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('solution_provider_uid', $user->uid);
- $query->condition('approval_status', [
- 0,
- 1,
- ], 'IN');
- $query->condition('solution_status', [
- 0,
- 1,
- 2,
- ], 'IN');
- $solution_provider_q = $query->execute();
+
+ $solution_provider_q = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('solution_provider_uid', $this->currentUser->id())
+ ->condition('approval_status', [0, 1], 'IN')
+ ->condition('solution_status', [0, 1, 2], 'IN')
+ ->execute();
+
if ($solution_provider_q->fetchObject()) {
- $form_state->setErrorByName('', t("You have already applied for a solution. Please compelete that before applying for another solution."));
- // RedirectResponse('lab-migration/open-proposal');
- $response = new RedirectResponse('/lab-migration/open-proposal');
- $response->send();
+ $form_state->setErrorByName('', $this->t("You have already applied for a solution. Please complete that before applying for another solution."));
+ $response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_open')->toString());
+ throw new EnforcedFormResponseException($response);
}
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- // $proposal_id = (int) arg(2);
- $route_match = \Drupal::routeMatch();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $route_match = $this->requestStack->getCurrentRequest()->attributes->get('_route_match');
+ $proposal_id = $route_match ? (int) $route_match->getParameter('id') : 0;
- $proposal_id = (int) $route_match->getParameter('id');
- if ($form_state->getValue(['version']) == 'olderversion') {
- $form_state->setValue(['version'], $form_state->getValue(['older']));
+ if ($form_state->getValue('version') == 'olderversion') {
+ $form_state->setValue('version', $form_state->getValue('older'));
}
- //$proposal_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
+
+ $proposal_data = $this->database->select('lab_migration_proposal')
+ ->fields('lab_migration_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
if (!$proposal_data) {
- \Drupal::messenger()->addmessage("Invalid proposal.", 'error');
- // RedirectResponse('/lab-migration/open-proposal');
- $response = new RedirectResponse('/lab-migration/open-proposal');
- $response->send();
+ $this->messenger->addError($this->t("Invalid proposal."));
+ $form_state->setRedirect('lab_migration.proposal_open');
+ return;
}
+
if ($proposal_data->solution_provider_uid != 0) {
- \Drupal::messenger()->addmessage("Someone has already applied for solving this Lab.", 'error');
- // RedirectResponse('lab-migration/open-proposal');
- $response = new RedirectResponse('/lab-migration/open-proposal');
- $response->send();
+ $this->messenger->addError($this->t("Someone has already applied for solving this Lab."));
+ $form_state->setRedirect('lab_migration.proposal_open');
+ return;
}
- $query = "UPDATE {lab_migration_proposal} set solution_provider_uid = :uid, solution_status = :solution_status, solution_provider_name_title = :solution_provider_name_title, solution_provider_name = :solution_provider_contact_name, solution_provider_contact_ph = :solution_provider_contact_ph, solution_provider_department = :solution_provider_department, solution_provider_university = :solution_provider_university , version = :dwsim_version WHERE id = :proposal_id";
- $args = [
- 'uid' => \Drupal::currentUser()->id(),
- "solution_status" => 1,
- "solution_provider_name_title" => $form_state->getValue(['solution_provider_name_title']),
- "solution_provider_contact_name" => $form_state->getValue(['solution_provider_name']),
- "solution_provider_contact_ph" => $form_state->getValue(['solution_provider_contact_ph']),
- "solution_provider_department" => $form_state->getValue(['solution_provider_department']),
- "solution_provider_university" => $form_state->getValue(['solution_provider_university']),
- "dwsim_version" => $form_state->getValue(['version']),
- "proposal_id" => $proposal_id,
- ];
- $result = \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addmessage("We have received your application. We will get back to you soon.", 'status');
- /* sending email */
- $email_to = $user->getEmail();
-
-/* Config */
-$config = \Drupal::config('lab_migration.settings');
-
-$from = $config->get('lab_migration_from_email');
-$bcc = $config->get('lab_migration_emails');
-$cc = $config->get('lab_migration_cc_emails');
-
-/* Mandatory fallback */
-if (empty($from)) {
- $from = \Drupal::config('system.site')->get('mail');
-}
-
-/* Params */
-$params['solution_proposal_received'] = [
- 'proposal_id' => $proposal_id,
- 'user_id' => $user->id(),
- 'headers' => [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ],
-];
-
-/* Language */
-$langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
-
-/* Send mail */
-$mailManager = \Drupal::service('plugin.manager.mail');
-
-$result = $mailManager->mail(
- 'lab_migration',
- 'solution_proposal_received',
- $email_to,
- $langcode,
- $params,
- $from,
- TRUE
-);
-
-if (empty($result['result'])) {
- \Drupal::messenger()->addError('Error sending email message.');
-}
-else {
- \Drupal::messenger()->addStatus('Email sent successfully.');
-}
-
- /* Sending email */
-
-$email_to = $config->get('lab_migration_emails');
-
-$from = $config->get('lab_migration_from_email');
-
-/* Fallback if from is empty */
-if (empty($from)) {
- $from = \Drupal::config('system.site')->get('mail');
-}
-
-/* Language */
-$langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
-
-/* Send mail */
-$mailManager = \Drupal::service('plugin.manager.mail');
-
-$result = $mailManager->mail(
- 'lab_migration',
- 'solution_proposal_received',
- $email_to,
- $langcode,
- $param,
- $from,
- TRUE
-);
-
-if (empty($result['result'])) {
- \Drupal::messenger()->addError('Error sending email message.');
-}
-// $response = new RedirectResponse('');
- // $response->send();
- }
+ $this->database->update('lab_migration_proposal')
+ ->fields([
+ 'solution_provider_uid' => $this->currentUser->id(),
+ 'solution_status' => 1,
+ 'solution_provider_name_title' => $form_state->getValue('solution_provider_name_title'),
+ 'solution_provider_name' => $form_state->getValue('solution_provider_name'),
+ 'solution_provider_contact_ph' => $form_state->getValue('solution_provider_contact_ph'),
+ 'solution_provider_department' => $form_state->getValue('solution_provider_department'),
+ 'solution_provider_university' => $form_state->getValue('solution_provider_university'),
+ 'version' => $form_state->getValue('version'),
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ $this->messenger->addMessage($this->t("We have received your application. We will get back to you soon."), 'status');
+
+ $user = User::load($this->currentUser->id());
+ if ($user && $user->getEmail()) {
+ $email_to = $user->getEmail();
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ if (empty($from)) {
+ $from = $this->configFactory()->get('system.site')->get('mail');
+ }
+ $params['solution_proposal_received'] = [
+ 'proposal_id' => $proposal_id,
+ 'user_id' => $user->id(),
+ 'headers' => [
+ 'From' => $from,
+ 'Cc' => $cc,
+ 'Bcc' => $bcc,
+ ],
+ ];
+
+ if ($this->mailService->sendMail('lab_migration', 'solution_proposal_received', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Confirmation email sent successfully.'));
+ }
+
+ $email_admin = $config->get('lab_migration_emails');
+ if ($email_admin) {
+ $this->mailService->sendMail('lab_migration', 'solution_proposal_received', $email_admin, $params);
+ }
+ }
+
+ $form_state->setRedirect('lab_migration.proposal_open');
+ }
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationUploadCodeForm.php b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationUploadCodeForm.php
index 15e52df..2839b43 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationUploadCodeForm.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Form/LabMigrationUploadCodeForm.php
@@ -9,20 +9,95 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\lab_migration\Services\LabMigrationGlobalfunction;
+use Drupal\lab_migration\Services\MailService;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\user\Entity\User;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
-use Drupal\Core\Config\ConfigFactoryInterface;
-use Drupal\Core\Database\Database;
-use Drupal\file\Entity\File;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedFormResponseException;
+class LabMigrationUploadCodeForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
-class LabMigrationUploadCodeForm extends FormBase {
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+ /**
+ * The lab migration global service.
+ *
+ * @var \Drupal\lab_migration\Services\LabMigrationGlobalfunction
+ */
+ protected $labGlobal;
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\lab_migration\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * Constructs a new LabMigrationUploadCodeForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ LabMigrationGlobalfunction $lab_global,
+ MailService $mail_service,
+ RequestStack $request_stack
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->labGlobal = $lab_global;
+ $this->mailService = $mail_service;
+ $this->requestStack = $request_stack;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('lab_migration_global'),
+ $container->get('lab_migration.mail_service'),
+ $container->get('request_stack')
+ );
+ }
/**
* {@inheritdoc}
@@ -31,63 +106,31 @@ public function getFormId() {
return 'lab_migration_upload_code_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $config = \Drupal::config('lab_migration.settings'); // Load the configuration
- // $user = \Drupal::currentUser();
-
- $proposal_data = \Drupal::service("lab_migration_global")->lab_migration_get_proposal();
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $proposal_data = $this->labGlobal->lab_migration_get_proposal();
if (!$proposal_data) {
- // RedirectResponse('');
$response = new RedirectResponse(Url::fromRoute('lab_migration.proposal_form')->toString());
-$response->send();
- return;
- // var_dump($response);die;
+ throw new EnforcedFormResponseException($response);
}
- /* add javascript for dependency selection effects */
- $dep_selection_js = "(function ($) {
- //alert('ok');
- $('#edit-existing-depfile-dep-lab-title').change(function() {
- var dep_selected = '';
-
- /* showing and hiding relevant files */
- $('.form-checkboxes .option').hide();
- $('.form-checkboxes .option').each(function(index) {
- var activeClass = $('#edit-existing-depfile-dep-lab-title').va\Drupal\Core\Link;
- consloe.log(activeClass);
- if ($(this).children().hasClass(activeClass)) {
- $(this).show();
- }
- if ($(this).children().attr('checked') == true) {
- dep_selected += $(this).children().next().text() + ' ';
- }
- });
- /* showing list of already existing dependencies */
- $('#existing_depfile_selected').html(dep_selected);
- });
-
- $('.form-checkboxes .option').change(function() {
- $('#edit-existing-depfile-dep-lab-title').trigger('change');
- });
- $('#edit-existing-depfile-dep-lab-title').trigger('change');
- }(jQuery));";
- #attached($dep_selection_js, 'inline', 'header');
-
- $form['#attributes'] = ['enctype' => "multipart/form-data"];
+ $form['#attributes'] = ['enctype' => 'multipart/form-data'];
$form['lab_title'] = [
'#type' => 'item',
'#title' => $this->t('Title of the Lab'),
'#markup' => $proposal_data->lab_title,
];
- $form['name'] = [
- '#type' => 'item',
- '#title' => t('Proposer Name'),
+ $form['name'] = [
+ '#type' => 'item',
+ '#title' => $this->t('Proposer Name'),
'#markup' => $proposal_data->name_title . ' ' . $proposal_data->name,
];
- $query = \Drupal::database()->select('lab_migration_experiment', 'e')
+ $query = $this->database->select('lab_migration_experiment', 'e')
->fields('e')
->condition('proposal_id', $proposal_data->id)
->orderBy('id', 'ASC');
@@ -98,161 +141,137 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
$experiment_rows[$experiment_data->id] = $experiment_data->number . '. ' . $experiment_data->title;
}
- // var_dump($proposal_data);die;
- /* get experiment list */
- // $experiment_rows = [];
- // //$experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY id ASC", $proposal_data->id);
- // $query = \Drupal::database()->select('lab_migration_experiment');
- // $query->fields('lab_migration_experiment');
- // $query->condition('proposal_id', $proposal_data->id);
- // $query->orderBy('id', 'ASC');
- // $experiment_q = $query->execute();
- // while ($experiment_data = $experiment_q->fetchObject()) {
- // $experiment_rows[$experiment_data->id] = $experiment_data->number . '. ' . $experiment_data->title;
- // }
-
$form['experiment'] = [
'#type' => 'select',
- '#title' => t('Title of the Experiment'),
+ '#title' => $this->t('Title of the Experiment'),
'#options' => $experiment_rows,
- // '#multiple' => FALSE,
- // '#size' => 1,
'#required' => TRUE,
];
- // var_dump($experiment_rows);die;
-// var_dump($form);die;
+
$form['code_number'] = [
'#type' => 'textfield',
- '#title' => t('Code No'),
- // '#size' => 5,
- // '#maxlength' => 10,
- // '#description' => t(""),
+ '#title' => $this->t('Code No'),
'#required' => TRUE,
];
- // $form['code_caption'] = [
- // '#type' => 'textfield',
- // '#title' => t('Caption'),
- // '#size' => 40,
- // '#maxlength' => 255,
- // '#description' => t(''),
- // '#required' => TRUE,
- // ];
+
$form['code_caption'] = [
'#type' => 'textfield',
- '#title' => t('Caption'),
- '#description' => t('For eg: Shell & Tube Heat Exchanger Simulation'),
+ '#title' => $this->t('Caption'),
+ '#description' => $this->t('For eg: Shell & Tube Heat Exchanger Simulation'),
'#size' => 40,
'#maxlength' => 255,
'#required' => TRUE,
];
+
$form['os_used'] = [
'#type' => 'select',
- '#title' => t('Operating System used'),
+ '#title' => $this->t('Operating System used'),
'#options' => [
- 'Linux' => 'Linux',
- 'Windows' => 'Windows',
- 'Mac' => 'Mac',
+ 'Linux' => $this->t('Linux'),
+ 'Windows' => $this->t('Windows'),
+ 'Mac' => $this->t('Mac'),
],
'#required' => TRUE,
];
+
$form['version'] = [
'#type' => 'select',
- '#title' => t('DWSIM version used'),
- '#options' => \Drupal::service("lab_migration_global")->_lm_list_of_software_version(),
+ '#title' => $this->t('DWSIM version used'),
+ '#options' => $this->labGlobal->_lm_list_of_software_version(),
'#required' => TRUE,
];
+
$form['toolbox_used'] = [
'#type' => 'hidden',
- '#title' => t('Toolbox used (If any)'),
+ '#title' => $this->t('Toolbox used (If any)'),
'#default_value' => 'none',
];
+
$form['code_warning'] = [
'#type' => 'container',
- '#title' => t('Upload all the dwsim project files in .dwxml/dwxmz format'),
+ '#title' => $this->t('Upload all the dwsim project files in .dwxml/dwxmz format'),
'#prefix' => '',
'#suffix' => '
',
];
+
$form['sourcefile'] = [
'#type' => 'fieldset',
- '#title' => t('Main or Source Files'),
+ '#title' => $this->t('Main or Source Files'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
];
+
+ $config = $this->configFactory()->get('lab_migration.settings');
$extensions = $config->get('lab_migration_source_extensions') ?? '';
$form['sourcefile']['sourcefile1'] = [
'#type' => 'file',
- '#title' => t('Upload main or source file'),
+ '#title' => $this->t('Upload main or source file'),
'#size' => 48,
- '#description' => t('Only alphabets and numbers are allowed as a valid filename.') . ' ' . t('Allowed file extensions: ') .$extensions
-,
+ '#description' => $this->t('Only alphabets and numbers are allowed as a valid filename.') . ' ' . $this->t('Allowed file extensions: ') . $extensions,
];
-
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
+ $form['cancel_link'] = [
+ '#type' => 'markup',
+ '#markup' => Link::fromTextAndUrl($this->t('Cancel'), Url::fromRoute('lab_migration.list_experiments'))->toString(),
+ ];
-$form['cancel_link'] = [
- '#type' => 'markup',
- '#markup' => Link::fromTextAndUrl(t('Cancel'), Url::fromRoute('lab_migration.list_experiments'))->toString(),
-];
return $form;
-
}
+
private function lab_migration_check_code_number($code_number) {
- return preg_match('/^[0-9]+$/', $code_number); // Example regex for numeric-only check
+ return preg_match('/^[0-9]+$/', $code_number);
}
+
private function lab_migration_check_name($caption) {
- // Allows only alphabets, numbers, and spaces
return preg_match('/^[a-zA-Z0-9 ]+$/', $caption);
}
- public function validateForm(array &$form , FormStateInterface $form_state) {
- if (!$this->lab_migration_check_code_number($form_state->getValue(['code_number']))) {
- $form_state->setErrorByName('code_number', t('Invalid Code Number. Code Number can contain only numbers.'));
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (!$this->lab_migration_check_code_number($form_state->getValue('code_number'))) {
+ $form_state->setErrorByName('code_number', $this->t('Invalid Code Number. Code Number can contain only numbers.'));
}
- if (!$this->lab_migration_check_name($form_state->getValue(['code_caption']))) {
- $form_state->setErrorByName('code_caption', t('Caption can contain only alphabets, numbers and spaces.'));
+ if (!$this->lab_migration_check_name($form_state->getValue('code_caption'))) {
+ $form_state->setErrorByName('code_caption', $this->t('Caption can contain only alphabets, numbers and spaces.'));
}
- if (!$form_state->getValue(['os_used'])) {
- $form_state->setErrorByName('os_used', t('Please select the operating system used.'));
+ if (!$form_state->getValue('os_used')) {
+ $form_state->setErrorByName('os_used', $this->t('Please select the operating system used.'));
}
- if (!$form_state->getValue(['version'])) {
- $form_state->setErrorByName('version', t('Please select the version used.'));
+ if (!$form_state->getValue('version')) {
+ $form_state->setErrorByName('version', $this->t('Please select the version used.'));
}
if (isset($_FILES['files'])) {
- /* check if atleast one source or result file is uploaded */
- if (!($_FILES['files']['name']['sourcefile1'] )) {
- $form_state->setErrorByName('sourcefile1', t('Please upload atleast one main or source file.'));
+ if (empty($_FILES['files']['name']['sourcefile1'])) {
+ $form_state->setErrorByName('sourcefile1', $this->t('Please upload at least one main or source file.'));
}
- /* check for valid filename extensions */
foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
if ($file_name) {
- /* checking file type */
if (strstr($file_form_name, 'source')) {
$file_type = 'S';
}
+ elseif (strstr($file_form_name, 'result')) {
+ $file_type = 'R';
+ }
+ elseif (strstr($file_form_name, 'xcos')) {
+ $file_type = 'X';
+ }
else {
- if (strstr($file_form_name, 'result')) {
- $file_type = 'R';
- }
- else {
- if (strstr($file_form_name, 'xcos')) {
- $file_type = 'X';
- }
- else {
- $file_type = 'U';
- }
- }
+ $file_type = 'U';
}
- // var_dump($file_name);die;
- $config = $this->config('lab_migration.settings');
+
+ $config = $this->configFactory()->get('lab_migration.settings');
$allowed_extensions_str = '';
switch ($file_type) {
case 'S':
@@ -262,282 +281,177 @@ public function validateForm(array &$form , FormStateInterface $form_state) {
$allowed_extensions_str = $config->get('lab_migration_result_extensions') ?? '';
break;
case 'X':
- $allowed_extensions_str = $config->get('lab_migration_xcos_extensions' ) ?? '';
+ $allowed_extensions_str = $config->get('lab_migration_xcos_extensions') ?? '';
break;
}
+
$allowed_extensions = explode(',', $allowed_extensions_str);
$tmp_ext = explode('.', strtolower($_FILES['files']['name'][$file_form_name]));
$temp_extension = end($tmp_ext);
if (!in_array($temp_extension, $allowed_extensions)) {
- $form_state->setErrorByName($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.'));
+ $form_state->setErrorByName($file_form_name, $this->t('Only file with @ext extensions can be uploaded.', ['@ext' => $allowed_extensions_str]));
}
if ($_FILES['files']['size'][$file_form_name] <= 0) {
- $form_state->setErrorByName($file_form_name, t('File size cannot be zero.'));
+ $form_state->setErrorByName($file_form_name, $this->t('File size cannot be zero.'));
}
- $config = $this->config('lab_migration.settings');
-
- /* check if valid file name */
- // if (!lab_migration_check_valid_filename($_FILES['files']['name'][$file_form_name])) {
- // $form_state->setErrorByName($file_form_name, t('Invalid file name specified. Only alphabets and numbers are allowed as a valid filename.'));
- // }
}
}
-
-
+ }
}
-}
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $root_path = $this->labGlobal->lab_migration_path();
-public function submitForm(array &$form, FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
+ $proposal_data = $this->labGlobal->lab_migration_get_proposal();
+ if (!$proposal_data) {
+ $form_state->setRedirect('');
+ return;
+ }
- $root_path = \Drupal::service('lab_migration_global')->lab_migration_path();
+ $proposal_id = $proposal_data->id;
+ $proposal_directory = $proposal_data->directory_name;
- $proposal_data = \Drupal::service('lab_migration_global')->lab_migration_get_proposal();
- if (!$proposal_data) {
- return new RedirectResponse(Url::fromRoute('')->toString());
- }
-// var_dump($proposal_data);die;
- $proposal_id = $proposal_data->id;
- $proposal_directory = $proposal_data->directory_name;
-
- // Check experiment details.
- $experiment_id = (int) $form_state->getValue('experiment');
- $query = \Drupal::database()->select('lab_migration_experiment', 'e');
- $query->fields('e');
- $query->condition('id', $experiment_id);
- $query->condition('proposal_id', $proposal_id);
- $query->range(0, 1);
- $experiment_data = $query->execute()->fetchObject();
-
- // var_dump($experiment_id);die;
- if (!$experiment_data) {
- \Drupal::messenger()->addMessage("Invalid experiment selected", 'error');
- return new RedirectResponse(Url::fromRoute('lab_migration.list_experiments')->toString());
- }
+ $experiment_id = (int) $form_state->getValue('experiment');
+ $experiment_data = $this->database->select('lab_migration_experiment', 'e')
+ ->fields('e')
+ ->condition('id', $experiment_id)
+ ->condition('proposal_id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if (!$experiment_data) {
+ $this->messenger->addError($this->t("Invalid experiment selected"));
+ $form_state->setRedirect('lab_migration.list_experiments');
+ return;
+ }
- // Create directories.
- $dest_path = $proposal_directory . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path, 0775, TRUE);
- }
+ $dest_path = $proposal_directory . '/';
+ if (!is_dir($root_path . $dest_path)) {
+ mkdir($root_path . $dest_path, 0775, TRUE);
+ }
- $code_number = $experiment_data->number . '.' . $form_state->getValue('code_number');
+ $code_number = $experiment_data->number . '.' . $form_state->getValue('code_number');
- // Check if solution already exists.
- $query = \Drupal::database()->select('lab_migration_solution', 's');
- $query->fields('s');
- $query->condition('experiment_id', $experiment_id);
- $query->condition('code_number', $code_number);
- $cur_solution_d = $query->execute()->fetchObject();
+ $cur_solution_d = $this->database->select('lab_migration_solution', 's')
+ ->fields('s')
+ ->condition('experiment_id', $experiment_id)
+ ->condition('code_number', $code_number)
+ ->execute()
+ ->fetchObject();
- if ($cur_solution_d) {
- if ($cur_solution_d->approval_status == 1) {
- \Drupal::messenger()->addMessage(t("Solution already approved. Cannot overwrite it."), 'error');
- return new RedirectResponse(Url::fromRoute('lab_migration.list_experiments')->toString());
- }
- elseif ($cur_solution_d->approval_status == 0) {
- \Drupal::messenger()->addMessage(t("Solution is under pending review. Delete the solution and reupload it."), 'error');
- return new RedirectResponse(Url::fromRoute('lab_migration.list_experiments')->toString());
+ if ($cur_solution_d) {
+ if ($cur_solution_d->approval_status == 1) {
+ $this->messenger->addError($this->t("Solution already approved. Cannot overwrite it."));
+ $form_state->setRedirect('lab_migration.list_experiments');
+ return;
+ }
+ elseif ($cur_solution_d->approval_status == 0) {
+ $this->messenger->addError($this->t("Solution is under pending review. Delete the solution and reupload it."));
+ $form_state->setRedirect('lab_migration.list_experiments');
+ return;
+ }
+ else {
+ $this->messenger->addError($this->t("Error uploading solution. Please contact administrator."));
+ $form_state->setRedirect('lab_migration.list_experiments');
+ return;
+ }
}
- else {
- \Drupal::messenger()->addMessage(t("Error uploading solution. Please contact administrator."), 'error');
- return new RedirectResponse(Url::fromRoute('lab_migration.list_experiments')->toString());
+
+ $dest_path .= 'EXP' . $experiment_data->number . '/';
+ if (!is_dir($root_path . $dest_path)) {
+ mkdir($root_path . $dest_path, 0775, TRUE);
}
- }
- // Create experiment directories.
- $dest_path .= 'EXP' . $experiment_data->number . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path, 0775, TRUE);
- }
+ $dest_path .= 'CODE' . $experiment_data->number . '.' . $form_state->getValue('code_number') . '/';
+ if (!is_dir($root_path . $dest_path)) {
+ mkdir($root_path . $dest_path, 0775, TRUE);
+ }
- // Create code directories.
- $dest_path .= 'CODE' . $experiment_data->number . '.' . $form_state->getValue('code_number') . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path, 0775, TRUE);
- }
+ $file_path = 'EXP' . $experiment_data->number . '/' . 'CODE' . $experiment_data->number . '.' . $form_state->getValue('code_number') . '/';
+
+ $solution_id = $this->database->insert('lab_migration_solution')
+ ->fields([
+ 'experiment_id' => $experiment_id,
+ 'approver_uid' => 0,
+ 'code_number' => $code_number,
+ 'caption' => $form_state->getValue('code_caption'),
+ 'approval_date' => 0,
+ 'approval_status' => 0,
+ 'timestamp' => time(),
+ 'os_used' => $form_state->getValue('os_used'),
+ 'dwsim_version' => $form_state->getValue('version') ?? '',
+ 'toolbox_used' => $form_state->getValue('toolbox_used'),
+ ])
+ ->execute();
+
+ foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
+ if ($file_name) {
+ if (strstr($file_form_name, 'source')) {
+ $file_type = 'S';
+ }
+ elseif (strstr($file_form_name, 'result')) {
+ $file_type = 'R';
+ }
+ elseif (strstr($file_form_name, 'xcos')) {
+ $file_type = 'X';
+ }
+ else {
+ $file_type = 'U';
+ }
- $file_path = 'EXP' . $experiment_data->number . '/' . 'CODE' . $experiment_data->number . '.' . $form_state->getValue('code_number') . '/';
-
- // Insert solution.
- $query = "INSERT INTO {lab_migration_solution}
- (experiment_id, approver_uid, code_number, caption, approval_date, approval_status, timestamp, os_used, dwsim_version, toolbox_used)
- VALUES (:experiment_id, :approver_uid, :code_number, :caption, :approval_date, :approval_status, :timestamp, :os_used, :dwsim_version, :toolbox_used)";
- $args = [
- ":experiment_id" => $experiment_id,
- ":approver_uid" => 0,
- ":code_number" => $code_number,
- ":caption" => $form_state->getValue('code_caption'),
- ":approval_date" => 0,
- ":approval_status" => 0,
- ":timestamp" => time(),
- ":os_used" => $form_state->getValue('os_used'),
- // ":dwsim_version" => $form_state->getValue('dwsim_version'),
- ":dwsim_version" => $form_state->getValue('dwsim_version') ?? '',
-
- ":toolbox_used" => $form_state->getValue('toolbox_used'),
- ];
- $solution_id = \Drupal::database()->query($query, $args, ['return' => Database::RETURN_INSERT_ID]);
-
- if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- // Insert into DB
- $query = "INSERT INTO {lab_migration_solution_files}
- (solution_id, filename, filepath, filemime, filesize, filetype, timestamp)
- VALUES (:solution_id, :filename, :filepath, :filemime, :filesize, :filetype, :timestamp)";
- $args = [
- ":solution_id" => $solution_id,
- ":filename" => $_FILES['files']['name'][$file_form_name],
- ":filepath" => $file_path . $_FILES['files']['name'][$file_form_name],
- ":filemime" => mime_content_type($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]),
- ":filesize" => $_FILES['files']['size'][$file_form_name],
- ":filetype" => $file_type,
- ":timestamp" => time(),
- ];
- \Drupal::database()->query($query, $args);
-}
-
- /* uploading files */
- // foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- // if ($file_name) {
- // /* checking file type */
- // if (strstr($file_form_name, 'source')) {
- // $file_type = 'S';
- // }
- // else {
- // if (strstr($file_form_name, 'result')) {
- // $file_type = 'R';
- // }
- // else {
- // if (strstr($file_form_name, 'xcos')) {
- // $file_type = 'X';
- // }
- // else {
- // $file_type = 'U';
- // }
- // }
- // }
-
- // if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- // \Drupal::database()->addmessage(t("Error uploading file. File !filename already exists.", [
- // '!filename' => $_FILES['files']['name'][$file_form_name]
- // ]), 'error');
- // return;
- // }
-
- // /* uploading file */
- // if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- // /* for uploaded files making an entry in the database */
- // $query = "INSERT INTO {lab_migration_solution_files} (solution_id, filename, filepath, filemime, filesize, filetype, timestamp)
- // VALUES (:solution_id, :filename, :filepath, :filemime, :filesize, :filetype, :timestamp)";
- // $args = [
- // ":solution_id" => $solution_id,
- // ":filename" => $_FILES['files']['name'][$file_form_name],
- // ":filepath" => $file_path . $_FILES['files']['name'][$file_form_name],
- // ":filemime" => mime_content_type($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]),
- // ":filesize" => $_FILES['files']['size'][$file_form_name],
- // ":filetype" => $file_type,
- // ":timestamp" => time(),
- // ];
- // }
- // }
- // }
-
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- if ($file_name) {
-
- // Determine file type
- if (strstr($file_form_name, 'source')) {
- $file_type = 'S';
- }
- elseif (strstr($file_form_name, 'result')) {
- $file_type = 'R';
- }
- elseif (strstr($file_form_name, 'xcos')) {
- $file_type = 'X';
- }
- else {
- $file_type = 'U';
- }
+ if (file_exists($root_path . $dest_path . $file_name)) {
+ $this->messenger->addError($this->t("Error uploading file. File @filename already exists.", [
+ '@filename' => $file_name,
+ ]));
+ return;
+ }
- // Check duplicate files
- if (file_exists($root_path . $dest_path . $file_name)) {
- \Drupal::messenger()->addMessage(t("Error uploading file. File @filename already exists.", [
- '@filename' => $file_name,
- ]), 'error');
- return;
+ if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $file_name)) {
+ $this->database->insert('lab_migration_solution_files')
+ ->fields([
+ 'solution_id' => $solution_id,
+ 'filename' => $file_name,
+ 'filepath' => $file_path . $file_name,
+ 'filemime' => mime_content_type($root_path . $dest_path . $file_name),
+ 'filesize' => $_FILES['files']['size'][$file_form_name],
+ 'filetype' => $file_type,
+ 'timestamp' => time(),
+ ])
+ ->execute();
+ }
+ }
}
- // Upload file
- if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $file_name)) {
-
- // Insert database record
- $insert_query = "
- INSERT INTO {lab_migration_solution_files}
- (solution_id, filename, filepath, filemime, filesize, filetype, timestamp)
- VALUES (:solution_id, :filename, :filepath, :filemime, :filesize, :filetype, :timestamp)";
-
- $insert_args = [
- ':solution_id' => $solution_id,
- ':filename' => $file_name,
- ':filepath' => $file_path . $file_name,
- ':filemime' => mime_content_type($root_path . $dest_path . $file_name),
- ':filesize' => $_FILES['files']['size'][$file_form_name],
- ':filetype' => $file_type,
- ':timestamp' => time(),
+ $this->messenger->addMessage($this->t('Solution uploaded successfully.'), 'status');
+
+ $user_data = User::load($proposal_data->uid);
+ if ($user_data && $user_data->getEmail()) {
+ $email_to = $user_data->getEmail();
+ $config = $this->configFactory()->get('lab_migration.settings');
+ $from = $config->get('lab_migration_from_email');
+ $bcc = $config->get('lab_migration_emails');
+ $cc = $config->get('lab_migration_cc_emails');
+
+ $params['solution_uploaded'] = [
+ 'solution_id' => $solution_id,
+ 'user_id' => $this->currentUser->id(),
+ 'headers' => [
+ 'From' => $from,
+ 'Cc' => $cc,
+ 'Bcc' => $bcc,
+ ],
];
- \Drupal::database()->query($insert_query, $insert_args);
- }
- }
-}
-
- \Drupal::messenger()->addMessage('Solution uploaded successfully.', 'status');
-
- $user_data = \Drupal::entityTypeManager()->getStorage('user')->load($proposal_data->uid);
-$email_to = $user_data->getEmail();
- $from = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
-$bcc = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
-$cc = \Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
-
- $params['solution_uploaded']['solution_id'] = $solution_id;
-$params['solution_uploaded']['user_id'] = $user->uid;
-
-$params['solution_uploaded']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
-];
-
-$langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
-$mail_manager = \Drupal::service('plugin.manager.mail');
-
-$result = $mail_manager->mail(
- 'lab_migration',
- 'solution_uploaded',
- $email_to,
- $langcode,
- $params,
- NULL,
- TRUE
-);
-
-if (!$result['result']) {
- \Drupal::messenger()->addMessage('Mail sent successfully');
-}
-
- \Drupal::messenger()->addStatus($this->t('Solution uploaded successfully.'));
- (new RedirectResponse(Url::fromRoute('lab_migration.list_experiments')->toString()))->send();
-
- $response = new RedirectResponse(Url::fromRoute('lab_migration.upload_code_form')->toString());
- // Send the redirect response
- $response->send();
-
- // RedirectResponse('lab-migration/code/upload');
+ if ($this->mailService->sendMail('lab_migration', 'solution_uploaded', $email_to, $params)) {
+ $this->messenger->addMessage($this->t('Mail notification sent successfully.'));
}
}
-
\ No newline at end of file
+
+ $form_state->setRedirect('lab_migration.list_experiments');
+ }
+
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Services/AjaxHelper.php b/modules/custom/DWSIM_lab_migration_module/src/Services/AjaxHelper.php
new file mode 100644
index 0000000..4d09309
--- /dev/null
+++ b/modules/custom/DWSIM_lab_migration_module/src/Services/AjaxHelper.php
@@ -0,0 +1,132 @@
+renderer = $renderer;
+ }
+
+ /**
+ * Replaces the HTML of a given CSS selector.
+ *
+ * @param string $selector
+ * The CSS selector to target.
+ * @param string|array $content
+ * The replacement content (string or render array).
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function replaceWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new ReplaceCommand($selector, $rendered));
+ return $response;
+ }
+
+ /**
+ * Sets the inner HTML of a given CSS selector.
+ *
+ * @param string $selector
+ * The CSS selector to target.
+ * @param string|array $content
+ * The content to inject (string or render array).
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function htmlWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new HtmlCommand($selector, $rendered));
+ return $response;
+ }
+
+ /**
+ * Generates a DataCommand response for setting jQuery data attributes.
+ *
+ * @param string $selector
+ * The CSS selector.
+ * @param string $name
+ * The data attribute name.
+ * @param mixed $value
+ * The data value.
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function dataCommand($selector, $name, $value) {
+ $response = new AjaxResponse();
+ $response->addCommand(new DataCommand($selector, $name, $value));
+ return $response;
+ }
+
+ /**
+ * Returns a status/warning/error message command.
+ *
+ * @param string $message
+ * The message text.
+ * @param string $type
+ * Message type: 'status', 'warning', or 'error'. Defaults to 'status'.
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function messageCommand($message, $type = 'status') {
+ $response = new AjaxResponse();
+ $response->addCommand(new MessageCommand($message, NULL, ['type' => $type]));
+ return $response;
+ }
+
+ /**
+ * Builds a response with multiple HTML/Replace/Data commands at once.
+ *
+ * @param array $commands
+ * Keyed array of commands. Each entry must have:
+ * - 'type': 'html', 'replace', or 'data'
+ * - 'content': the content (for html/replace)
+ * - 'name' and 'value': for data type
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function buildMultiCommandResponse(array $commands) {
+ $response = new AjaxResponse();
+ foreach ($commands as $selector => $data) {
+ $rendered = isset($data['content']) && is_array($data['content'])
+ ? $this->renderer->render($data['content'])
+ : ($data['content'] ?? '');
+
+ if ($data['type'] === 'html') {
+ $response->addCommand(new HtmlCommand($selector, $rendered));
+ }
+ elseif ($data['type'] === 'replace') {
+ $response->addCommand(new ReplaceCommand($selector, $rendered));
+ }
+ elseif ($data['type'] === 'data') {
+ $response->addCommand(new DataCommand($selector, $data['name'], $data['value']));
+ }
+ }
+ return $response;
+ }
+
+}
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Services/LabMigrationGlobalfunction.php b/modules/custom/DWSIM_lab_migration_module/src/Services/LabMigrationGlobalfunction.php
index bab73d9..c9938b1 100755
--- a/modules/custom/DWSIM_lab_migration_module/src/Services/LabMigrationGlobalfunction.php
+++ b/modules/custom/DWSIM_lab_migration_module/src/Services/LabMigrationGlobalfunction.php
@@ -1,1221 +1,803 @@
database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->moduleHandler = $module_handler;
+ $this->fileSystem = $file_system;
+ $this->mailService = $mail_service;
+ }
- public function _list_of_labs()
- {
- $lab_titles = array(
- '0' => 'Please select...'
- );
- //$lab_titles_q = $injected_database->query("SELECT * FROM {lab_migration_proposal} WHERE solution_display = 1 ORDER BY lab_title ASC");
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('solution_display', 1);
- $query->condition('approval_status', 3);
- $query->orderBy('lab_title', 'ASC');
- $lab_titles_q = $query->execute();
- while ($lab_titles_data = $lab_titles_q->fetchObject())
- {
- $lab_titles[$lab_titles_data->id] = $lab_titles_data->lab_title . ' (Proposed by ' . $lab_titles_data->name_title .' '.$lab_titles_data->name . ')';
- }
+ /**
+ * Returns list of approved labs for select options.
+ */
+ public function _list_of_labs() {
+ $lab_titles = ['0' => 'Please select...'];
+ $result = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('solution_display', 1)
+ ->condition('approval_status', 3)
+ ->orderBy('lab_title', 'ASC')
+ ->execute();
+ foreach ($result as $row) {
+ $lab_titles[$row->id] = $row->lab_title . ' (Proposed by ' . $row->name_title . ' ' . $row->name . ')';
+ }
return $lab_titles;
}
- public function _lm_list_of_states()
- {
- $states = array(0 => '-Select-');
- $query = \Drupal::database()->select('list_states_of_india');
- $query->fields('list_states_of_india');
- //$query->orderBy('', '');
- $states_list = $query->execute();
- while ($states_list_data = $states_list->fetchObject())
- {
- $states[$states_list_data->state] = $states_list_data->state;
- }
+
+ /**
+ * Returns list of Indian states from list_states_of_india table.
+ */
+ public function _lm_list_of_states() {
+ $states = [0 => '-Select-'];
+ $result = $this->database->select('list_states_of_india', 's')
+ ->fields('s')
+ ->execute();
+ foreach ($result as $row) {
+ $states[$row->state] = $row->state;
+ }
return $states;
}
- public function _lab_migration_list_of_states()
-{
- $states = array(''=> '- Select -');
- $states_list = \Drupal::database()->query("SELECT state FROM all_india_pincode WHERE country = 'India' ORDER BY state ASC");
- while ($states_list_data = $states_list->fetchObject())
- {
- $states[$states_list_data->state] = $states_list_data->state;
+
+ /**
+ * Returns list of Indian states from all_india_pincode table.
+ */
+ public function _lab_migration_list_of_states() {
+ $states = ['' => '- Select -'];
+ $result = $this->database->query(
+ "SELECT DISTINCT state FROM {all_india_pincode} WHERE country = 'India' ORDER BY state ASC"
+ );
+ foreach ($result as $row) {
+ $states[$row->state] = $row->state;
}
return $states;
-}
-
-public function _lm_list_of_cities()
- {
- $city = array(0 => '-Select-');
- $query = \Drupal::database()->select('list_cities_of_india');
- $query->fields('list_cities_of_india');
- $query->orderBy('city', 'ASC');
- $city_list = $query->execute();
- while ($city_list_data = $city_list->fetchObject())
- {
- $city[$city_list_data->city] = $city_list_data->city;
- }
+ }
+
+ /**
+ * Returns list of Indian cities for select options.
+ */
+ public function _lm_list_of_cities() {
+ $city = [0 => '-Select-'];
+ $result = $this->database->select('list_cities_of_india', 'c')
+ ->fields('c')
+ ->orderBy('city', 'ASC')
+ ->execute();
+ foreach ($result as $row) {
+ $city[$row->city] = $row->city;
+ }
return $city;
}
- public function _lab_migration_list_of_city_pincode($city=Null, $state=NULL, $district=NULL)
-{
- $pincode = array();
- if($city){
- $pincode_list = \Drupal::database()->query("SELECT pincode FROM all_india_pincode WHERE city = :city AND state = :state AND district = :district", array(':city' => $city,':state'=> $state, ':district' => $district));
- while ($pincode_list_data = $pincode_list->fetchObject())
- {
- $pincode[$pincode_list_data->pincode] = $pincode_list_data->pincode;
- }
+ /**
+ * Returns list of pincodes for a given city/state/district.
+ */
+ public function _lab_migration_list_of_city_pincode($city = NULL, $state = NULL, $district = NULL) {
+ $pincode = [];
+ if ($city) {
+ $result = $this->database->query(
+ "SELECT pincode FROM {all_india_pincode} WHERE city = :city AND state = :state AND district = :district",
+ [':city' => $city, ':state' => $state, ':district' => $district]
+ );
+ foreach ($result as $row) {
+ $pincode[$row->pincode] = $row->pincode;
+ }
}
- else{
- $pincode[000000] = '000000';
+ else {
+ $pincode['000000'] = '000000';
}
return $pincode;
-}
-
- public function _lm_list_of_departments()
- {
- $department = array();
- $query = \Drupal::database()->select('list_of_departments');
- $query->fields('list_of_departments');
- $query->orderBy('id', 'DESC');
- $department_list = $query->execute();
- while ($department_list_data = $department_list->fetchObject())
- {
- $department[$department_list_data->department] = $department_list_data->department;
- }
+ }
+
+ /**
+ * Returns list of departments for select options.
+ */
+ public function _lm_list_of_departments() {
+ $department = [];
+ $result = $this->database->select('list_of_departments', 'd')
+ ->fields('d')
+ ->orderBy('id', 'DESC')
+ ->execute();
+ foreach ($result as $row) {
+ $department[$row->department] = $row->department;
+ }
return $department;
}
- public function _lm_list_of_software_version()
- {
- $software_version = array();
- $query = \Drupal::database()->select('dwsim_software_version');
- $query->fields('dwsim_software_version');
- //$query->orderBy('id', 'DESC');
- $software_version_list = $query->execute();
- while ($software_version_list_data = $software_version_list->fetchObject())
- {
- $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
- }
- return $software_version;
+ /**
+ * Returns list of DWSIM software versions for select options.
+ */
+ public function _lm_list_of_software_version() {
+ $versions = [];
+ $result = $this->database->select('dwsim_software_version', 'v')
+ ->fields('v')
+ ->execute();
+ foreach ($result as $row) {
+ $versions[$row->dwsim_version] = $row->dwsim_version;
+ }
+ return $versions;
}
- public function _lab_migration_list_of_district($state=Null)
-{
- $district = array(''=> '- Select -');
- if($state){
- $district_list = \Drupal::database()->query("SELECT district FROM all_india_pincode WHERE state = :state ORDER BY district ASC", array(':state'=> $state));
- while ($district_list_data = $district_list->fetchObject())
- {
- $district[$district_list_data->district] = $district_list_data->district;
- }
+ /**
+ * Returns list of districts for a given state.
+ */
+ public function _lab_migration_list_of_district($state = NULL) {
+ $district = ['' => '- Select -'];
+ if ($state) {
+ $result = $this->database->query(
+ "SELECT DISTINCT district FROM {all_india_pincode} WHERE state = :state ORDER BY district ASC",
+ [':state' => $state]
+ );
+ foreach ($result as $row) {
+ $district[$row->district] = $row->district;
+ }
}
return $district;
-}
-public function _lm_dir_name($lab, $name, $university)
- {
- $lab_title = \Drupal::service("lab_migration_global")->lm_ucname($lab);
- $proposar_name = \Drupal::service("lab_migration_global")->lm_ucname($lab);
- $university_name = \Drupal::service("lab_migration_global")->lm_ucname($university);
- $dir_name = $lab_title . " " . "by". " " . $proposar_name . ' ' . $university_name;
- $directory_name = str_replace("__", "_", str_replace(" ", "_", $dir_name));
- return $directory_name;
}
-public function lm_ucname($string)
- {
+
+ /**
+ * Builds a filesystem-safe directory name from lab/proposer/university.
+ */
+ public function _lm_dir_name($lab, $name, $university) {
+ $lab_title = $this->lm_ucname($lab);
+ $proposer_name = $this->lm_ucname($name);
+ $university_name = $this->lm_ucname($university);
+ $dir_name = $lab_title . ' by ' . $proposer_name . ' ' . $university_name;
+ return str_replace('__', '_', str_replace(' ', '_', $dir_name));
+ }
+
+ /**
+ * Capitalises a name string, handling hyphens and apostrophes.
+ */
+ public function lm_ucname($string) {
$string = ucwords(strtolower($string));
- foreach (array(
- '-',
- '\''
- ) as $delimiter)
- {
- if (strpos($string, $delimiter) !== false)
- {
- $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
- }
+ foreach (['-', "'"] as $delimiter) {
+ if (strpos($string, $delimiter) !== FALSE) {
+ $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
}
+ }
return $string;
- // Example of using lm_ucname in another method of this service.
-
- $name = $this->lm_ucname('example-string');
- // Other logic here...
- return $name;
-
}
- public function lab_migration_path()
- {
+
+ /**
+ * Returns the absolute filesystem path for lab migration uploads.
+ */
+ public function lab_migration_path() {
return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'DWSIM_uploads/lab_migration_uploads/';
}
- public function _bulk_list_of_labs()
- {
- $lab_titles = array(
- '0' => 'Please select...'
- );
- //$lab_titles_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE solution_display = 1 ORDER BY lab_title ASC");
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('solution_display', 1);
- $query->orderBy('lab_title', 'ASC');
- $lab_titles_q = $query->execute();
- while ($lab_titles_data = $lab_titles_q->fetchObject())
- {
- $lab_titles[$lab_titles_data->id] = $lab_titles_data->lab_title . ' (Proposed by ' . $lab_titles_data->name . ')';
- }
+
+ /**
+ * Returns labs with solution_display=1 for bulk management selects.
+ */
+ public function _bulk_list_of_labs() {
+ $lab_titles = ['0' => 'Please select...'];
+ $result = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('solution_display', 1)
+ ->orderBy('lab_title', 'ASC')
+ ->execute();
+ foreach ($result as $row) {
+ $lab_titles[$row->id] = $row->lab_title . ' (Proposed by ' . $row->name . ')';
+ }
return $lab_titles;
}
-
- public function _latex_copy_script_file()
- {
- // exec("cp ./" . drupal_get_path('module', 'lab_migration') . "/latex/* " . \Drupal::service("lab_migration_global")->lab_migration_path() . "latex");
- // exec("chmod u+x ./uploads/latex/*.sh");
- // Get the module path using the updated method for Drupal 10
-$module_path = \Drupal::service('module_handler')->getModule('lab_migration')->getPath();
-
-// Get the migration path from the lab_migration_global service
-$lab_migration_path = \Drupal::service('lab_migration_global')->lab_migration_path();
-
-// Execute the command to copy files
-exec("cp {$module_path}/latex/* {$lab_migration_path}latex");
-
-// Execute the command to change permissions
-exec("chmod u+x ./uploads/latex/*.sh");
+
+ /**
+ * Returns available bulk lab actions for the bulk management form.
+ */
+ public function _bulk_list_lab_actions() {
+ return [
+ 0 => 'Please select...',
+ 1 => 'Approve Entire Lab',
+ 2 => 'Pending Review Entire Lab',
+ 3 => 'Dis-Approve Entire Lab (This will delete all the solutions in the lab)',
+ 4 => 'Delete Entire Lab Including Proposal',
+ ];
}
-
- public function lab_migration_solution_proposal_pending()
- {
- /* get list of solution proposal where the solution_provider_uid is set to some userid except 0 and solution_status is also 1 */
- $pending_rows = array();
- //$pending_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE solution_provider_uid != 0 AND solution_status = 1 ORDER BY id DESC");
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('solution_provider_uid', 0, '!=');
- $query->condition('solution_status', 1);
- $query->orderBy('id', 'DESC');
- $pending_q = $query->execute();
- while ($pending_data = $pending_q->fetchObject())
- {
- $pending_rows[$pending_data->id] = array(
- l($pending_data->name, 'user/' . $pending_data->uid),
- $pending_data->lab_title,
- l('Approve', 'lab-migration/manage-proposal/solution-proposal-approve/' . $pending_data->id)
- );
- }
- /* check if there are any pending proposals */
- if (!$pending_rows)
- {
- \Drupal::messenger()->addMessage(t('There are no pending solution proposals.'), 'status');
- return '';
- }
- $pending_header = array(
- 'Proposer Name',
- 'Title of the Lab',
- 'Action'
- );
- $output = theme('table', array(
- 'header' => $pending_header,
- 'rows' => $pending_rows
- ));
- return $output;
+
+ /**
+ * Returns available bulk experiment actions.
+ */
+ public function _bulk_list_experiment_actions() {
+ return [
+ 0 => 'Please select...',
+ 1 => 'Approve Entire Experiment',
+ 2 => 'Pending Review Entire Experiment',
+ 3 => 'Dis-Approve Entire Experiment (This will delete all the solutions in the experiment)',
+ ];
}
- public function lab_migration_list_experiments() {
- // $user = \Drupal::currentUser();
-$user = $user->get('uid')->value;
- $proposal_data = \Drupal::service("lab_migration_global")->lab_migration_get_proposal();
- if (!$proposal_data) {
- RedirectResponse('');
- return;
+ /**
+ * Returns available bulk solution actions.
+ */
+ public function _bulk_list_solution_actions() {
+ return [
+ 0 => 'Please select...',
+ 1 => 'Approve Entire Solution',
+ 2 => 'Pending Review Entire Solution',
+ 3 => 'Dis-approve Solution (This will delete the solution)',
+ ];
+ }
+
+ /**
+ * Copies LaTeX script files to the uploads directory.
+ */
+ public function _latex_copy_script_file() {
+ $module_path = $this->moduleHandler->getModule('lab_migration')->getPath();
+ $lab_migration_path = $this->lab_migration_path();
+ exec("cp {$module_path}/latex/* {$lab_migration_path}latex");
+ exec("chmod u+x {$lab_migration_path}latex/*.sh");
+ }
+
+ /**
+ * Returns a render array of pending solution proposals.
+ *
+ * Returns an empty array and sets a status message when none exist.
+ */
+ public function lab_migration_solution_proposal_pending() {
+ $rows = [];
+ $result = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('solution_provider_uid', 0, '!=')
+ ->condition('solution_status', 1)
+ ->orderBy('id', 'DESC')
+ ->execute();
+
+ foreach ($result as $data) {
+ $user_link = Link::fromTextAndUrl(
+ $data->name,
+ Url::fromRoute('entity.user.canonical', ['user' => $data->uid])
+ )->toString();
+
+ $approve_link = Link::fromTextAndUrl(
+ 'Approve',
+ Url::fromRoute('lab_migration.solution_proposal_approval_form')
+ )->toString();
+
+ $rows[] = [$user_link, $data->lab_title, $approve_link];
}
- $return_html = 'Title of the Lab: ' . $proposal_data->lab_title . ' ';
- $return_html .= 'Proposer Name: ' . $proposal_data->name_title . ' ' . $proposal_data->name . ' ';
- // $return_html .= Link::fromTextAndUrl('Upload Solution', 'lab-migration/code/upload') . ' ';
- $return_html .= Link::fromTextAndUrl(
- 'Upload Solution',
- Url::fromUri('internal:/lab-migration/code/upload')
- )->toString() . ' ';
- /* get experiment list */
- $experiment_rows = [];
- //$experiment_q = \Drupal::database()->query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY number ASC", $proposal_data->id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_data->id);
- $query->orderBy('number', 'ASC');
- $experiment_q = $query->execute();
-
-
-
- while ($experiment_data = $experiment_q->fetchObject()) {
-
-
- $experiment_rows[] = [
- $experiment_data->number . ') ' . $experiment_data->title,
- '',
- '',
- '',
- ];
- /* get solution list */
- //$solution_q = \Drupal::database()->query("SELECT * FROM {lab_migration_solution} WHERE experiment_id = %d ORDER BY id ASC", $experiment_data->id);
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $experiment_data->id);
- $query->orderBy('id', 'ASC');
- $solution_q = $query->execute();
- if ($solution_q) {
- while ($solution_data = $solution_q->fetchObject()) {
- $solution_status = '';
- switch ($solution_data->approval_status) {
- case 0:
- $solution_status = "Pending";
- break;
- case 1:
- $solution_status = "Approved";
- break;
- default:
- $solution_status = "Unknown";
- break;
- }
- if ($solution_data->approval_status == 0) {
- $experiment_rows[] = [
- " " . $solution_data->code_number . " " . $solution_data->caption,
- '',
- $solution_status,
- Link::fromTextAndUrl('Delete', 'lab-migration/code/delete/' . $solution_data->id),
- ];
- }
- else {
- $experiment_rows[] = [
- " " . $solution_data->code_number . " " . $solution_data->caption,
- '',
- $solution_status,
- '',
- ];
- }
- /* get solution files */
- //$solution_files_q = \Drupal::database()->query("SELECT * FROM {lab_migration_solution_files} WHERE solution_id = %d ORDER BY id ASC", $solution_data->id);
- $query = \Drupal::database()->select('lab_migration_solution_files');
- $query->fields('lab_migration_solution_files');
- $query->condition('solution_id', $solution_data->id);
- $query->orderBy('id', 'ASC');
- $solution_files_q = $query->execute();
-
- if ($solution_files_q) {
- while ($solution_files_data = $solution_files_q->fetchObject()) {
- $code_file_type = '';
- switch ($solution_files_data->filetype) {
- case 'S':
- $code_file_type = 'Source';
- break;
- case 'R':
- $code_file_type = 'Result';
- break;
- case 'X':
- $code_file_type = 'Xcox';
- break;
- case 'U':
- $code_file_type = 'Unknown';
- break;
- default:
- $code_file_type = 'Unknown';
- break;
- }
- $experiment_rows[] = [
- " " . Link::fromTextAndUrl($solution_files_data->filename, 'lab-migration/download/file/' . $solution_files_data->id),
- $code_file_type,
- '',
- '',
- ];
- }
- }
- /* get dependencies files */
- //$dependency_q = \Drupal::database()->query("SELECT * FROM {lab_migration_solution_dependency} WHERE solution_id = %d ORDER BY id ASC", $solution_data->id);
- $query = \Drupal::database()->select('lab_migration_solution_dependency');
- $query->fields('lab_migration_solution_dependency');
- $query->condition('solution_id', $solution_data->id);
- $query->orderBy('id', 'ASC');
- $dependency_q = $query->execute();
- while ($dependency_data = $dependency_q->fetchObject()) {
- //$dependency_files_q = \Drupal::database()->query("SELECT * FROM {lab_migration_dependency_files} WHERE id = %d", $dependency_data->dependency_id);
- $query = \Drupal::database()->select('lab_migration_dependency_files');
- $query->fields('lab_migration_dependency_files');
- $query->condition('id', $dependency_data->dependency_id);
- $dependency_files_q = $query->execute();
- $dependency_files_data = $dependency_files_q->fetchObject();
- $experiment_rows[] = [
- " " . Link::fromTextAndUrl($dependency_files_data->filename, 'lab-migration/download/dependency/' . $dependency_files_data->id),
- 'Dependency',
- '',
- '',
- ];
- }
- }
- }
+ if (empty($rows)) {
+ $this->messenger->addStatus(t('There are no pending solution proposals.'));
+ return [];
}
- $experiment_header = [
- 'No. Title of the Experiment',
- 'Type',
- 'Status',
- 'Actions',
- ];
- // $return_html .= drupal_render()_table($experiment_header, $experiment_rows);
-
- // $return_html .= \Drupal::service("renderer")->render('table', [
- // 'header' => $experiment_header,
- // 'rows' => $experiment_rows,
- // ]);
- $return_html = 'Title of the Lab: ';
-$return_html .= 'Proposer Name: ';
-$return_html .= 'Upload Solution ';
-// Add your table or any other HTML content here
-
-return new Response($return_html);
- $table = [
- '#type' => 'table',
- '#header' => $experiment_header, // The headers for the table
- '#rows' => $experiment_rows, // The rows for the table
-
+ return [
+ '#type' => 'table',
+ '#header' => ['Proposer Name', 'Title of the Lab', 'Action'],
+ '#rows' => $rows,
];
-
-
- $return_html .= \Drupal::service('renderer')->render($table);
- return $return_html;
}
- public function verify_lab_migration_certificates($qr_code = 0) {
-
- $route_match = \Drupal::routeMatch();
+ /**
+ * Loads the approved solution proposal for the current user.
+ *
+ * Returns proposal object on success, FALSE otherwise.
+ */
+ public function lab_migration_get_proposal() {
+ $uid = $this->currentUser->id();
+
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('solution_provider_uid', $uid)
+ ->condition('solution_status', 2)
+ ->orderBy('id', 'DESC')
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
-$qr_code = (int) $route_match->getParameter('qr_code');
- $page_content = "";
- if ($qr_code) {
- $page_content = verify_qrcode_lm_fromdb($qr_code);
- } //$qr_code
- else {
- $verify_certificates_form = \Drupal::formBuilder()->getForm("verify_lab_migration_certificates_form");
- $page_content = \Drupal::service("renderer")->render($verify_certificates_form);
+ if (!$proposal_data) {
+ return FALSE;
}
- return $page_content;
- }
- public function _bulk_list_lab_actions()
- {
- $lab_actions = array(
- 0 => 'Please select...'
- );
- $lab_actions[1] = 'Approve Entire Lab';
- $lab_actions[2] = 'Pending Review Entire Lab';
- $lab_actions[3] = 'Dis-Approve Entire Lab (This will delete all the solutions in the lab)';
- $lab_actions[4] = 'Delete Entire Lab Including Proposal';
- return $lab_actions;
- }
- public function _bulk_list_experiment_actions()
- {
- $lab_experiment_actions = array(
- 0 => 'Please select...'
- );
- $lab_experiment_actions[1] = 'Approve Entire Experiment';
- $lab_experiment_actions[2] = 'Pending Review Entire Experiment';
- $lab_experiment_actions[3] = 'Dis-Approve Entire Experiment (This will delete all the solutions in the experiment)';
- return $lab_experiment_actions;
- }
- public function _bulk_list_solution_actions()
- {
- $lab_solution_actions = array(
- 0 => 'Please select...'
- );
- $lab_solution_actions[1] = 'Approve Entire Solution';
- $lab_solution_actions[2] = 'Pending Review Entire Solution';
- $lab_solution_actions[3] = 'Dis-approve Solution (This will delete the solution)';
- return $lab_solution_actions;
- }
- public function lab_migration_delete_lab_pdf() {
-
- $route_match = \Drupal::routeMatch();
-
-$lab_id = (int) $route_match->getParameter('lab_id');
-\Drupal::service("lab_migration_global")->lab_migration_del_lab_pdf($lab_id);
- \Drupal::messenger()->addMessage(t('Lab schedule for regeneration.'), 'status');
- RedirectResponse('lab_migration/code_approval/bulk');
- return;
- }
- public function lab_migration_delete_lab($lab_id)
-{
- $status = TRUE;
- $root_path = \Drupal::service("lab_migration_global")->lab_migration_path();
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $lab_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- if (!$proposal_data)
- {
- \Drupal::messenger()->addError('Invalid Lab.');
- return FALSE;
- }
- /* delete experiments */
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_data->id);
- $experiment_q = $query->execute();
- while ($experiment_data = $experiment_q->fetchObject())
- {
- if (!\Drupal::service("lab_migration_global")->lab_migration_delete_experiment($experiment_data->id))
- {
- $status = FALSE;
+ switch ($proposal_data->approval_status) {
+ case 0:
+ $this->messenger->addStatus(t('Proposal is awaiting approval.'));
+ return FALSE;
+
+ case 1:
+ return $proposal_data;
+
+ case 2:
+ $this->messenger->addError(t('Proposal has been dis-approved.'));
+ return FALSE;
+
+ case 3:
+ $this->messenger->addStatus(t('Proposal has been marked as completed.'));
+ return FALSE;
+
+ default:
+ $this->messenger->addError(t('Invalid proposal state. Please contact site administrator.'));
+ return FALSE;
}
}
- return $status;
-}
-public function lab_migration_delete_experiment($experiment_id)
-{
+ /**
+ * Deletes all experiments and solutions belonging to a lab proposal.
+ *
+ * @param int $lab_id
+ * The proposal ID.
+ *
+ * @return bool
+ * TRUE if all deletions succeeded, FALSE otherwise.
+ */
+ public function lab_migration_delete_lab($lab_id) {
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $lab_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError(t('Invalid Lab.'));
+ return FALSE;
+ }
+
$status = TRUE;
- $root_path = \Drupal::service("lab_migration_global")->lab_migration_path();
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $experiment_id);
- $experiment_q = $query->execute();
- $experiment_data = $experiment_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $experiment_data->proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- if (!$experiment_data)
- {
- \Drupal::messenger()->addError('Invalid experiment.');
- return FALSE;
+ $experiments = $this->database->select('lab_migration_experiment', 'e')
+ ->fields('e')
+ ->condition('proposal_id', $proposal_data->id)
+ ->execute();
+
+ foreach ($experiments as $experiment) {
+ if (!$this->lab_migration_delete_experiment($experiment->id)) {
+ $status = FALSE;
+ }
}
- /* deleting solutions */
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $experiment_id);
- $solution_q = $query->execute();
+
+ return $status;
+ }
+
+ /**
+ * Deletes all solutions for an experiment and removes its directory.
+ *
+ * @param int $experiment_id
+ *
+ * @return bool
+ */
+ public function lab_migration_delete_experiment($experiment_id) {
+ $experiment_data = $this->database->select('lab_migration_experiment', 'e')
+ ->fields('e')
+ ->condition('id', $experiment_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$experiment_data) {
+ $this->messenger->addError(t('Invalid experiment.'));
+ return FALSE;
+ }
+
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $experiment_data->proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ $status = TRUE;
$delete_exp_folder = FALSE;
- while ($solution_data = $solution_q->fetchObject())
- {
- $delete_exp_folder = TRUE;
- if (!\Drupal::service("lab_migration_global")->lab_migration_delete_solution($solution_data->id))
- $status = FALSE;
+
+ $solutions = $this->database->select('lab_migration_solution', 's')
+ ->fields('s')
+ ->condition('experiment_id', $experiment_id)
+ ->execute();
+
+ foreach ($solutions as $solution) {
+ $delete_exp_folder = TRUE;
+ if (!$this->lab_migration_delete_solution($solution->id)) {
+ $status = FALSE;
+ }
}
- if (!$delete_exp_folder)
- {
- return TRUE;
+
+ if (!$delete_exp_folder) {
+ return TRUE;
}
- if ($status)
- {
- $dir_path = $root_path . $proposal_data->directory_name . '/EXP' . $experiment_data->number;
- if (is_dir($dir_path))
- {
- $res = rmdir($dir_path);
- if (!$res)
- {
- \Drupal::messenger()->addError(t('Error deleting experiment folder !folder', array('!folder' => $dir_path)));
- /* sending email to admins */
- // $email_to = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
- // $from = \Drupal::config('lab_migration.settings')->get('lab_migration_from_email');
- // $bcc="";
- // $cc=\Drupal::config('lab_migration.settings')->get('lab_migration_cc_emails');
- // $param['standard']['subject'] = "[ERROR] Error deleting experiment folder";
- // $param['standard']['body'] = "Error deleting folder " . $dir_path;
- // $param['standard']['headers']=array('From'=>$from,'MIME-Version'=> '1.0',
- // 'Content-Type'=> 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- // 'Content-Transfer-Encoding' => '8Bit',
- // 'X-Mailer'=> 'Drupal','Cc' => $cc, 'Bcc' => $bcc);
- // if (!drupal_mail('lab_migration', 'standard', $email_to, language_default(), $param,$from, TRUE))
- // \Drupal::messenger()->addError('Error sending email message.');
- // return FALSE;
- }
- else
- {
- return TRUE;
- }
- }
- else {
- \Drupal::messenger()->addError(t('Cannot delete experiment folder. !folder does not exists.', array('!folder' => $dir_path)));
+
+ if ($status && $proposal_data) {
+ $root_path = $this->lab_migration_path();
+ $dir_path = $root_path . $proposal_data->directory_name . '/EXP' . $experiment_data->number;
+ if (is_dir($dir_path)) {
+ if (!rmdir($dir_path)) {
+ $this->messenger->addError(t('Error deleting experiment folder @folder', ['@folder' => $dir_path]));
return FALSE;
}
+ return TRUE;
+ }
+ else {
+ $this->messenger->addError(t('Cannot delete experiment folder. @folder does not exist.', ['@folder' => $dir_path]));
+ return FALSE;
+ }
}
- return FALSE;
-}
-
- public function lab_migration_get_proposal()
- {
- global $user;
- $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
- //var_dump($user->id() );die;
- //$proposal_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE solution_provider_uid = ".$user->uid." AND solution_status = 2 ORDER BY id DESC LIMIT 1");
- $query = Database::getConnection()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('solution_provider_uid', $user->id());
- $query->condition('solution_status', 2);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- //var_dump($proposal_data);die;
-// if (!$proposal_data)
-// {
-
-// // Create the link URL object for the "available" link.
-// $link_url = Url::fromRoute('lab_migration.proposal_open');
-// $link = Link::fromTextAndUrl('available', $link_url)->toString();
-
-
-// // Now you can use $link in your output or messages
-// \Drupal::messenger()->addMessage("Check out the proposal: " . $link);
-// }
-
- switch ($proposal_data->approval_status)
- {
- case 0:
- \Drupal::messenger()->addMessage(t('Proposal is awaiting approval.'), 'status');
- return FALSE;
- case 1:
- return $proposal_data;
- case 2:
- \Drupal::messenger()->addMessage(t('Proposal has been dis-approved.'), 'error');
- return FALSE;
- case 3:
- \Drupal::messenger()->addMessage(t('Proposal has been marked as completed.'), 'status');
- return FALSE;
- default:
- \Drupal::messenger()->addMessage(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- return FALSE;
- }
- // return $proposal_data;
- }
- public function lab_migration_upload_code_form($form,$form_state)
-{
-
- global $user;
-
- $proposal_data = lab_migration_get_proposal();
- if (!$proposal_data) {
- drupal_goto('');
- return;
- }
- /* add javascript for dependency selection effects */
- $dep_selection_js = "(public function ($) {
- //alert('ok');
- $('#edit-existing-depfile-dep-lab-title').change(public function() {
- var dep_selected = '';
-
- /* showing and hiding relevant files */
- $('.form-checkboxes .option').hide();
- $('.form-checkboxes .option').each(public function(index) {
- var activeClass = $('#edit-existing-depfile-dep-lab-title').val();
- consloe.log(activeClass);
- if ($(this).children().hasClass(activeClass)) {
- $(this).show();
- }
- if ($(this).children().attr('checked') == true) {
- dep_selected += $(this).children().next().text() + ' ';
- }
- });
- /* showing list of already existing dependencies */
- $('#existing_depfile_selected').html(dep_selected);
- });
-
- $('.form-checkboxes .option').change(public function() {
- $('#edit-existing-depfile-dep-lab-title').trigger('change');
- });
- $('#edit-existing-depfile-dep-lab-title').trigger('change');
- }(jQuery));";
- drupal_add_js($dep_selection_js, 'inline', 'header');
-
- $form['#attributes'] = array('enctype' => "multipart/form-data");
-
- $form['lab_title'] = array(
- '#type' => 'item',
- '#markup' => $proposal_data->lab_title,
- '#title' => t('Title of the Lab'),
- );
- $form['name'] = array(
- '#type' => 'item',
- '#markup' => $proposal_data->name_title . ' ' . $proposal_data->name,
- '#title' => t('Proposer Name'),
- );
-
- /* get experiment list */
- $experiment_rows = array();
- //$experiment_q = db_query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY id ASC", $proposal_data->id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_data->id);
- $query->orderBy('id', 'ASC');
- $experiment_q = $query->execute();
- while ($experiment_data = $experiment_q->fetchObject())
- {
- $experiment_rows[$experiment_data->id] = $experiment_data->number . '. ' . $experiment_data->title;
+ return FALSE;
}
- $form['experiment'] = array(
- '#type' => 'select',
- '#title' => t('Title of the Experiment'),
- '#options' => $experiment_rows,
- '#multiple' => FALSE,
- '#size' => 1,
- '#required' => TRUE,
- );
-
- $form['code_number'] = array(
- '#type' => 'textfield',
- '#title' => t('Code No'),
- '#size' => 5,
- '#maxlength' => 10,
- '#description' => t(""),
- '#required' => TRUE,
- );
- $form['code_caption'] = array(
- '#type' => 'textfield',
- '#title' => t('Caption'),
- '#size' => 40,
- '#maxlength' => 255,
- '#description' => t(''),
- '#required' => TRUE,
- );
- $form['os_used'] = array(
- '#type' => 'select',
- '#title' => t('Operating System used'),
- '#options' => array(
- 'Linux' => 'Linux',
- 'Windows' => 'Windows',
- 'Mac' => 'Mac'
- ),
- '#required' => TRUE,
- );
- $form['version'] = array(
- '#type' => 'select',
- '#title' => t('DWSIM version used'),
- '#options' => _lm_list_of_software_version(),
- '#required' => TRUE,
- );
- $form['toolbox_used'] = array(
- '#type' => 'hidden',
- '#title' => t('Toolbox used (If any)'),
-'#default_value'=>'none',
- );
- $form['code_warning'] = array(
- '#type' => 'item',
- '#title' => t('Upload all the r project files in .zip format'),
- '#prefix' => '',
- '#suffix' => '
',
- );
- $form['sourcefile'] = array(
- '#type' => 'fieldset',
- '#title' => t('Main or Source Files'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE,
- );
- $form['sourcefile']['sourcefile1'] = array(
- '#type' => 'file',
- '#title' => t('Upload main or source file'),
- '#size' => 48,
- '#description' => t('Only alphabets and numbers are allowed as a valid filename.') . ' ' .
- t('Allowed file extensions: ') . variable_get('lab_migration_source_extensions', ''),
- );
-
- /* $form['dep_files'] = array(
- '#type' => 'item',
- '#title' => t('Dependency Files'),
- );*/
- }
-
- public function lab_migration_delete_solution($solution_id)
-{
- global $user;
- $root_path = \Drupal::service("lab_migration_global")->lab_migration_path();
+
+ /**
+ * Deletes a solution's files from disk and removes DB records.
+ *
+ * Sends an admin error email via MailService if file deletion fails.
+ *
+ * @param int $solution_id
+ *
+ * @return bool
+ */
+ public function lab_migration_delete_solution($solution_id) {
+ $root_path = $this->lab_migration_path();
$status = TRUE;
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $solution_id);
- $solution_q = $query->execute();
- $solution_data = $solution_q->fetchObject();
- if (!$solution_data)
- {
- \Drupal::messenger()->addMessage(t('Invalid solution.'), 'error');
- return FALSE;
- }
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_data->experiment_id);
- $experiment_q = $query->execute();
- $experiment_data = $experiment_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $experiment_data->proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- if (!$experiment_data)
- {
- \Drupal::messenegr()->addMessage(t('Invalid experiment.'), 'error');
- return FALSE;
- }
- /* deleting solution files */
- $query = \Drupal::database()->select('lab_migration_solution_files');
- $query->fields('lab_migration_solution_files');
- $query->condition('solution_id', $solution_id);
- $solution_files_q = $query->execute();
- while ($solution_files_data = $solution_files_q->fetchObject())
- {
- $ex_path = $proposal_data->directory_name . '/' . $solution_files_data->filepath;
- $dir_path = $root_path . $ex_path;
- if (!file_exists($dir_path))
- {
- $status = FALSE;
- \Drupal::messenger()->addMessage(t('Error deleting !file. File does not exists.', array('!file' => $dir_path)), 'error');
- continue;
- }
- /* removing solution file */
- if (!unlink($dir_path))
- {
- $status = FALSE;
- \Drupal::messenger()->addMessage(t('Error deleting !file', array('!file' => $dir_path)), 'error');
-
- /* sending email to admins */
- $email_to = variable_get('lab_migration_emails', '');
- $from = variable_get('lab_migration_from_email', '');
- $bcc="";
- $cc=variable_get('lab_migration_cc_emails', '');
- $param['standard']['subject'] = "[ERROR] Error deleting example file";
- $param['standard']['body'] = "Error deleting solution files by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " :
- solution id : " . $solution_id . "
- file id : " . $solution_files_data->id . "
- file path : " . $solution_files_data->filepath."
- PDF path : " . $PdfStatus;
- $param['standard']['headers']=array('From'=>$from,'MIME-Version'=> '1.0',
- 'Content-Type'=> 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer'=> 'Drupal','Cc' => $cc, 'Bcc' => $bcc);
-
- if (!drupal_mail('lab_migration', 'standard', $email_to, language_default(), $param, $from, TRUE))
- \Drupal::messenger()->addMessage('Error sending email message.', 'error');
- }
- else {
- /* deleting example files database entries */
- \Drupal::database()->delete('lab_migration_solution_files')->condition('id', $solution_files_data->id)->execute();
- }
+
+ $solution_data = $this->database->select('lab_migration_solution', 's')
+ ->fields('s')
+ ->condition('id', $solution_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$solution_data) {
+ $this->messenger->addError(t('Invalid solution.'));
+ return FALSE;
}
- if (!$status)
- return FALSE;
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $solution_id);
- $solution_q = $query->execute();
- $solution_data = $solution_q->fetchObject();
- if (!$solution_data)
- {
- \Drupal::messenger()->addMessage(t('Invalid solution.'), 'error');
- return FALSE;
- }
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_data->experiment_id);
- $experiment_q = $query->execute();
- $experiment_data = $experiment_q->fetchObject();
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $experiment_data->proposal_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- $dir_path = $root_path . $proposal_data->directory_name . '/EXP' . $experiment_data->number . '/CODE' . $solution_data->code_number;
- if (is_dir($dir_path))
- {
- // if (!rmdir($dir_path))
- // {
- // \Drupal::messenger()->addMessage(t('Error deleting folder !folder', array('!folder' => $dir_path)), 'error');
-
- /* sending email to admins */
- // $email_to = variable_get('lab_migration_emails', '');
- // $from = variable_get('lab_migration_from_email', '');
- // $bcc="";
- // $cc=variable_get('lab_migration_cc_emails', '');
-
-
- // $param['standard']['subject'] = "[ERROR] Error deleting folder";
- // $param['standard']['body'] = "Error deleting folder " . $dir_path . " by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
- // $param['standard']['headers']=array('From'=>$from,'MIME-Version'=> '1.0',
- // 'Content-Type'=> 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- // 'Content-Transfer-Encoding' => '8Bit',
- // 'X-Mailer'=> 'Drupal','Cc' => $cc, 'Bcc' => $bcc);
-
- // if (!drupal_mail('lab_migration', 'standard', $email_to, language_default(), $param, $from, TRUE))
- // \Drupal::messenger()->addMessage('Error sending email message.', 'error');
- // return FALSE;
- // }
- }
- else
- {
- \Drupal::messenger()->addMessage(t('Cannot delete solution folder. !folder does not exists.', array('!folder' => $dir_path)), 'error');
- return FALSE;
+ $experiment_data = $this->database->select('lab_migration_experiment', 'e')
+ ->fields('e')
+ ->condition('id', $solution_data->experiment_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$experiment_data) {
+ $this->messenger->addError(t('Invalid experiment.'));
+ return FALSE;
}
- /* deleting solution dependency and solution database entries */
- \Drupal::database()->delete('lab_migration_solution_dependency')->condition('solution_id', $solution_id)->execute();
- \Drupal::database()->delete('lab_migration_solution')->condition('id', $solution_id)->execute();
- return $status;
-}
-public function LM_RenameDir($proposal_id, $dir_name)
- {
- $query = \Drupal::database()->query("SELECT directory_name FROM lab_migration_proposal WHERE id = :proposal_id", array(
- ':proposal_id' => $proposal_id
- ));
- $result = $query->fetchObject();
- $new_directory_name = rename(\Drupal::service("lab_migration_global")->lab_migration_path() . $result->directory_name, \Drupal::service("lab_migration_global")->lab_migration_path() . $dir_name) or \Drupal::messenger()->addMessage("Unable to rename folder");
-
- return $new_directory_name;
-
- }
-public function lab_migration_with_morefeature($key, &$message, $params)
- {
- if (isset($params['subject']))
- {
- $message['subject'] = $params['subject'];
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $experiment_data->proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ // Delete associated solution files from disk and DB.
+ $solution_files = $this->database->select('lab_migration_solution_files', 'sf')
+ ->fields('sf')
+ ->condition('solution_id', $solution_id)
+ ->execute();
+
+ foreach ($solution_files as $file) {
+ $dir_path = $root_path . $proposal_data->directory_name . '/' . $file->filepath;
+ if (!file_exists($dir_path)) {
+ $status = FALSE;
+ $this->messenger->addError(t('Error deleting @file. File does not exist.', ['@file' => $dir_path]));
+ continue;
}
- if (isset($params['body']))
- {
- $message['body'][] = $params['body'];
+
+ if (!unlink($dir_path)) {
+ $status = FALSE;
+ $this->messenger->addError(t('Error deleting @file.', ['@file' => $dir_path]));
+
+ // Notify admins via MailService.
+ $email_to = \Drupal::config('lab_migration.settings')->get('lab_migration_emails');
+ if (!empty($email_to)) {
+ $subject = '[ERROR] Error deleting solution file';
+ $body = 'Error deleting solution file. Solution ID: ' . $solution_id . ', File: ' . $dir_path;
+ $this->mailService->sendNotification('lab_migration', 'standard', $email_to, $subject, $body);
+ }
}
- if (isset($params['headers']) && is_array($params['headers']))
- {
- $message['headers'] += $params['headers'];
+ else {
+ $this->database->delete('lab_migration_solution_files')
+ ->condition('id', $file->id)
+ ->execute();
}
- }
-
- public function lab_migration_upload_code_delete()
-{
- global $user;
-
- $root_path = lab_migration_path();
- // $solution_id = (int)arg(3);
- $route_match = \Drupal::routeMatch();
-
- $solution_id = (int) $route_match->getParameter('solution_id');
-
-
- /* check solution */
- // $solution_q = db_query("SELECT * FROM {lab_migration_solution} WHERE id = %d LIMIT 1", $solution_id);
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('id', $solution_id);
- $query->range(0, 1);
- $solution_q = $query->execute();
- $solution_data = $solution_q->fetchObject();
- if (!$solution_data)
- {
- \Drupal::messenger()->addMessage('Invalid solution.', 'error');
- // drupal_goto('lab-migration/code');
- return;
- }
- if ($solution_data->approval_status != 0)
- {
- \Drupal::messenger()->addMessage('You cannnot delete a solution after it has been approved. Please contact site administrator if you want to delete this solution.', 'error');
- // drupal_goto('lab-migration/code');
- return;
- }
+ }
- //$experiment_q = db_query("SELECT * FROM {lab_migration_experiment} WHERE id = %d LIMIT 1", $solution_data->experiment_id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('id', $solution_data->experiment_id);
- $query->range(0, 1);
- $experiment_q = $query->execute();
-
- $experiment_data = $experiment_q->fetchObject();
- if (!$experiment_data)
- {
- \Drupal::messenger()->addMessage('You do not have permission to delete this solution.', 'error');
- // drupal_goto('lab-migration/code');
- return;
- }
+ if (!$status) {
+ return FALSE;
+ }
+
+ // Remove the solution code directory if it exists.
+ $dir_path = $root_path . $proposal_data->directory_name
+ . '/EXP' . $experiment_data->number
+ . '/CODE' . $solution_data->code_number;
+
+ if (!is_dir($dir_path)) {
+ $this->messenger->addError(t('Cannot delete solution folder. @folder does not exist.', ['@folder' => $dir_path]));
+ return FALSE;
+ }
- //$proposal_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE id = %d AND solution_provider_uid = %d LIMIT 1", $experiment_data->proposal_id, $user->uid);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $experiment_data->proposal_id);
- $query->condition('solution_provider_uid', $user->uid);
- $query->range(0, 1);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- if (!$proposal_data)
- {
- \Drupal::messenger()->addMessage('You do not have permission to delete this solution.', 'error');
- // drupal_goto('lab-migration/code');
- return;
+ // Remove solution dependency and solution records from DB.
+ $this->database->delete('lab_migration_solution_dependency')
+ ->condition('solution_id', $solution_id)
+ ->execute();
+
+ $this->database->delete('lab_migration_solution')
+ ->condition('id', $solution_id)
+ ->execute();
+
+ return TRUE;
}
- /* deleting solution files */
- if (lab_migration_delete_solution($solution_data->id))
- {
- \Drupal::messenger()->addMessage('Solution deleted.', 'status');
-
- /* sending email */
- $email_to = $user->mail;
-
- $from = variable_get('lab_migration_from_email', '');
- $bcc= variable_get('lab_migration_emails', '');
- $cc=variable_get('lab_migration_cc_emails', '');
- $param['solution_deleted_user']['solution_id'] = $proposal_data->id;
- $param['solution_deleted_user']['lab_title'] = $proposal_data->lab_title;
- $param['solution_deleted_user']['experiment_title'] = $experiment_data->title;
- $param['solution_deleted_user']['solution_number'] = $solution_data->code_number;
- $param['solution_deleted_user']['solution_caption'] = $solution_data->caption;
- $param['solution_deleted_user']['user_id'] = $user->uid;
- $param['solution_deleted_user']['headers']=array('From'=>$from,'MIME-Version'=> '1.0',
- 'Content-Type'=> 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer'=> 'Drupal','Cc' => $cc, 'Bcc' => $bcc);
-
- if (!drupal_mail('lab_migration', 'solution_deleted_user', $email_to, language_default(), $param , $from , TRUE))
- \Drupal::messenger()->addMessage('Error sending email message.', 'error');
- } else {
- \Drupal::messenger()->addMessage('Error deleting example.', 'status');
+ /**
+ * Renames a lab directory on disk when the proposal directory name changes.
+ *
+ * @param int $proposal_id
+ * @param string $dir_name
+ * The new directory name.
+ *
+ * @return bool
+ */
+ public function LM_RenameDir($proposal_id, $dir_name) {
+ $result = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p', ['directory_name'])
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$result) {
+ $this->messenger->addError(t('Proposal not found for directory rename.'));
+ return FALSE;
+ }
+
+ $old_path = $this->lab_migration_path() . $result->directory_name;
+ $new_path = $this->lab_migration_path() . $dir_name;
+
+ if (!rename($old_path, $new_path)) {
+ $this->messenger->addError(t('Unable to rename folder.'));
+ return FALSE;
+ }
+
+ return TRUE;
}
- // drupal_goto('lab-migration/code');
- return;
-}
-
-public function CreateReadmeFileLabMigration($proposal_id)
- {
- $result =\Drupal::database()->select("
- SELECT * from lab_migration_proposal WHERE id = :proposal_id", array(
- ":proposal_id" => $proposal_id
- ));
- $proposal_data = $result->fetchObject();
- $root_path = \Drupal::service("lab_migration_global")->lab_migration_path();
- $readme_file = fopen($root_path . $proposal_data->directory_name . "/README.txt", "w") or die("Unable to open file!");
- $txt = "";
- $txt .= "About the lab";
- $txt .= "\n" . "\n";
- $txt .= "Title Of The Lab: " . $proposal_data->lab_title . "\n";
- $txt .= "Proposar Name: " . $proposal_data->name_title . " " . $proposal_data->name . "\n";
- $txt .= "Department: " . $proposal_data->department . "\n";
- $txt .= "University: " . $proposal_data->university . "\n";
- $txt .= "Category: " . $proposal_data->department . "\n\n";
- $txt .= "\n" . "\n";
- $txt .= "Solution provider";
- $txt .= "\n" . "\n";
- $txt .= "Solution Provider Name: " . $proposal_data->solution_provider_name_title . " " . $proposal_data->solution_provider_name . "\n";
- $txt .= "Solution Provider University: " . $proposal_data->solution_provider_university . "\n";
- $txt .= "\n" . "\n";
- $txt .= "Lab Migration Project By FOSSEE, IIT Bombay" . "\n";
+ /**
+ * Creates a README.txt file inside a lab's upload directory.
+ *
+ * @param int $proposal_id
+ *
+ * @return string
+ * The README file contents.
+ */
+ public function CreateReadmeFileLabMigration($proposal_id) {
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ return '';
+ }
+
+ $root_path = $this->lab_migration_path();
+ $readme_path = $root_path . $proposal_data->directory_name . '/README.txt';
+ $readme_file = fopen($readme_path, 'w');
+ if (!$readme_file) {
+ $this->messenger->addError(t('Unable to open README file for writing.'));
+ return '';
+ }
+
+ $txt = "About the lab\n\n";
+ $txt .= 'Title Of The Lab: ' . $proposal_data->lab_title . "\n";
+ $txt .= 'Proposer Name: ' . $proposal_data->name_title . ' ' . $proposal_data->name . "\n";
+ $txt .= 'Department: ' . $proposal_data->department . "\n";
+ $txt .= 'University: ' . $proposal_data->university . "\n";
+ $txt .= 'Category: ' . $proposal_data->department . "\n\n";
+ $txt .= "\nSolution provider\n\n";
+ $txt .= 'Solution Provider Name: ' . $proposal_data->solution_provider_name_title . ' ' . $proposal_data->solution_provider_name . "\n";
+ $txt .= 'Solution Provider University: ' . $proposal_data->solution_provider_university . "\n\n";
+ $txt .= "Lab Migration Project By FOSSEE, IIT Bombay\n";
+
fwrite($readme_file, $txt);
fclose($readme_file);
+
return $txt;
}
-
- public function _latex_generate_files($lab_id, $full_lab = FALSE)
- {
- $root_path = \Drupal::service("lab_migration_global")->lab_migration_path();
- $dir_path = $root_path . "latex/";
- $lab_filedata = "";
- $solution_provider_filedata = "";
- $latex_filedata = "";
- $latex_dep_filedata = "";
- $depedency_list = array();
+
+ /**
+ * Generates LaTeX data files for a lab's solutions.
+ *
+ * @param int $lab_id
+ * @param bool $full_lab
+ * If TRUE, includes all solutions; otherwise only approved ones.
+ */
+ public function _latex_generate_files($lab_id, $full_lab = FALSE) {
+ $root_path = $this->lab_migration_path();
+ $dir_path = $root_path . 'latex/';
+
+ $proposal_data = $this->database->select('lab_migration_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $lab_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError(t('Invalid lab specified.'));
+ return;
+ }
+
+ if ($proposal_data->approval_status == 0) {
+ $this->messenger->addError(t('Lab proposal is still in pending review.'));
+ return;
+ }
+
+ $category_map = [
+ 0 => 'Not Selected',
+ 1 => 'Fluid Mechanics',
+ 2 => 'Control Theory & Control Systems',
+ 3 => 'Chemical Engineering',
+ 4 => 'Thermodynamics',
+ 5 => 'Mechanical Engineering',
+ 6 => 'Signal Processing',
+ 7 => 'Digital Communications',
+ 8 => 'Electrical Technology',
+ 9 => 'Mathematics & Pure Science',
+ 10 => 'Analog Electronics',
+ 11 => 'Digital Electronics',
+ 12 => 'Computer Programming',
+ 13 => 'Others',
+ ];
+ $category_data = $category_map[$proposal_data->category] ?? 'Unknown';
+
+ $sep = '#';
$eol = "\n";
- $sep = "#";
- //$proposal_q = db_query("SELECT * FROM {lab_migration_proposal} WHERE id = %d", $lab_id);
- $query = \Drupal::database()->select('lab_migration_proposal');
- $query->fields('lab_migration_proposal');
- $query->condition('id', $lab_id);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- if (!$proposal_data)
- {
- \Drupal::messenger()->addMessage('Invalid lab specified.', 'error');
- // drupal_goto('');
- }
- if ($proposal_data->approval_status == 0)
- {
- \Drupal::messenger()->addMessage('Lab proposal is still in pending review.', 'error');
- // drupal_goto('');
- }
- $category_data = '';
- switch ($proposal_data->category)
- {
- case 0:
- $category_data = 'Not Selected';
- break;
- case 1:
- $category_data = 'Fluid Mechanics';
- break;
- case 2:
- $category_data = 'Control Theory & Control Systems';
- break;
- case 3:
- $category_data = 'Chemical Engineering';
- break;
- case 4:
- $category_data = 'Thermodynamics';
- break;
- case 5:
- $category_data = 'Mechanical Engineering';
- break;
- case 6:
- $category_data = 'Signal Processing';
- break;
- case 7:
- $category_data = 'Digital Communications';
- break;
- case 8:
- $category_data = 'Electrical Technology';
- break;
- case 9:
- $category_data = 'Mathematics & Pure Science';
- break;
- case 10:
- $category_data = 'Analog Electronics';
- break;
- case 11:
- $category_data = 'Digital Electronics';
- break;
- case 12:
- $category_data = 'Computer Programming';
- break;
- case 13:
- $category_data = 'Others';
- break;
- default:
- $category_data = 'Unknown';
- break;
+
+ $lab_filedata = implode($sep, [
+ $proposal_data->lab_title,
+ $proposal_data->name_title,
+ $proposal_data->name,
+ $proposal_data->department,
+ $proposal_data->university,
+ $category_data,
+ ]) . $eol;
+
+ // If PDF already exists, stream it directly.
+ $pdf_path = $dir_path . 'lab_' . $proposal_data->id . '.pdf';
+ if (file_exists($pdf_path)) {
+ header('Content-Type: application/pdf');
+ header('Content-Disposition: attachment; filename="' . $proposal_data->lab_title . '.pdf"');
+ header('Content-Length: ' . filesize($pdf_path));
+ readfile($pdf_path);
+ return;
}
- $lab_filedata = $proposal_data->lab_title . $sep . $proposal_data->name_title . $sep . $proposal_data->name . $sep . $proposal_data->department . $sep . $proposal_data->university . $sep . $category_data . $eol;
- /* regenerate lab if full lab selected */
- if ($full_lab)
- {
- lab_migration_del_lab_pdf($proposal_data->id);
- }
- /* check if lab already generated */
- if (file_exists($dir_path . "lab_" . $proposal_data->id . ".pdf"))
- {
- /* download zip file */
- header('Content-Type: application/pdf');
- header('Content-disposition: attachment; filename="' . $proposal_data->lab_title . '.pdf"');
- header('Content-Length: ' . filesize($dir_path . "lab_" . $proposal_data->id . ".pdf"));
- readfile($dir_path . "lab_" . $proposal_data->id . ".pdf");
- return;
- }
- $solution_provider_user = User::load($proposal_data->solution_provider_uid);
- if (!$solution_provider_user)
- {
- \Drupal::messenger()->addMessage('Could not fetch solution provider information for the lab specified.', 'error');
+
+ $solution_provider_filedata = implode($sep, [
+ $proposal_data->solution_provider_name_title,
+ $proposal_data->solution_provider_name,
+ $proposal_data->solution_provider_department,
+ $proposal_data->solution_provider_university,
+ ]) . $eol;
+
+ $latex_filedata = '';
+ $latex_dep_filedata = '';
+ $dependency_list = [];
+
+ $experiment_query = $this->database->select('lab_migration_experiment', 'e')
+ ->fields('e')
+ ->condition('proposal_id', $proposal_data->id)
+ ->orderBy('number', 'DESC');
+ $experiments = $experiment_query->execute();
+
+ foreach ($experiments as $experiment_data) {
+ $solution_query = $this->database->select('lab_migration_solution', 's')
+ ->fields('s')
+ ->condition('experiment_id', $experiment_data->id)
+ ->orderBy('code_number', 'DESC');
+
+ if (!$full_lab) {
+ $solution_query->condition('approval_status', 1);
}
- $solution_provider_filedata .= $proposal_data->solution_provider_name_title . $sep . $proposal_data->solution_provider_name . $sep . $proposal_data->solution_provider_department . $sep . $proposal_data->solution_provider_university . $eol;
- //$experiment_q = db_query("SELECT * FROM {lab_migration_experiment} WHERE proposal_id = %d ORDER BY number DESC", $proposal_data->id);
- $query = \Drupal::database()->select('lab_migration_experiment');
- $query->fields('lab_migration_experiment');
- $query->condition('proposal_id', $proposal_data->id);
- $query->orderBy('number', 'DESC');
- $experiment_q = $query->execute();
- while ($experiment_data = $experiment_q->fetchObject())
- {
- if ($full_lab)
- {
- //$solution_q = db_query("SELECT * FROM {lab_migration_solution} WHERE experiment_id = %d ORDER BY code_number DESC", $experiment_data->id);
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $experiment_data->id);
- $query->orderBy('code_number', 'DESC');
- $solution_q = $query->execute();
- }
- else
- {
- //$solution_q = db_query("SELECT * FROM {lab_migration_solution} WHERE experiment_id = %d AND approval_status = 1 ORDER BY code_number DESC", $experiment_data->id);
- $query = \Drupal::database()->select('lab_migration_solution');
- $query->fields('lab_migration_solution');
- $query->condition('experiment_id', $experiment_data->id);
- $query->condition('approval_status', 1);
- $query->orderBy('code_number', 'DESC');
- $solution_q = $query->execute();
- }
- while ($solution_data = $solution_q->fetchObject())
- {
- //$solution_files_q = db_query("SELECT * FROM {lab_migration_solution_files} WHERE solution_id = %d", $solution_data->id);
- $query = \Drupal::database()->select('lab_migration_solution_files');
- $query->fields('lab_migration_solution_files');
- $query->condition('solution_id', $solution_data->id);
- $solution_files_q = $query->execute();
- while ($solution_files_data = $solution_files_q->fetchObject())
- {
- $latex_filedata .= $experiment_data->number . $sep;
- $latex_filedata .= $experiment_data->title . $sep;
- $latex_filedata .= $solution_data->code_number . $sep;
- $latex_filedata .= $solution_data->caption . $sep;
- $latex_filedata .= $solution_files_data->filename . $sep;
- $latex_filedata .= $solution_files_data->filepath . $sep;
- $latex_filedata .= $solution_files_data->filetype . $sep;
- $latex_filedata .= $sep;
- $latex_filedata .= $solution_files_data->id;
- $latex_filedata .= $eol;
- }
- //$dependency_files_q = db_query("SELECT * FROM {lab_migration_solution_dependency} WHERE solution_id = %d", $solution_data->id);
- $query = \Drupal::database()->select('lab_migration_solution_dependency');
- $query->fields('lab_migration_solution_dependency');
- $query->condition('solution_id', $solution_data->id);
- $dependency_files_q = $query->execute();
- while ($dependency_files_data = $dependency_files_q->fetchObject())
- {
- //$dependency_q = db_query("SELECT * FROM {lab_migration_dependency_files} WHERE id = %d LIMIT 1", $dependency_files_data->dependency_id);
- $query = \Drupal::database()->select('lab_migration_dependency_files');
- $query->fields('lab_migration_dependency_files');
- $query->condition('id', $dependency_files_data->dependency_id);
- $query->range(0, 1);
- $dependency_q = $query->execute();
- if ($dependency_data = $dependency_q->fetchObject())
- {
- if (substr($dependency_data->filename, -3) != "wav")
- {
- $latex_filedata .= $experiment_data->number . $sep;
- $latex_filedata .= $experiment_data->title . $sep;
- $latex_filedata .= $solution_data->code_number . $sep;
- $latex_filedata .= $solution_data->caption . $sep;
- $latex_filedata .= $dependency_data->filename . $sep;
- $latex_filedata .= $dependency_data->filepath . $sep;
- $latex_filedata .= 'D' . $sep;
- $latex_filedata .= $dependency_data->caption . $sep;
- $latex_filedata .= $dependency_data->id;
- $latex_filedata .= $eol;
- $depedency_list[$dependency_data->id] = "D";
- }
- }
- }
+
+ $solutions = $solution_query->execute();
+
+ foreach ($solutions as $solution_data) {
+ // Gather solution files.
+ $solution_files = $this->database->select('lab_migration_solution_files', 'sf')
+ ->fields('sf')
+ ->condition('solution_id', $solution_data->id)
+ ->execute();
+
+ foreach ($solution_files as $sf) {
+ $latex_filedata .= implode($sep, [
+ $experiment_data->number,
+ $experiment_data->title,
+ $solution_data->code_number,
+ $solution_data->caption,
+ $sf->filename,
+ $sf->filepath,
+ $sf->filetype,
+ '',
+ $sf->id,
+ ]) . $eol;
+ }
+
+ // Gather dependency files.
+ $dep_refs = $this->database->select('lab_migration_solution_dependency', 'sd')
+ ->fields('sd')
+ ->condition('solution_id', $solution_data->id)
+ ->execute();
+
+ foreach ($dep_refs as $dep_ref) {
+ $dep = $this->database->select('lab_migration_dependency_files', 'df')
+ ->fields('df')
+ ->condition('id', $dep_ref->dependency_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if ($dep && substr($dep->filename, -3) !== 'wav') {
+ $latex_filedata .= implode($sep, [
+ $experiment_data->number,
+ $experiment_data->title,
+ $solution_data->code_number,
+ $solution_data->caption,
+ $dep->filename,
+ $dep->filepath,
+ 'D',
+ $dep->caption,
+ $dep->id,
+ ]) . $eol;
+ $dependency_list[$dep->id] = 'D';
}
+ }
}
- foreach ($depedency_list as $row => $data)
- {
- //$dependency_q = db_query("SELECT * FROM {lab_migration_dependency_files} WHERE id = %d LIMIT 1", $row);
- $query = \Drupal::database()->select('lab_migration_dependency_files');
- $query->fields('lab_migration_dependency_files');
- $query->condition('id', $row);
- $query->range(0, 1);
- $dependency_q = $query->execute();
- if ($dependency_data = $dependency_q->fetchObject())
- {
- $latex_dep_filedata .= $dependency_data->filename . $sep;
- $latex_dep_filedata .= $dependency_data->filepath . $sep;
- $latex_dep_filedata .= $dependency_data->caption . $sep;
- $latex_dep_filedata .= $dependency_data->id;
- $latex_dep_filedata .= $eol;
- }
+ }
+
+ // Build dependency file listing.
+ foreach ($dependency_list as $dep_id => $type) {
+ $dep = $this->database->select('lab_migration_dependency_files', 'df')
+ ->fields('df')
+ ->condition('id', $dep_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if ($dep) {
+ $latex_dep_filedata .= implode($sep, [
+ $dep->filename,
+ $dep->filepath,
+ $dep->caption,
+ $dep->id,
+ ]) . $eol;
}
-}
-}
-
\ No newline at end of file
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_lab_migration_module/src/Services/MailService.php b/modules/custom/DWSIM_lab_migration_module/src/Services/MailService.php
new file mode 100644
index 0000000..882af61
--- /dev/null
+++ b/modules/custom/DWSIM_lab_migration_module/src/Services/MailService.php
@@ -0,0 +1,210 @@
+mailManager = $mail_manager;
+ $this->loggerFactory = $logger_factory;
+ $this->configFactory = $config_factory;
+ $this->languageManager = $language_manager;
+ }
+
+ /**
+ * Sends an email using the module's hook_mail and MailManager.
+ *
+ * Validates recipient, attaches standard headers, and logs failures.
+ *
+ * @param string $module_name
+ * The module name (matches hook_mail module parameter).
+ * @param string $mail_key
+ * The mail key (matches the switch case in hook_mail).
+ * @param string $to
+ * The recipient email address.
+ * @param array $params
+ * Parameters passed to hook_mail.
+ * @param bool $send
+ * Whether to actually send (defaults TRUE).
+ *
+ * @return bool
+ * TRUE on success, FALSE on failure.
+ */
+ public function sendMail($module_name, $mail_key, $to, array $params = [], $send = TRUE) {
+ if (empty($to)) {
+ $this->loggerFactory->get($module_name)->warning(
+ 'Email not sent: recipient is empty for mail key: @key',
+ ['@key' => $mail_key]
+ );
+ return FALSE;
+ }
+
+ $config = $this->configFactory->get($module_name . '.settings');
+ $from = $config->get($module_name . '_from_email')
+ ?: $this->configFactory->get('system.site')->get('mail');
+
+ // Set standard headers if not already provided.
+ if (!isset($params[$mail_key]['headers'])) {
+ $params[$mail_key]['headers'] = [
+ 'From' => $from,
+ 'MIME-Version' => '1.0',
+ 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
+ 'Content-Transfer-Encoding' => '8Bit',
+ 'X-Mailer' => 'Drupal',
+ ];
+ }
+ else {
+ $params[$mail_key]['headers']['From'] = $params[$mail_key]['headers']['From'] ?? $from;
+ }
+
+ // Attach Cc from config if not already overridden.
+ if (!isset($params[$mail_key]['headers']['Cc'])) {
+ $cc = $config->get($module_name . '_cc_emails');
+ if (!empty($cc)) {
+ $params[$mail_key]['headers']['Cc'] = $cc;
+ }
+ }
+
+ // Attach Bcc from config if not already overridden.
+ if (!isset($params[$mail_key]['headers']['Bcc'])) {
+ $bcc = $config->get($module_name . '_emails');
+ if (!empty($bcc)) {
+ $params[$mail_key]['headers']['Bcc'] = $bcc;
+ }
+ }
+
+ $langcode = $this->languageManager->getCurrentLanguage()->getId();
+
+ $result = $this->mailManager->mail(
+ $module_name,
+ $mail_key,
+ $to,
+ $langcode,
+ $params,
+ $from,
+ $send
+ );
+
+ if (empty($result['result'])) {
+ $this->loggerFactory->get($module_name)->error(
+ 'Failed to send email for key @key to @to',
+ ['@key' => $mail_key, '@to' => $to]
+ );
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ /**
+ * Sends a proposal approval notification email.
+ *
+ * @param string $module_name
+ * @param int $proposal_id
+ * @param int $user_id
+ * @param string $to
+ * @param array $extra_params
+ *
+ * @return bool
+ */
+ public function sendApprovalMail($module_name, $proposal_id, $user_id, $to, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_approved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Sends a proposal rejection notification email.
+ *
+ * @param string $module_name
+ * @param int $proposal_id
+ * @param int $user_id
+ * @param string $to
+ * @param string $reason
+ * @param array $extra_params
+ *
+ * @return bool
+ */
+ public function sendRejectionMail($module_name, $proposal_id, $user_id, $to, $reason, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_disapproved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+ $params[$mail_key]['reason'] = $reason;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Sends a generic notification email with explicit subject and body.
+ *
+ * @param string $module_name
+ * @param string $mail_key
+ * @param string $to
+ * @param string $subject
+ * @param string $body
+ * @param array $extra_params
+ *
+ * @return bool
+ */
+ public function sendNotification($module_name, $mail_key, $to, $subject, $body, array $extra_params = []) {
+ $params = $extra_params;
+ $params[$mail_key]['subject'] = $subject;
+ $params[$mail_key]['body'] = $body;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/cheque_contact.inc b/modules/custom/DWSIM_textbook_companion/cheque_contact.inc
index 55c0af0..aed0067 100755
--- a/modules/custom/DWSIM_textbook_companion/cheque_contact.inc
+++ b/modules/custom/DWSIM_textbook_companion/cheque_contact.inc
@@ -1,162 +1,5 @@
fields('textbook_companion_paper');
- $query->condition('proposal_id', $proposal_id);
- $preference4_q = $query->execute();
-
- $form1=0;
- $form2=0;
- $form3=0;
- $form4=0;
- if($data = $preference4_q->fetchObject())
- {
- $form1 = $data->internship_form;
- $form2 = $data->copyright_form;
- $form3 = $data->undertaking_form;
- $form4 = $data->reciept_form;
- }
- else
- {
- $query = "Insert into {textbook_companion_paper} (proposal_id) values (:proposal_id)";
- $args = array(
- ":proposal_id"=>$proposal_id,
- );
- $result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
- }
- $form['proposal_id'] =array(
- '#type' => 'hidden',
- '#default_value' => $proposal_id,
- );
- $form['internshipform'] = array(
- '#type' => 'checkbox',
- '#title' => t('Recieved Internship Application'),
- '#description' => t('Check if the Internship Application has been recieved.'),
- '#default_value' => $form1,
- );
- $form['copyrighttransferform'] = array(
- '#type' => 'checkbox',
- '#title' => t('Recieved Copyright Transfer Form'),
- '#description' => t('Check if the Copyright Transfer Form has been recieved.'),
- '#default_value' => $form2,
- );
- $form['undertakingform'] = array(
- '#type' => 'checkbox',
- '#title' => t('Recieved Undertaking Form'),
- '#description' => t('Check if the Undertaking Form has been recieved.'),
- '#default_value' => $form3,
- );
- $form['recieptform'] = array(
- '#type' => 'checkbox',
- '#title' => t('Recieved Reciept Form'),
- '#description' => t('Check if the Reciept Form has been recieved.'),
- '#default_value' => $form4,
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Send Email')
- );
- $form['cancel'] = array(
- '#type' => 'markup',
- '#value' => l(t('Cancel'), 'manage_proposal/all'),
- );
- return $form;
-}
-
-function paper_submission_form_submit($form, &$form_state)
-{
-
- /*$query ="UPDATE {textbook_companion_paper} SET internship_form = ".$form_state['values']['internshipform'].", copyright_form = ".$form_state['values']['copyrighttransferform'].", undertaking_form= ".$form_state['values']['undertakingform'].", reciept_form= ".$form_state['values']['recieptform']." WHERE proposal_id = ".$form_state['values']['proposal_id'];
- db_query($query);*/
-
- $query = db_update('textbook_companion_paper');
- $query->fields(array(
- 'internship_form' => $form_state[ values ][ internshipform ],
- 'copyright_form' => $form_state[ values ][ copyrighttransferform ],
- 'undertaking_form' => $form_state[ values ][ undertakingform ],
- 'reciept_form' => $form_state[ values ][ recieptform ],
- ));
- $query->condition('proposal_id', $form_state['values']['proposal_id']);
- $num_updated = $query->execute();
-
- /************************************************
- Check For the Internship Form is checked or not
- ************************************************/
- if ($form_state['values']['internshipform'] == 1)
- {
- /* sending email */
- $book_user = user_load($proposal_data->uid);
- $params['proposal_completed']['proposal_id'] = $proposal_id;
- $params['proposal_completed']['user_id'] = $proposal_data->uid;
- $email_to = $book_user->mail;
- if (!drupal_mail('textbook_companion', 'internship_form', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('Internship Form for Book proposal has been recieved. User has been notified .', 'status');
- }
- else
- {
- if (!drupal_mail('textbook_companion', 'internship_form_not', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('Internship Form for Book proposal has not been recieved. User has been notified .', 'status');
- }
-
- /************************************************
- Check For the Copyright Form is checked or not
- ************************************************/
-
- if ($form_state['values']['copyrighttransferform'] == 1)
- {
- /* sending email */
- $book_user = user_load($proposal_data->uid);
- $params['proposal_completed']['proposal_id'] = $proposal_id;
- $params['proposal_completed']['user_id'] = $proposal_data->uid;
- $email_to = $book_user->mail;
- if (!drupal_mail('textbook_companion', 'copyrighttransfer_form', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('Copyright Form for Book proposal has been recieved. User has been notified .', 'status');
- }
- else
- {
- if (!drupal_mail('textbook_companion', 'copyrighttransfer_form_not', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('Copyright Transfer Form for Book proposal has not been recieved. User has been notified .', 'status');
- }
-
- /************************************************
- Check For the Undertaking Form is checked or not
- ************************************************/
-
- if ($form_state['values']['undertakingform'] == 1)
- {
- /* sending email */
- $book_user = user_load($proposal_data->uid);
- $params['proposal_completed']['proposal_id'] = $proposal_id;
- $params['proposal_completed']['user_id'] = $proposal_data->uid;
- $email_to = $book_user->mail;
- if (!drupal_mail('textbook_companion', 'undertakingform_form', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('Undertaking Form for Book proposal has been recieved. User has been notified .', 'status');
- }
- else
- {
- if (!drupal_mail('textbook_companion', 'undertakingform_form_not', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('Undertaking Form for Book proposal has not been recieved. User has been notified .', 'status');
- }
-
-drupal_set_message(t('Proposal Updated'), 'status');
-}
-
-
/*function proposal_edit_form_validate($form, &$form_state)
{
/* mobile */
@@ -451,455 +294,6 @@ function cheque_contct_form()
}
-function cheque_status_form($form_state, $proposal_id)
-{
- global $user;
-
- /* get current proposal */
- $proposal_id = arg(2);
-
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id =".$proposal_id);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
-
- /*$proposal_q1 = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id =".$proposal_id);*/
- $query = db_select('textbook_companion_cheque');
- $query->fields('textbook_companion_cheque');
- $query->condition('proposal_id', $proposal_id);
- $proposal_q1 = $query->execute();
-
-
- $proposal_data1 = $proposal_q1->fetchObject();
- if (!$proposal_data = $proposal_q->fetchObject())
- {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('manage_proposal');
- return;
- }
- $form['proposal_id'] =array(
- '#type' => 'hidden',
- '#default_value' => $proposal_id,
- );
-
- /*$empty = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = ".$proposal_id);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $proposal_id);
- $empty = $query->execute();
-
- if(!$empty)
- {
- /*$prop =db_query("insert into {textbook_companion_cheque} (proposal_id) values(%d)",$proposal_id);*/
-
- $query = "insert into {textbook_companion_cheque} (proposal_id) values (:proposal_id)";
- $args = array(
- ":proposal_id"=>$proposal_id,
- );
- $result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
- }
- $form['candidate_detail'] = array(
- '#type' => 'fieldset',
- '#title' => t('Candidate Details'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'candidate_detail'),
- );
- $form['candidate_detail']['full_name'] = array(
- '#type' => 'item',
- '#markup' => $proposal_data->full_name,
- '#title' => t('Contributor Name'),
- );
- $form['candidate_detail']['email'] = array(
- '#type' => 'item',
- '#markup' => user_load($proposal_data->uid)->mail,
- '#title' => t('Email'),
- );
- $form['candidate_detail']['mobile'] = array(
- '#type' => 'item',
- '#markup' => $proposal_data->mobile,
- '#title' => t('Mobile'),
- );
- $form['candidate_detail']['alt_mobile'] = array(
- '#type' => 'item',
- '#markup' => $proposal_data1->alt_mobno,
- '#title' => t('Alternate Mobile No.'),
- );
- /*$form_q=db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id =".$proposal_id);
- $form_data=db_fetch_object($form_q);*/
-
- $query = db_select('textbook_companion_paper');
- $query->fields('textbook_companion_paper');
- $query->condition('proposal_id', $proposal_id);
- $result = $query->execute();
- $form_data=$result->fetchObject();
-
- /* get book preference */
- $preference_html = '';
-
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('pref_number', 'ASC');
- $preference_q = $query->execute();
-
- while ($preference_data = $preference_q->fetchObject())
- {
- if ($preference_data->approval_status == 1)
- $preference_html .= '' . $preference_data->book . ' (Written by ' . $preference_data->author . ') - Approved Book ';
- else
- $preference_html .= '' . $preference_data->book . ' (Written by ' . $preference_data->author . ') ';
- }
- $preference_html .= ' ';
- $form['book_preference_f'] = array(
- '#type' => 'fieldset',
- '#title' => t('Book Preferences/Application Status'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'book_preference_f'),
- );
- $form['book_preference_f']['book_preference'] = array(
- '#type' => 'item',
- '#markup' => $preference_html,
- '#title' => t('Book Preferences'),
- );
-
- /*$chq_q=db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id = %d", $proposal_id);
- $chq_data=db_fetch_object($chq_q);*/
- $query = db_select('textbook_companion_cheque');
- $query->fields('textbook_companion_cheque');
- $query->condition('proposal_id', $proposal_id);
- $result = $query->execute();
- $chq_data=$result->fetchObject();
-
- $form_html .= '';
- if($form_data->internship_form)
- {
- $form_html .= 'Internship Application Form Submitted ';
- }
- else
- {
- $form_html .= 'Internship Application Form Not Submitted ';
- }
- if($form_data->copyright_form)
- {
- $form_html .= 'Copyright Application Form Submitted ';
- }
- else
- {
- $form_html .= 'Copyright Application Form Not Submitted ';
- }
- if($form_data->undertaking_form)
- {
- $form_html .= 'Undertaking Application Form Submitted ';
- }
- else
- {
- $form_html .= 'Undertaking Application Form Not Submitted ';
- }
- $form_html .= ' ';
- $form['book_preference_f']['formsubmit'] = array(
- '#type' => 'item',
- '#markup' => $form_html,
- '#title' => t('Application Form Status'),
- );
- $form['stu_cheque_details'] = array(
- '#type' => 'fieldset',
- '#title' => t('Student Cheque Details'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'stu_cheque_details'),
- );
- $form['tea_cheque_details'] = array(
- '#type' => 'fieldset',
- '#title' => t('Teacher Cheque Details'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'tea_cheque_details'),
- );
- $form['perm_cheque_address'] = array(
- '#type' => 'fieldset',
- '#title' => t('Permanent Address'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'perm_cheque_address'),
- );
- $form['temp_cheque_address'] = array(
- '#type' => 'fieldset',
- '#title' => t('Temporary Address'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'temp_cheque_address'),
- );
- $form['cheque_delivery'] = array(
- '#type' => 'fieldset',
- '#title' => t('Cheque Delivery'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'cheque_delivery'),
- );
- $form['commentf'] = array(
- '#type' => 'fieldset',
- '#title' => t('Remark'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE,
- '#attributes' => array('id' => 'commentf'),
- );
- /*$chq4_q = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id);*/
- $query = db_select('textbook_companion_cheque');
- $query->fields('textbook_companion_cheque');
- $query->condition('proposal_id', $proposal_id);
- $chq4_q = $query->execute();
-
- $chq1 = '';
- $chq2 = '';
- $chq3 = '';
- $chq4 = '';
- $chq5 = '';
- $chq6 = '';
- $chq7 = '';
- $chq8 = '';
- $chq9 = '';
- $chq10 = '';
- $chq11 = '';
- $chq12 = '';
- $chq13 = '';
- $chq14 = '';
- $chq15 = '';
- $chq16 = '';
- $chq17 = '';
- if($chqe = $chq4_q->fetchObject())
- {
- $chq1 = $chqe->cheque_no;
- $chq2 = $chqe->address;
- $chq3 = $chqe->cheque_amt;
- $chq4 = $chqe->cheque_sent;
- $chq5 = $chqe->cheque_cleared;
- $chq6 = $chqe->perm_chq_address2;
- $chq7 = $chqe->perm_city;
- $chq8 = $chqe->perm_state;
- $chq9 = $chqe->perm_pincode;
- $chq10 = $chqe->temp_chq_address;
- $chq11 = $chqe->temp_chq_address2;
- $chq12 = $chqe->temp_city;
- $chq13 = $chqe->temp_state;
- $chq14 = $chqe->temp_pincode;
- $chq15 = $chqe->commentf;
- $chq16 = $chqe->t_cheque_amt;
- $chq17 = $chqe->t_cheque_no;
- $form['stu_cheque_details']['cheque_no'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq1,
- '#title' => t('Cheque No'),
- '#size' => 54,
- );
- $form['tea_cheque_details']['cheque_no_t'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq17,
- '#title' => t('Cheque No'),
- '#size' => 54,
- );
- $form['perm_cheque_address']['chq_address'] = array(
- '#type' => 'textarea',
- '#default_value' => $chq2,
- '#title' => t('Address Street 1'),
- );
- $form['perm_cheque_address']['chq_address']['#attributes']['readonly'] = 'readonly';
- $form['perm_cheque_address']['perm_city'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq7,
- '#title' => t('City'),
- '#size' => 35,
- );
- $form['perm_cheque_address']['perm_city']['#attributes']['readonly'] = 'readonly';
- $form['perm_cheque_address']['perm_state'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq8,
- '#title' => t('State'),
- '#size' => 35,
- );
- $form['perm_cheque_address']['perm_state']['#attributes']['readonly'] = 'readonly';
- $form['perm_cheque_address']['perm_pincode'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq9,
- '#title' => t('Zip code'),
- '#size' => 35,
- );
- $form['perm_cheque_address']['perm_pincode']['#attributes']['readonly'] = 'readonly';
- $form['stu_cheque_details']['cheq_amt'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq3,
- '#title' => t('Cheque Amount'),
- '#size' => 54,
- );
- $form['tea_cheque_details']['cheq_amt_t'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq17,
- '#title' => t('Cheque Amount'),
- '#size' => 54,
- );
- $form['temp_cheque_address']['temp_chq_address'] = array(
- '#type' => 'textarea',
- '#default_value' => $chq10,
- '#title' => t('Address Street 1'),
- );
- $form['temp_cheque_address']['temp_chq_address']['#attributes']['readonly'] = 'readonly';
- $form['temp_cheque_address']['temp_city'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq12,
- '#title' => t('City'),
- '#size' => 35,
- );
- $form['temp_cheque_address']['temp_city']['#attributes']['readonly'] = 'readonly';
- $form['temp_cheque_address']['temp_state'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq13,
- '#title' => t('State'),
- '#size' => 35,
- );
- $form['temp_cheque_address']['temp_state']['#attributes']['readonly'] = 'readonly';
- $form['temp_cheque_address']['temp_pincode'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq14,
- '#title' => t('Zipcode'),
- '#size' => 35,
- );
- $form['temp_cheque_address']['temp_pincode']['#attributes']['readonly'] = 'readonly';
- }
- else
- {
- $form['stu_cheque_details']['cheque_no'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq1,
- '#title' => t('Cheque No'),
- );
- $form['tea_cheque_details']['cheque_no_t'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq16,
- '#title' => t('Cheque No'),
- );
- $form['perm_cheque_address']['chq_address'] = array(
- '#type' => 'textarea',
- '#default_value' => $chq2,
- '#title' => t('Address Street 1'),
- );
- $form['perm_cheque_address']['perm_city'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq7,
- '#title' => t('City'),
- '#size' => 35,
- );
- $form['perm_cheque_address']['perm_state'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq8,
- '#title' => t('State'),
- '#size' => 35,
- );
- $form['perm_cheque_address']['perm_pincode'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq9,
- '#title' => t('Zip code'),
- '#size' => 35,
- );
- $form['perm_cheque_address']['same_address'] = array(
- '#type' => 'checkbox',
- '#title' => t('Same As Permanent Address'),
- '#attributes' => array('onclick' => 'copy_address()'),
- );
- $form['stu_cheque_details']['cheq_amt'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq3,
- '#title' => t('Cheque Amount'),
- );
- $form['tea_cheque_details']['cheq_amt'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq17,
- '#title' => t('Cheque Amount'),
- );
- $form['temp_cheque_address']['temp_chq_address'] = array(
- '#type' => 'textarea',
- '#default_value' => $chq10,
- '#title' => t('Address Street 1'),
- );
- $form['temp_cheque_address']['temp_city'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq12,
- '#title' => t('City'),
- '#size' => 35,
- );
- $form['temp_cheque_address']['temp_state'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq13,
- '#title' => t('State'),
- '#size' => 35,
- );
- $form['temp_cheque_address']['temp_pincode'] = array(
- '#type' => 'textfield',
- '#default_value' => $chq14,
- '#title' => t('Zip code'),
- '#size' => 35,
- );
- $form['temp_cheque_address']['same_address'] = array(
- '#type' => 'checkbox',
- '#title' => t('Same As Permanent Address'),
- );
- $form['temp_cheque_address']['same_address'] = array(
- '#type' => 'checkbox',
- '#title' => t('Same As Permanent Address'),
- '#attributes' => array('onclick' => 'copy_address()'),
- );
- }
- $form['cheque_delivery']['cheque_sent'] = array(
- '#type' => 'checkbox',
- '#title' => t('Cheque Sent'),
- '#default_value' => $chq4,
- '#description' => t('Check if the Cheque has been sent to the user.'),
- '#attributes' => array('id' => 'cheque_sent'),
- );
- $form['cheque_delivery']['cheque_cleared'] = array(
- '#type' => 'checkbox',
- '#title' => t('Cheque Cleared'),
- '#default_value' => $chq5,
- '#description' => t('Check if the Cheque has been Realised to the User Account.'),
- '#attributes' => array('id' => 'cheque_cleared'),
- );
- $form['commentf']['comment_cheque'] = array(
- '#type' => 'textarea',
- '#size' => 35,
- '#attributes' => array('id' => 'comment'),
- '#default_value' => $chq15,
- );
- $form['proposal_id'] = array(
- '#type' => 'hidden',
- '#value' => $proposal_id,
- );
-
- /*$preference1_p = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id = %d ORDER BY id ASC", $proposal_id); */
-
- $query = db_select('textbook_companion_paper');
- $query->fields('textbook_companion_paper');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('id', 'ASC');
- $preference1_p = $query->execute();
-
- if (!($proposal_data1 = $preference1_p->fetchObject()))
- {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('manage_proposal');
- return;
- }
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit')
- );
- $form['cancel'] = array(
- '#type' => 'markup',
- '#value' => l(t('Cancel'), 'manage_proposal/all'),
- );
- return $form;
-}
/*function cheque_status_form_validate($form, &$form_state)
{
@@ -926,121 +320,6 @@ function cheque_status_form($form_state, $proposal_id)
return;
}
}*/
-function cheque_status_form_submit($form, &$form_state)
-{
- global $user;
- $proposal_id=arg(2);
-
-
- /*$query ="UPDATE {textbook_companion_cheque} SET
- cheque_no = ".$form_state['values']['cheque_no'].",
- cheque_amt = ".$form_state['values']['cheq_amt'].",
- alt_mobno = '".$form_state['values']['mobileno2']."',
- address = '".$form_state['values']['chq_address']."',
- perm_city = '".$form_state['values']['perm_city']."',
- perm_state = '".$form_state['values']['perm_state']."',
- perm_pincode = '".$form_state['values']['perm_pincode']."',
- temp_chq_address = '".$form_state['values']['temp_chq_address']."',
- temp_city = '".$form_state['values']['temp_city']."',
- temp_state = '".$form_state['values']['temp_state']."',
- temp_pincode = '".$form_state['values']['temp_pincode']."',
- commentf = '".$form_state['values']['comment_cheque']."',
- t_cheque_no = ".$form_state['values']['cheque_no_t'].",
- t_cheque_amt = ".$form_state['values']['cheq_amt_t']."
- WHERE proposal_id = ".$proposal_id;
-
- db_query($query);*/
-
- $query = db_update('textbook_companion_cheque');
- $query->fields(array(
- 'cheque_no' => $form_state[ values ][ cheque_no ],
- 'cheque_amt' => $form_state[ values ][ cheq_amt ],
- 'alt_mobno' => $form_state[ values ][ mobileno2 ],
- 'address' => $form_state[ values ][ chq_address ],
- 'perm_city' => $form_state[ values ][ perm_city ],
- 'perm_state' => $form_state[ values ][ perm_state ],
- 'perm_pincode' => $form_state[ values ][ perm_pincode ],
- 'temp_chq_address' => $form_state[ values ][ temp_chq_address ],
- 'temp_city' => $form_state[ values ][ temp_city ],
- 'temp_state' => $form_state[ values ][ temp_state ],
- 'temp_pincode' => $form_state[ values ][ temp_pincode ],
- 'commentf' => $form_state[ values ][ comment_cheque ],
- 't_cheque_no' => $form_state[ values ][ cheque_no_t ],
- 't_cheque_amt' => $form_state[ values ][ cheq_amt_t ],
- ));
- $query->condition('proposal_id', $proposal_id);
- $num_updated = $query->execute();
-
- if ($form_state['values']['cheque_sent'] == 1)
- {
- /* sending email */
- /*$query ="UPDATE {textbook_companion_cheque} SET cheque_sent = ".$form_state['values']['cheque_sent']." WHERE proposal_id = ".$proposal_id;
- db_query($query);*/
-
- $query = db_update('textbook_companion_cheque');
- $query->fields(array(
- 'cheque_sent' => $form_state[ values ][ cheque_sent ],
- ));
- $query->condition('proposal_id', $proposal_id);
- $num_updated = $query->execute();
-
- $book_user = user_load($proposal_data->uid);
- $params['proposal_completed']['proposal_id'] = $proposal_id;
- $params['proposal_completed']['user_id'] = $proposal_data->uid;
- $email_to = $book_user->mail;
- if (!drupal_mail('textbook_companion', 'cheque_sent', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('Cheque for Book proposal has been Sent. User has been notified .', 'status');
- }
-
-
- if ($form_state['values']['cheque_cleared'] == 1)
- {
- /*$query ="UPDATE {textbook_companion_cheque} SET cheque_cleared = ".$form_state['values']['cheque_cleared']." WHERE proposal_id = ".$proposal_id;
- db_query($query);*/
-
- $query = db_update('textbook_companion_cheque');
- $query->fields(array(
- 'cheque_cleared' => $form_state[ values ][ cheque_cleared ],
- ));
- $query->condition('proposal_id', $proposal_id);
- $num_updated = $query->execute();
-
- $curtime = MySQL_NOW();
- echo $curtime;
- drupal_set_message('Cheque Has Been Debited into User Account.', 'status');
- /*$queryc ="UPDATE {textbook_companion_cheque} SET cheque_dispatch_date = NOW() WHERE proposal_id = ".$form_state['values']['proposal_id']."";
- db_query($queryc);*/
-
- $query = db_update('textbook_companion_cheque');
- $query->fields(array(
- 'cheque_dispatch_date' => 'NOW',
- ));
- $query->condition('proposal_id', $form_state['values']['proposal_id']);
- $num_updated = $query->execute();
- }
-
- /************************************************
- Check For the Remark
- ************************************************/
- if ($form_state['values']['comment_cheque'])
- {
- /* sending email */
- $book_user = user_load($proposal_data->uid);
- $params['proposal_completed']['proposal_id'] = $proposal_id;
- $params['proposal_completed']['user_id'] = $proposal_data->uid;
- $email_to = $book_user->mail;
- if (!drupal_mail('textbook_companion', 'remark', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message(t('Remark Updated. User has been notified'), 'status');
- }
- else
- {
- if (!drupal_mail('textbook_companion', 'remark_not', $email_to , language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message('No Remarks. User has been notified .', 'status');
- }
-}
function MySQL_NOW(){ return date('Y-m-d'); }
function contact_details($form_state)
@@ -1399,45 +678,4 @@ function copy_address()
);
}
-function cheque_report_form()
-{
- /*$search_qx = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id)");*/
-
- $query = db_select('textbook_companion_proposal', 'p');
- $query->join('textbook_companion_cheque','c','p.id = c.proposal_id');
- $query->fields('p',array('textbook_companion_proposal'));
- $query->fields('c',array('textbook_companion_cheque'));
- $query->condition('c.address_con', 'Submitted');
- $search_qx = $query->execute();
-
- while ($search_datax = $search_qx->fetchObject())
- {
- $result = array($search_datax->full_name,$search_datax->address_con,$search_datax->cheque_no,$search_datax->cheque_dispatch_date);
- }
- if (!$result) die('Couldn\'t fetch records');
- $num_fields = count($result);
- $headers = array();
- for ($i = 0; $i < $num_fields; $i++)
- {
- $headers[] = mysql_field_name($result , $i);
- }
-
- $row = array();
- $fp = fopen('php://output', 'w');
- $search_header = array('Name Of The Student', 'Application Form Status', 'Cheque No', 'Cheque Clearance Date');
- fputcsv($fp, $search_header);
- if ($fp && $result)
- {
- header('Content-Type: text/csv');
- header('Content-Disposition: attachment; filename="Report.csv"');
- header('Pragma: no-cache');
- header('Expires: 0');
- fputcsv($fp, $headers);
- while ($row = mysql_fetch_row($result))
- {
- fputcsv($fp, array_values($row));
- }
- die;
- }
-}
?>
diff --git a/modules/custom/DWSIM_textbook_companion/code.inc b/modules/custom/DWSIM_textbook_companion/code.inc
index 2966162..ab5da0e 100755
--- a/modules/custom/DWSIM_textbook_companion/code.inc
+++ b/modules/custom/DWSIM_textbook_companion/code.inc
@@ -1,446 +1,10 @@
uid);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- if (!$proposal_data) {
- drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error');
- drupal_goto('');
- } //!$proposal_data
- if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) {
- switch ($proposal_data->proposal_status) {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error');
- drupal_goto('');
- return;
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status');
- drupal_goto('');
- return;
- break;
- case 5:
- drupal_set_message(t('You have submitted your all codes.'), 'status');
- drupal_goto('');
- return;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if (!$preference_data) {
- drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
- $form['#attributes'] = array(
- 'enctype' => "multipart/form-data"
- );
- $form['book_details']['pref_id'] = array(
- '#type' => 'hidden',
- '#value' => $preference_data->id
- );
- $form['book_details']['book'] = array(
- '#type' => 'item',
- '#markup' => $preference_data->book,
- '#title' => t('Title of the Book')
- );
- $form['contributor_name'] = array(
- '#type' => 'item',
- '#markup' => $proposal_data->full_name,
- '#title' => t('Contributor Name')
- );
- $options = array(
- '' => '(Select)'
- );
- for ($i = 1; $i <= 100; $i++) {
- $options[$i] = $i;
- } //$i = 1; $i <= 100; $i++
- $form['number'] = array(
- '#type' => 'select',
- '#title' => t('Chapter No'),
- '#options' => $options,
- '#multiple' => FALSE,
- '#size' => 1,
- '#required' => TRUE,
- '#ajax' => array(
- 'callback' => 'ajax_chapter_name_callback'
- )
- );
- $form['name'] = array(
- '#type' => 'textfield',
- '#title' => t('Title of the Chapter'),
- '#size' => 40,
- '#maxlength' => 255,
- '#required' => TRUE,
- '#prefix' => '',
- '#suffix' => '
'
- );
- $form['example_number'] = array(
- '#type' => 'textfield',
- '#title' => t('Example No'),
- '#size' => 5,
- '#maxlength' => 10,
- '#description' => t("Example number should be separated by dots only. Example: 1.1.a or 1.1.1"),
- '#required' => TRUE
- );
- $form['example_caption'] = array(
- '#type' => 'textfield',
- '#title' => t('Caption'),
- '#size' => 40,
- '#maxlength' => 255,
- '#description' => t('Example caption should contain only alphabets, numbers and spaces.'),
- '#required' => TRUE
- );
- $form['example_warning'] = array(
- '#type' => 'item',
- '#title' => t('You should upload all the files as zip (main or source files, result files, executable file if any): '),
- '#prefix' => '',
- '#suffix' => '
'
- );
- $form['sourcefile'] = array(
- '#type' => 'fieldset',
- '#title' => t('Main or Source Files'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE
- );
- $form['sourcefile']['sourcefile1'] = array(
- '#type' => 'file',
- '#title' => t('Upload main or source file'),
- '#size' => 48,
- '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') . ' '
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit')
- );
- $form['cancel'] = array(
- '#type' => 'markup',
- '#value' => l(t('Cancel'), 'textbook-companion/code')
- );
- return $form;
-}
-function upload_examples_form_validate($form, &$form_state)
-{
- if (!check_name($form_state['values']['name']))
- form_set_error('name', t('Title of the Chapter can contain only alphabets, numbers and spaces.'));
- if (!check_name($form_state['values']['example_caption']))
- form_set_error('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.'));
- if (!check_chapter_number($form_state['values']['example_number']))
- form_set_error('example_number', t('Invalid Example Number. Example Number can contain only alphabets and numbers sepereated by dot.'));
- if (isset($_FILES['files'])) {
- /* check if atleast one source or result file is uploaded */
- if (!($_FILES['files']['name']['sourcefile1']))
- form_set_error('sourcefile1', t('Please upload source file.'));
- /* check for valid filename extensions */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- if ($file_name) {
- $allowed_extensions_str = variable_get('textbook_companion_source_extensions', '');
- $allowed_extensions = explode(',', $allowed_extensions_str);
- $temp_ext = explode('.', strtolower($_FILES['files']['name'][$file_form_name]));
- $temp_extension = end($temp_ext);
- //$temp_extension = substr($_FILES['files']['name'][$file_form_name], strripos($_FILES['files']['name'][$file_form_name], '.')); // get file name
- //var_dump($temp_extension); die;
- if (!in_array($temp_extension, $allowed_extensions))
- form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.'));
- if ($_FILES['files']['size'][$file_form_name] <= 0)
- form_set_error($file_form_name, t('File size cannot be zero.'));
- /* check if valid file name
- if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name]))
- form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.'));*/
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- } //isset($_FILES['files'])
-}
-function upload_examples_form_submit($form, &$form_state)
-{
- global $user;
- $root_path = textbook_companion_path();
- /************************ start approve book details ************************/
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- if (!$proposal_data) {
- drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error');
- drupal_goto('');
- } //!$proposal_data
- if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) {
- switch ($proposal_data->proposal_status) {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error');
- drupal_goto('');
- return;
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status');
- drupal_goto('');
- return;
- break;
- case 5:
- drupal_set_message(t('You have submmited your all codes'), 'status');
- drupal_goto('');
- return;
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if (!$preference_data) {
- drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
- /************************ end approve book details **************************/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $result = $query->execute()->rowCount();
- if ($result > 1) {
- drupal_set_message(t('You cannot upload your code. This name of book directory alrady preasent in directory folder, please contact to administrator.'), 'error');
- return;
- } //$result > 1
- $proposal_directory = $preference_data->directory_name;
- $dest_path = $proposal_directory . '/';
- if (!is_dir($root_path . $dest_path)) {
- if (!mkdir($root_path . $dest_path)) {
- drupal_set_message(t('You cannot upload your code. Error in creating directory'), 'error');
- } //!mkdir($root_path . $dest_path)
- } //!is_dir($root_path . $dest_path)
- /* inserting chapter details */
- $chapter_id = 0;
- /*$chapter_result = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d AND number = %d", $preference_id, $form_state['values']['number']);*/
- $preference_id = $preference_data->id;
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $preference_id);
- $query->condition('number', $form_state['values']['number']);
- $chapter_result = $query->execute();
- if (!$chapter_row = $chapter_result->fetchObject()) {
- /*db_query("INSERT INTO {textbook_companion_chapter} (preference_id, number, name) VALUES (%d, '%s', '%s')",
- $preference_id,
- $form_state['values']['number'],
- $form_state['values']['name']
- );
- $chapter_id = db_last_insert_id('textbook_companion_chapter', 'id'); */
- $query = "INSERT INTO {textbook_companion_chapter} (preference_id, number, name) VALUES(:preference_id, :number, :name)";
- $args = array(
- ":preference_id" => $preference_id,
- ":number" => $form_state['values']['number'],
- ":name" => $form_state['values']['name']
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- $chapter_id = $result;
- } //!$chapter_row = $chapter_result->fetchObject()
- else {
- $chapter_id = $chapter_row->id;
- /*db_query("UPDATE {textbook_companion_chapter} SET name = '%s' WHERE id = %d", $form_state['values']['name'], $chapter_id);*/
- $query = db_update('textbook_companion_chapter');
- $query->fields(array(
- 'name' => $form_state['values']['name']
- ));
- $query->condition('id', $chapter_id);
- $num_updated = $query->execute();
- }
- /* get example details - dont allow if already example present */
- /*$cur_example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND number = '%s'", $chapter_id, $form_state['values']['example_number']);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_id);
- $query->condition('number', $form_state['values']['example_number']);
- $cur_example_q = $query->execute();
- if ($cur_example_d = $cur_example_q->fetchObject()) {
- if ($cur_example_d->approval_status == 1) {
- drupal_set_message(t("Example already approved. Cannot overwrite it."), 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //$cur_example_d->approval_status == 1
- else if ($cur_example_d->approval_status == 0) {
- drupal_set_message(t("Example is under pending review. Delete the example and reupload it."), 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //$cur_example_d->approval_status == 0
- else {
- drupal_set_message(t("Error uploading example. Please contact administrator."), 'error');
- drupal_goto('textbook-companion/code');
- return;
- }
- } //$cur_example_d = $cur_example_q->fetchObject()
- /* creating directories */
- $dest_path .= 'CH' . $form_state['values']['number'] . '/';
- if (!is_dir($root_path . $dest_path))
- mkdir($root_path . $dest_path);
- $dest_path .= 'EX' . $form_state['values']['example_number'] . '/';
- if (!is_dir($root_path . $dest_path))
- mkdir($root_path . $dest_path);
- $filepath = 'CH' . $form_state['values']['number'] . '/' . 'EX' . $form_state['values']['example_number'] . '/';
- /* creating example database entry */
- /*db_query("INSERT INTO {textbook_companion_example} (chapter_id, number, caption, approval_status, timestamp) VALUES (%d, '%s', '%s', %d, %d)",
- $chapter_id,
- $form_state['values']['example_number'],
- $form_state['values']['example_caption'],
- 0,
- time()
- );
- $example_id = db_last_insert_id('textbook_companion_example', 'id');*/
- $query = "INSERT INTO {textbook_companion_example} (chapter_id, number, caption, approval_date, approval_status, timestamp) VALUES (:chapter_id, :number, :caption, :approval_date,:approval_status, :timestamp)";
- $args = array(
- ":chapter_id" => $chapter_id,
- ":number" => $form_state['values']['example_number'],
- ":caption" => $form_state['values']['example_caption'],
- ":approval_date" => time(),
- ":approval_status" => 0,
- ":timestamp" => time()
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- $example_id = $result;
- /* linking existing dependencies */
- /* foreach ($form_state['values']['existing_depfile']['dep_chapter_example_files'] as $row)
- {
- if ($row > 0)
- {
- /* insterting into database */
- /*db_query("INSERT INTO {textbook_companion_example_dependency} (example_id, dependency_id, approval_status, timestamp)
- VALUES (%d, %d, %d, %d)",
- $example_id,
- $row,
- 0,
- time()
- );*/
- /*$query = "INSERT INTO {textbook_companion_example_dependency} (example_id, dependency_id, approval_status, timestamp)
- VALUES (:example_id, :dependency_id, :approval_status, :timestamp)";
- $args = array(
- ":example_id"=>$example_id,
- ":dependency_id"=>$row,
- ":approval_status"=> 0,
- ":timestamp"=>time(),
- );
- $result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
- }
- }*/
- /* uploading files */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- if ($file_name) {
- /* checking file type */
- $file_type = 'S';
- if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- drupal_set_message(t("Error uploading file. File !filename already exists.", array(
- '!filename' => $_FILES['files']['name'][$file_form_name]
- )), 'error');
- return;
- } //file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
- /* uploading file */
- if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- /* for uploaded files making an entry in the database */
- /*db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp)
- VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)",
- $example_id,
- $_FILES['files']['name'][$file_form_name],
- $dest_path . $_FILES['files']['name'][$file_form_name],
- $_FILES['files']['type'][$file_form_name],
- $_FILES['files']['size'][$file_form_name],
- $file_type,
- time()
- );*/
- $query = "INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath,filemime, filesize, filetype, timestamp)
- VALUES (:example_id, :filename ,:filepath,:filemime, :filesize, :filetype, :timestamp)";
- $args = array(
- ":example_id" => $example_id,
- ":filename" => $_FILES['files']['name'][$file_form_name],
- ":filepath" => $filepath . $_FILES['files']['name'][$file_form_name],
- ":filemime" => 'application/zip',
- ":filesize" => $_FILES['files']['size'][$file_form_name],
- ":filetype" => $file_type,
- ":timestamp" => time()
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- drupal_set_message($file_name . ' uploaded successfully.', 'status');
- } //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
- else {
- drupal_set_message('Error uploading file : ' . $dest_path . '/' . $file_name, 'error');
- }
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- drupal_set_message('Example uploaded successfully.', 'status');
- /* sending email */
- $email_to = $user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_bcc_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $params['example_uploaded']['example_id'] = $example_id;
- $params['example_uploaded']['user_id'] = $user->uid;
- $params['example_uploaded']['headers'] = array(
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc
- );
- if (!drupal_mail('textbook_companion', 'example_uploaded', $email_to, language_default(), $params, $from, TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_goto('textbook-companion/code');
-}
+
+/**
+ * Legacy upload_examples_form / ajax_chapter_name_callback removed.
+ * Active: Drupal\textbook_companion\Form\UploadExamplesForm
+ */
+
/******************************************************************************/
/***************************** DELETE EXAMPLE *********************************/
/******************************************************************************/
@@ -588,36 +152,3 @@ function _list_of_book_dependency_files()
);
}
-function ajax_chapter_name_callback($form, &$form_state)
-{
- $pref_id = $form_state['values']['pref_id'];
- $chapter_number = $form_state['values']['number'];
- $query = "SELECT * FROM `textbook_companion_chapter` WHERE `preference_id` = :pref_id AND `number` = :number";
- $arg = array(
- ':pref_id' => $pref_id,
- ':number' => $chapter_number
- );
- $chapter_name_data = db_query($query, $arg);
-
- if ($chapter_name_data->rowCount() > 0) {
-
- //$form['name']['#default_value'] = $chapter_name_data->fetchObject()->name;
- $form['name']['#value'] = $chapter_name_data->fetchObject()->name;
- $form['name']['#readonly'] = TRUE;
- $form['name']['#attributes']['readonly'] = 'readonly';
- $commands[] = ajax_command_replace("#ajax-chapter-name-replace", drupal_render($form['name']));
-
- } //$chapter_name_data->rowCount() > 0
- else {
- $form['name']['#value'] = ' ';
- $form['name']['#readonly'] = FALSE;
- //$form['name']['#attributes']['readonly'] = 'readonly';
- $commands[] = ajax_command_replace("#ajax-chapter-name-replace", drupal_render($form['name']));
-
- }
- return array(
- '#type' => 'ajax',
- '#commands' => $commands
- );
-
-}
diff --git a/modules/custom/DWSIM_textbook_companion/pdf/generate_pdf.inc b/modules/custom/DWSIM_textbook_companion/pdf/generate_pdf.inc
index 06534ed..57eb3cc 100755
--- a/modules/custom/DWSIM_textbook_companion/pdf/generate_pdf.inc
+++ b/modules/custom/DWSIM_textbook_companion/pdf/generate_pdf.inc
@@ -1,210 +1,10 @@
uid;
- $proposal_id = arg(3);
- $query2 = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status=1 AND proposal_id= :prop_id", array(
- ':prop_id' => $proposal_id
- ));
- $data2 = $query2->fetchObject();
- $query3 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id= :prop_id AND proposal_status =3", array(
- ':prop_id' => $proposal_id
- ));
- $data3 = $query3->fetchObject();
- if($data3){
- if($data3->uid != $x){
- drupal_set_message('Certificate is not available','error');
- return;
- }
- }
- $query4 = db_query("SELECT COUNT( tce.id ) AS example_count FROM textbook_companion_example tce
- LEFT JOIN textbook_companion_chapter tcc ON tce.chapter_id = tcc.id
- LEFT JOIN textbook_companion_preference tcpe ON tcc.preference_id = tcpe.id
- LEFT JOIN textbook_companion_proposal tcpo ON tcpe.proposal_id = tcpo.id
- WHERE tcpo.proposal_status =3 AND tce.approval_status =1 AND tce.approval_status=1 AND tcpo.id = :prop_id", array(
- ':prop_id' => $proposal_id
- ));
- $data4 = $query4->fetchObject();
- if($data4->example_count == 0) {
- drupal_set_message('Certificate is not available','error');
- return;
- }
- $number_of_example = $data4->example_count;
- $gender = array(
- 'salutation' => 'Mr. /Ms.',
- 'gender' => 'He/She'
- );
- if ($data3->gender) {
- if ($data3->gender == 'M') {
- $gender = array(
- 'salutation' => 'Mr.',
- 'gender' => 'He'
- );
- } //$data3->gender == 'M'
- else {
- $gender = array(
- 'salutation' => 'Ms.',
- 'gender' => 'She'
- );
- }
- } //$data3->gender
- $pdf = new FPDF('L', 'mm', 'Letter');
- if (!$pdf) {
- echo "Error!";
- } //!$pdf
- $pdf->AddPage();
- $image_bg = $mpath . "/pdf/images/bg.png";
- $pdf->Image($image_bg, 0, 0, $pdf->w, $pdf->h);
- //$pdf->Rect(5, 5, 267, 207, 'D');
- $pdf->SetMargins(18, 1, 18);
- //$pdf->Line(7.0, 7.0, 270.0, 7.0);
- //$pdf->Line(7.0, 7.0, 7.0, 210.0);
- //$pdf->Line(270.0, 210.0, 270.0, 7.0);
- //$pdf->Line(7.0, 210.0, 270.0, 210.0);
- $path = drupal_get_path('module', 'textbook_companion');
- $image1 = $mpath . "/pdf/images/dwsim_logo.png";
- $pdf->Ln(15);
- //$pdf->Cell(200, 8, $pdf->Image($image1, 105, 15, 0, 28), 0, 1, 'C');
- $pdf->Ln(20);
- $pdf->SetFont('Arial', 'BI', 25);
- $pdf->SetTextColor(139, 69, 19);
- $pdf->Cell(240, 8, 'Certificate of Participation', '0', 1, 'C');
- $pdf->Ln(4);
- $pdf->SetFont('Arial', 'BI', 12);
- $pdf->SetTextColor(0, 0, 0);
- $pdf->Cell(240, 8, 'This is to certify that', '0', '1', 'C');
- $pdf->Ln(4);
- $pdf->SetFont('Arial', 'BI', 25);
- $pdf->SetTextColor(139, 69, 19);
- $pdf->Cell(240, 8, $data3->full_name, '0', '1', 'C');
- $pdf->Ln(5);
- $pdf->SetFont('Arial', 'I', 12);
- if (strtolower($data3->branch) != "others") {
- $pdf->SetTextColor(0, 0, 0);
- //$pdf->Cell(240, 8, 'from ' . $data3->university . ' has successfully', '0', '1', 'C');
- $pdf->MultiCell(240, 8, 'from ' . $data3->university . ' has successfully', '0','C');
- $pdf->Ln(0);
- $pdf->Cell(240, 8, 'completed Internship under DWSIM Textbook Companion', '0', '1', 'C');
- $pdf->Ln(0);
- $pdf->Cell(240, 8, 'He/she has coded ' . $number_of_example . ' solved examples using DWSIM from the', '0', '1', 'C');
- $pdf->Ln(0);
- //$pdf->Cell(240, 8, 'Book: ' . $data2->book . ', Author: ' . $data2->author . '.', '0', '1', 'C');
- $pdf->MultiCell(240, 8, 'Book: ' . $data2->book . ', Author: ' . $data2->author . '.', '0','C');
- $pdf->Ln(0);
- } //strtolower($data3->branch) != "others"
- else {
- $pdf->SetTextColor(0, 0, 0);
- $pdf->Cell(240, 8, 'from ' . $data3->university . ' has successfully', '0', '1', 'C');
- $pdf->Ln(0);
- $pdf->Cell(240, 8, 'completed Internship under DWSIM Textbook Companion', '0', '1', 'C');
- $pdf->Ln(0);
- $pdf->Cell(240, 8, 'He/she has coded ' . $number_of_example . ' solved examples using DWSIM from the', '0', '1', 'C');
- $pdf->Ln(0);
- $pdf->Cell(240, 8, 'Book: ' . $data2->book . ', Author: ' . $data2->author . '.', '0', '1', 'C');
- $pdf->Ln(0);
- }
- $proposal_get_id = 0;
- $UniqueString = "";
- $tempDir = $path . "/pdf/temp_prcode/";
- $query = db_select('textbook_companion_qr_code');
- $query->fields('textbook_companion_qr_code');
- $query->condition('proposal_id', $proposal_id);
- $result = $query->execute();
- $data = $result->fetchObject();
- $DBString = $data->qr_code;
- $proposal_get_id = $data->proposal_id;
- if ($DBString == "" || $DBString == "null") {
- $UniqueString = generateRandomString();
- $query = "
- INSERT INTO textbook_companion_qr_code
- (proposal_id,qr_code)
- VALUES
- (:proposal_id,:qr_code)
- ";
- $args = array(
- ":proposal_id" => $proposal_id,
- ":qr_code" => $UniqueString
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- } //$DBString == "" || $DBString == "null"
- else {
- $UniqueString = $DBString;
- }
- $codeContents = "http://dwsim.fossee.in/textbook-companion/certificates/verify/" . $UniqueString;
- $fileName = 'generated_qrcode.png';
- $pngAbsoluteFilePath = $tempDir . $fileName;
- $urlRelativeFilePath = $path . "/pdf/temp_prcode/" . $fileName;
- QRcode::png($codeContents, $pngAbsoluteFilePath);
- $pdf->Cell(240, 4, '', '0', '1', 'C');
- $pdf->SetX(95);
- $pdf->write(0, 'The work done is available at ');
- $pdf->SetFont('', 'U');
- $pdf->SetTextColor(139, 69, 19);
- $pdf->write(0, 'http://dwsim.fossee.in/', 'http://dwsim.fossee.in/');
- $pdf->SetFont('', '');
- $pdf->SetTextColor(0, 0, 0);
- $pdf->write(0, '.', '.');
- $pdf->Ln(5);
- $pdf->SetX(198);
- $pdf->SetFont('', '');
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetY(-85);
- $pdf->SetX(200);
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('', '');
- $sign = $path . "/pdf/images/sign.png";
- $pdf->Image($sign, $pdf->GetX() - 20, $pdf->GetY(), 75, 0);
- /*$pdf->Cell(0, 8, 'Prof. Kannan M. Moudgalya', 0, 1, 'L');
- $pdf->SetX(199);
- $pdf->SetFont('Arial', '', 10);
- $pdf->Cell(0, 7, 'Co - Principal Investigator - FOSSEE', 0, 1, 'L');
- $pdf->SetX(190);
- $pdf->Cell(0, 7, ' Dept. of Chemical Engineering, IIT Bombay.', 0, 1, 'L');*/
- $pdf->SetX(29);
- $pdf->SetFont('Arial', 'B', 10);
- $pdf->SetY(-58);
- $pdf->SetX(28);
- $pdf->Cell(0, 2, $UniqueString, 0, 0, 'C');
- $pdf->SetX(29);
- $pdf->SetY(-50);
- $image4 = $path . "/pdf/images/verify_content.png";
- //$pdf->Image($image4, $pdf->GetX(), $pdf->GetY(), 20, 0);
- $pdf->SetY(-50);
- $pdf->SetX(80);
- $image3 = $path . "/pdf/images/mhrd.png";
- $image2 = $path . "/pdf/images/fossee.png";
- $pdf->Image($image2, $pdf->GetX() - 15, $pdf->GetY() + 7, 40, 0);
- $pdf->Image($pngAbsoluteFilePath, $pdf->GetX() + 50, $pdf->GetY() - 5, 30, 0);
- $pdf->Image($image3, $pdf->GetX() + 110, $pdf->GetY() + 3, 40, 0);
- $pdf->Image($image4, $pdf->GetX() - 15, $pdf->GetY() + 28, 150, 0);
- $pdf->SetFont('Arial', 'I', 8);
- $pdf->SetTextColor(0, 0, 0);
- $filename = str_replace(' ', '-', $data3->full_name) . '-DWSIM-Textbook-Certificate.pdf';
- $file = $path . '/pdf/temp_certificate/' . $proposal_id . '_' . $filename;
- $pdf->Output($file, 'F');
- header("Content-Type: application/octet-stream");
- header("Content-Disposition: attachment; filename=" . $filename);
- header("Content-Type: application/octet-stream");
- header("Content-Type: application/download");
- header("Content-Description: File Transfer");
- header("Content-Length: " . filesize($file));
- flush();
- $fp = fopen($file, "r");
- while (!feof($fp)) {
- echo fread($fp, 65536);
- flush();
- } //!feof($fp)
- fclose($fp);
- unlink($file);
- drupal_goto('certificate');
- return;
-}
+
+/**
+ * Removed: generate_pdf().
+ * Active: Drupal\textbook_companion\Form\GeneratePdf
+ */
+
function generateRandomString($length = 5)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
diff --git a/modules/custom/DWSIM_textbook_companion/src/Controller/DefaultController.php b/modules/custom/DWSIM_textbook_companion/src/Controller/DefaultController.php
index 124d919..a73d457 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Controller/DefaultController.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Controller/DefaultController.php
@@ -1,4 +1,6 @@
-uid) {
- drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error');
- drupal_goto('');
- return;
- } //!$user->uid
- /* check if user has already submitted a proposal */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- switch ($proposal_data->proposal_status) {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 1:
- drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error');
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status');
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data = $proposal_q->fetchObject()
- } //$proposal_q
- $book_proposal_form = drupal_get_form("book_proposal_form");
- $page_content .= drupal_render($book_proposal_form);
- // drupal_goto("aicte_proposal");
- return $page_content;
+ protected $database;
+ protected $messenger;
+ protected $currentUser;
+ protected $entityTypeManager;
+ protected $mailService;
+ protected $configFactory;
+ protected $formBuilder;
+ protected $globalService;
+ protected $requestStack;
+ protected $loggerFactory;
+ protected $fileSystem;
+
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ MailService $mail_service,
+ ConfigFactoryInterface $config_factory,
+ FormBuilderInterface $form_builder,
+ TextbookCompanionGlobalFunction $global_service,
+ RequestStack $request_stack,
+ LoggerChannelFactoryInterface $logger_factory,
+ FileSystemInterface $file_system
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->mailService = $mail_service;
+ $this->configFactory = $config_factory;
+ $this->formBuilder = $form_builder;
+ $this->globalService = $global_service;
+ $this->requestStack = $request_stack;
+ $this->loggerFactory = $logger_factory;
+ $this->fileSystem = $file_system;
}
- public function textbook_companion_aicte_proposal_all() {
- $user = \Drupal::currentUser();
- $page_content = "";
- if (!$user->uid) {
- /*$query = "
- SELECT * FROM textbook_companion_aicte
- WHERE status = 0
- ";
- $result = db_query($query);*/
- $query = db_select('textbook_companion_aicte');
- $query->fields('textbook_companion_aicte');
- $query->condition('status', 0);
- $result = $query->execute();
- $page_content .= "";
- $page_content .= "These are the list of books available for Textbook Companion proposal. ";
- $page_content .= "Please Login to create a proposal. ";
- //$page_content .= "Unable to propose particular book: Click here ";
- //$page_content .= "Do not wish to propose any of the below books: Click here ";
- $page_content .= " ";
- $page_content .= "Search : ";
- $page_content .= " ";
- $page_content .= "";
- $num_rows = $result->rowCount();
- if ($num_rows > 0) {
- $i = 1;
- while ($row = $result->fetchObject()) {
- /* fixing title string */
- $title = "";
- $edition = "";
- $year = "";
- $title = "{$row->book} by {$row->author}";
- if ($row->edition) {
- $edition = "
ed : {$row->edition}";
- } //$row->edition
- if ($row->year) {
- if ($row->edition) {
- $year = ",
pub : {$row->year}";
- } //$row->edition
- else {
- $year = "
pub : {$row->year}";
- }
- } //$row->year
- if ($edition or $year) {
- $title .= "({$edition} {$year})";
- } //$edition or $year
- $page_content .= "
{$i}) {$title}
";
- $i++;
- } //$row = $result->fetchObject()
- } //$num_rows > 0
- $page_content .= "
";
- /* adding aicte report form */
- //$page_content .= drupal_get_form("textbook_companion_aicte_report_form");
- return $page_content;
- } //!$user->uid
- /* check if user has already submitted a proposal */
- /* $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- switch ($proposal_data->proposal_status) {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 1:
- drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error');
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status');
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data = $proposal_q->fetchObject()
- } //$proposal_q
- variable_del("aicte_" . $user->uid);
- $page_content .= "* Please select any 3 books from the below list. ";
- //$page_content .= "Unable to propose particular book: Click here ";
- //$page_content .= "Do not wish to propose any of the below books: Click here ";
- $page_content .= "Search : ";
- $page_content .= " ";
- //$page_content .= drupal_get_form("textbook_companion_aicte_report_form");
- $textbook_companion_aicte_proposal_form = drupal_get_form("textbook_companion_aicte_proposal_form");
- $page_content .= drupal_render($textbook_companion_aicte_proposal_form);
- return $page_content;
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('textbook_companion.mail_service'),
+ $container->get('config.factory'),
+ $container->get('form_builder'),
+ $container->get('textbook_companion_global'),
+ $container->get('request_stack'),
+ $container->get('logger.factory'),
+ $container->get('file_system')
+ );
}
- public function _proposal_pending() {
- /* get pending proposals to be approved */
- $pending_rows = [];
- /*$pending_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 ORDER BY id DESC");*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('proposal_status', 0);
- $query->orderBy('id', 'DESC');
- $pending_q = $query->execute();
- while ($pending_data = $pending_q->fetchObject()) {
- $pending_rows[$pending_data->id] = [
- date('d-m-Y', $pending_data->creation_date),
- l($pending_data->full_name, 'user/' . $pending_data->uid),
- date('d-m-Y', $pending_data->proposed_completion_date),
- l('Approve', 'textbook-companion/manage-proposal/approve/' . $pending_data->id) . ' | ' . l('Edit', 'textbook-companion/manage-proposal/edit/' . $pending_data->id),
- ];
- } //$pending_data = $pending_q->fetchObject()
- /* check if there are any pending proposals */
- if (!$pending_rows) {
- drupal_set_message(t('There are no pending proposals.'), 'status');
- return '';
- } //!$pending_rows
- $pending_header = [
- 'Date of Submission',
- 'Contributor Name',
- 'Proposed Date of Completion',
- 'Action',
+ /**
+ * Helper: build a render array table from header and rows.
+ */
+ protected function buildTable(array $header, array $rows): array {
+ return [
+ '#type' => 'table',
+ '#header' => $header,
+ '#rows' => $rows,
+ '#empty' => $this->t('No records found.'),
];
- $output = theme('table', [
- 'header' => $pending_header,
- 'rows' => $pending_rows,
- ]);
- return $output;
}
- public function _proposal_all() {
- function _tbc_ext($status, $preference_id) {
- if ($status == "Approved") {
- //return " | " . l("ER", "tbc_external_review/add_book/" . $preference_id);
- return "";
- } //$status == "Approved"
- else {
- return "";
- }
+ /**
+ * Helper: get proposal status label.
+ */
+ protected function proposalStatusLabel(int $status): string {
+ return [
+ 0 => 'Pending',
+ 1 => 'Approved',
+ 2 => 'Dis-approved',
+ 3 => 'Completed',
+ 4 => 'External',
+ 5 => 'Submitted all codes',
+ ][$status] ?? 'Unknown';
+ }
+
+ /**
+ * Helper: load the latest proposal for the current user.
+ */
+ protected function loadLatestUserProposal() {
+ return $this->database->select('textbook_companion_proposal', 'p')
+ ->fields('p')
+ ->condition('uid', $this->currentUser->id())
+ ->orderBy('id', 'DESC')
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+ }
+
+ /**
+ * Helper: redirect to front page as a render array with a status message.
+ */
+ protected function redirectFrontRender(): RedirectResponse {
+ return new RedirectResponse(Url::fromRoute('')->toString());
+ }
+
+ public function textbook_companion_proposal_all() {
+ if (!$this->currentUser->isAuthenticated()) {
+ $this->messenger->addError($this->t('It is mandatory to login on this website to access the proposal form.'));
+ return $this->redirectFrontRender();
}
- /* get pending proposals to be approved */
- $proposal_rows = [];
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} ORDER BY id DESC");*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->orderBy('id', 'DESC');
- $proposal_q = $query->execute();
- while ($proposal_data = $proposal_q->fetchObject()) {
- /* get preference */
- /*$preference_q = db_query("SELECT * FROM textbook_companion_preference WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $preference_q = $query->execute();
- $preference_data = $preference_q->fetchObject();
- if (!$preference_data) {
- /* $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('pref_number', 1);
- //$query->condition('approval_status', 0);
- $query->range(0, 1);
- $preference_q = $query->execute();
- $preference_data = $preference_q->fetchObject();
- } //!$preference_data
- $proposal_status = '';
+ $proposal_data = $this->loadLatestUserProposal();
+ if ($proposal_data) {
+ $code_link = Link::fromTextAndUrl($this->t('Code Submission'), Url::fromRoute('textbook_companion.list_chapters'))->toString();
+ $proposal_link = Link::fromTextAndUrl($this->t('here'), Url::fromRoute('textbook_companion.proposal_all'))->toString();
switch ($proposal_data->proposal_status) {
case 0:
- $proposal_status = 'Pending';
- break;
+ $this->messenger->addStatus($this->t('We have already received your proposal. We will get back to you soon.'));
+ return $this->redirectFrontRender();
case 1:
- $proposal_status = 'Approved';
- break;
+ $this->messenger->addStatus($this->t('Your proposal has been approved. Please go to @link to upload your code.', ['@link' => $code_link]));
+ return $this->redirectFrontRender();
case 2:
- $proposal_status = 'Dis-approved';
+ $this->messenger->addError($this->t('Your proposal has been dis-approved. Please create another proposal below.'));
break;
case 3:
- $proposal_status = 'Completed';
+ $this->messenger->addStatus($this->t('Congratulations! You have completed your last book proposal. You can create another proposal below.'));
break;
- case 4:
- $proposal_status = 'External';
+ default:
+ $this->messenger->addError($this->t('Invalid proposal state. Please contact site administrator.'));
+ return $this->redirectFrontRender();
+ }
+ }
+ return $this->formBuilder->getForm('Drupal\textbook_companion\Form\TextbookCompanionProposalForm');
+ }
+
+ public function textbook_companion_aicte_proposal_all() {
+ if (!$this->currentUser->isAuthenticated()) {
+ // Anonymous: show list of available books.
+ $result = $this->database->select('textbook_companion_aicte', 'a')
+ ->fields('a')->condition('status', 0)->execute();
+ $items = [];
+ foreach ($result as $row) {
+ $edition = $row->edition ? 'ed : ' . $row->edition : '';
+ $year = $row->year ? ($edition ? ', ' : '') . 'pub : ' . $row->year : '';
+ $suffix = ($edition || $year) ? " ({$edition}{$year})" : '';
+ $items[] = $row->book . ' by ' . $row->author . $suffix;
+ }
+ return [
+ '#theme' => 'item_list',
+ '#items' => $items,
+ '#prefix' => '' . $this->t('Please Login to create a proposal.') . '
',
+ ];
+ }
+ $proposal_data = $this->loadLatestUserProposal();
+ if ($proposal_data) {
+ $code_link = Link::fromTextAndUrl($this->t('Code Submission'), Url::fromRoute('textbook_companion.list_chapters'))->toString();
+ switch ($proposal_data->proposal_status) {
+ case 0:
+ $this->messenger->addStatus($this->t('We have already received your proposal. We will get back to you soon.'));
+ return $this->redirectFrontRender();
+ case 1:
+ $this->messenger->addStatus($this->t('Your proposal has been approved. Please go to @link to upload your code.', ['@link' => $code_link]));
+ return $this->redirectFrontRender();
+ case 2:
+ $this->messenger->addError($this->t('Your proposal has been dis-approved. Please create another proposal below.'));
break;
- case 5:
- $proposal_status = 'Submitted all codes';
+ case 3:
+ $this->messenger->addStatus($this->t('Congratulations! You have completed your last book proposal. You can create another proposal below.'));
break;
default:
- $proposal_status = 'Unknown';
- break;
- } //$proposal_data->proposal_status
- if ($proposal_data->proposed_completion_date != 0) {
- $proposed_completion_date = date('d-m-Y', $proposal_data->proposed_completion_date);
- } //$proposal_data->proposed_completion_date != 0
- else {
- $proposed_completion_date = "-----";
+ $this->messenger->addError($this->t('Invalid proposal state. Please contact site administrator.'));
+ return $this->redirectFrontRender();
}
- $proposal_rows[] = [
- date('d-m-Y', $proposal_data->creation_date),
- "{$preference_data->book}
-by {$preference_data->author} ",
- l($proposal_data->full_name, 'user/' . $proposal_data->uid),
- date('d-m-Y', $proposal_data->completion_date),
- $proposed_completion_date,
- $proposal_status,
- l('Status', 'textbook-companion/manage-proposal/status/' . $proposal_data->id) . ' | ' . l('Edit', 'textbook-companion/manage-proposal/edit/' . $proposal_data->id) . _tbc_ext($proposal_status, $preference_data->id),
- ];
- } //$proposal_data = $proposal_q->fetchObject()
- /* check if there are any pending proposals */
- if (!$proposal_rows) {
- drupal_set_message(t('There are no proposals.'), 'status');
- return '';
- } //!$proposal_rows
- $proposal_header = [
- 'Date of Submission',
- 'Title of the Book',
- 'Contributor Name',
- 'Actual Date of Completion',
- 'Proposed Date of Completion',
- 'Status',
- 'Action',
+ }
+ return [
+ '#markup' => '* Please select any 3 books from the below list. ',
];
- $output = theme('table', [
- 'header' => $proposal_header,
- 'rows' => $proposal_rows,
- ]);
- return $output;
}
- public function _failed_all($preference_id = 0, $confirm = "") {
- $page_content = "";
- if ($preference_id && $confirm == "yes") {
- /*$query = "
- SELECT *, pro.id as proposal_id FROM textbook_companion_proposal pro
- LEFT JOIN textbook_companion_preference pre ON pre.proposal_id = pro.id
- LEFT JOIN users usr ON usr.uid = pro.uid
- WHERE pre.id = {$preference_id}
- ";
- $result = db_query($query);
- $row = db_fetch_object($result);*/
- $query = db_select('textbook_companion_proposal', 'pro');
- $query->fields('*', ['']);
- $query->fields('pro', ['id']);
- $query->leftJoin('textbook_companion_preference', 'pre', 'pre.proposal_id = pro.id');
- $query->leftJoin('users', 'usr', 'usr.uid = pro.uid');
- $query->condition('pre.id', '$preference_id');
- $result = $query->execute();
- $row = $result->fetchObject();
- /* increment failed_reminder */
- /*$query = "
- UPDATE textbook_companion_proposal
- SET failed_reminder = failed_reminder + 1
- WHERE id = {$row->proposal_id}
- ";
- db_query($query);*/
- $query = db_update('textbook_companion_proposal');
- $query->fields(['failed_reminder' => 'failed_reminder + 1']);
- $query->condition('id', '$row->proposal_id');
- $num_updated = $query->execute();
- /* sending mail */
- $to = $row->mail;
- $subject = "Failed to upload the TBC codes on time";
- $body = "
-
- Dear {$row->name},
- This is to inform you that you have failed to upload the TBC codes on time.
- Please note that the time you have taken is way past the deadline as well.
- Kindly upload the TBC codes on the interface within 5 days from now.
- Failure to submit the same will result in disapproval of your work and cancellation of your internship.
- Regards,
- DWSIM TBC Team,
- FOSSEE.
-
- ";
- $message = [
- "to" => $to,
- "subject" => $subject,
- "body" => $body,
- "headers" => [
- "From" => "contact-dwsim@fossee.in",
- "Bcc" => "contact-dwsim@fossee.in",
- "Content-Type" => "text/html; charset=UTF-8; format=flowed",
- ],
+ public function _proposal_pending() {
+ $rows = [];
+ $pending_q = $this->database->select('textbook_companion_proposal', 'p')
+ ->fields('p')->condition('proposal_status', 0)->orderBy('id', 'DESC')->execute();
+ while ($d = $pending_q->fetchObject()) {
+ $approve_url = Url::fromRoute('textbook_companion.proposal_approval_form', [], ['query' => ['proposal_id' => $d->id]]);
+ $edit_url = Url::fromRoute('textbook_companion.proposal_edit_form', [], ['query' => ['proposal_id' => $d->id]]);
+ $rows[] = [
+ date('d-m-Y', $d->creation_date),
+ Link::fromTextAndUrl($d->full_name, Url::fromRoute('entity.user.canonical', ['user' => $d->uid]))->toString(),
+ date('d-m-Y', $d->proposed_completion_date),
+ Link::fromTextAndUrl($this->t('Approve'), $approve_url)->toString() . ' | ' . Link::fromTextAndUrl($this->t('Edit'), $edit_url)->toString(),
];
- drupal_mail_send($message);
- drupal_set_message("Reminder sent successfully.");
- drupal_goto("textbook-companion/manage-proposal/failed");
- } //$preference_id && $confirm == "yes"
+ }
+ if (!$rows) {
+ $this->messenger->addStatus($this->t('There are no pending proposals.'));
+ return ['#markup' => ''];
+ }
+ return $this->buildTable(['Date of Submission', 'Contributor Name', 'Proposed Date of Completion', 'Action'], $rows);
+ }
+
+ public function _proposal_all() {
+ $rows = [];
+ $proposal_q = $this->database->select('textbook_companion_proposal', 'p')
+ ->fields('p')->orderBy('id', 'DESC')->execute();
+ while ($d = $proposal_q->fetchObject()) {
+ $pref = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('proposal_id', $d->id)->condition('approval_status', 1)->range(0, 1)->execute()->fetchObject();
+ if (!$pref) {
+ $pref = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('proposal_id', $d->id)->condition('pref_number', 1)->range(0, 1)->execute()->fetchObject();
+ }
+ $status_label = $this->proposalStatusLabel($d->proposal_status);
+ $proposed = $d->proposed_completion_date ? date('d-m-Y', $d->proposed_completion_date) : '-----';
+ $status_url = Url::fromRoute('textbook_companion.proposal_status_form', [], ['query' => ['proposal_id' => $d->id]]);
+ $edit_url = Url::fromRoute('textbook_companion.proposal_edit_form', [], ['query' => ['proposal_id' => $d->id]]);
+ $rows[] = [
+ date('d-m-Y', $d->creation_date),
+ ($pref ? $pref->book . 'by ' . $pref->author . ' ' : ''),
+ Link::fromTextAndUrl($d->full_name, Url::fromRoute('entity.user.canonical', ['user' => $d->uid]))->toString(),
+ date('d-m-Y', $d->completion_date),
+ $proposed,
+ $status_label,
+ Link::fromTextAndUrl($this->t('Status'), $status_url)->toString() . ' | ' . Link::fromTextAndUrl($this->t('Edit'), $edit_url)->toString(),
+ ];
+ }
+ if (!$rows) {
+ $this->messenger->addStatus($this->t('There are no proposals.'));
+ return ['#markup' => ''];
+ }
+ return $this->buildTable(['Date of Submission', 'Title of the Book', 'Contributor Name', 'Actual Date of Completion', 'Proposed Date of Completion', 'Status', 'Action'], $rows);
+ }
+
+ public function _failed_all($preference_id = 0, $confirm = '') {
+ $page_content = '';
+ if ($preference_id && $confirm === 'yes') {
+ $row = $this->database->select('textbook_companion_proposal', 'pro')
+ ->fields('pro')
+ ->leftJoin('textbook_companion_preference', 'pre', 'pre.proposal_id = pro.id');
+ // Rebuild as proper query object.
+ $q = $this->database->select('textbook_companion_preference', 'pre');
+ $q->fields('pre');
+ $q->leftJoin('textbook_companion_proposal', 'pro', 'pro.id = pre.proposal_id');
+ $q->condition('pre.id', $preference_id);
+ $row = $q->execute()->fetchObject();
+ if ($row) {
+ $this->database->update('textbook_companion_proposal')
+ ->expression('failed_reminder', 'failed_reminder + 1')
+ ->condition('id', $row->proposal_id ?? $row->id)
+ ->execute();
+ // Send reminder email via MailService.
+ $params['failed_reminder']['preference_id'] = $preference_id;
+ $this->mailService->sendMail('textbook_companion', 'failed_reminder', $row->mail ?? '', $params);
+ $this->messenger->addStatus($this->t('Reminder sent successfully.'));
+ }
+ return new RedirectResponse(Url::fromRoute('textbook_companion.failed_all')->toString());
+ }
+ if ($preference_id) {
+ $row = $this->database->select('textbook_companion_preference', 'pre')
+ ->fields('pre')
+ ->condition('pre.id', $preference_id)
+ ->execute()->fetchObject();
+ if ($row) {
+ $yes_url = Url::fromRoute('textbook_companion.failed_all', ['preference_id' => $preference_id, 'confirm' => 'yes']);
+ $cancel_url = Url::fromRoute('textbook_companion.failed_all');
+ $page_content .= '' . $this->t('Are you sure you want to notify?') . '
';
+ $page_content .= '' . $this->t('Book:') . ' ' . $row->book . ' ';
+ $page_content .= '' . $this->t('Author:') . ' ' . $row->author . ' ';
+ $page_content .= Link::fromTextAndUrl($this->t('Yes'), $yes_url)->toString() . ' | ' . Link::fromTextAndUrl($this->t('Cancel'), $cancel_url)->toString();
+ }
+ }
else {
- if ($preference_id) {
- /*$query = "
- SELECT * FROM textbook_companion_preference pre
- LEFT JOIN textbook_companion_proposal pro ON pro.id = pre.proposal_id
- WHERE pre.id = {$preference_id}
- ";
- $result = db_query($query);
- $row = db_fetch_object($result);*/
- $query = db_select('textbook_companion_preference', 'pre');
- $query->fields('pre');
- $query->leftJoin('textbook_companion_proposal', 'pro', 'pro.id = pre.proposal_id');
- $query->condition('pre.id', $preference_id);
- $result = $query->execute();
- $row = $result->fetchObject();
- $page_content .= "Are you sure you want to notify? ";
- $page_content .= "Book: {$row->book} ";
- $page_content .= "Author: {$row->author} ";
- $page_content .= "Contributor: {$row->full_name} ";
- $page_content .= "Expected Completion Date: " . date("d-m-Y", $row->completion_date) . " ";
- $page_content .= l("Yes", "textbook-companion/manage-proposal/failed/{$preference_id}/yes") . " | ";
- $page_content .= l("Cancel", "textbook-companion/manage-proposal/failed");
- } //$preference_id
- else {
- /*$query = "
- SELECT * FROM textbook_companion_proposal pro
- LEFT JOIN textbook_companion_preference pre ON pre.proposal_id = pro.id
- LEFT JOIN users usr ON usr.uid = pro.uid
- WHERE pro.proposal_status = 1 AND pre.approval_status = 1 AND pro.completion_date < %d
- ORDER BY failed_reminder
- ";
- $result = db_query($query, time());*/
- $query = db_select('textbook_companion_proposal', 'pro');
- $query->fields('pro');
- $query->leftJoin('textbook_companion_preference', 'pre', 'pre.proposal_id = pro.id');
- $query->leftJoin('users', 'usr', 'usr.uid = pro.uid');
- $query->condition('pro.proposal_status', 1);
- $query->condition('pre.approval_status', 1);
- $query->condition('pro.completion_date', '%time()', '<');
- $query->orderBy('failed_reminder', 'ASC');
- $result = $query->execute();
- $headers = [
- "Date of Submission",
- "Book",
- "Contributor Name",
- "Expected Completion Date",
- "Remainders",
- "Action",
+ $result = $this->database->select('textbook_companion_proposal', 'pro')
+ ->fields('pro')
+ ->condition('pro.proposal_status', 1)
+ ->condition('pro.completion_date', time(), '<')
+ ->orderBy('failed_reminder', 'ASC')
+ ->execute();
+ $rows = [];
+ foreach ($result as $row) {
+ $remind_url = Url::fromRoute('textbook_companion.failed_all', ['preference_id' => $row->id]);
+ $rows[] = [
+ date('d-m-Y', $row->creation_date),
+ $row->full_name,
+ date('d-m-Y', $row->completion_date),
+ $row->failed_reminder,
+ Link::fromTextAndUrl($this->t('Remind'), $remind_url)->toString(),
];
- $rows = [];
- while ($row = $result->fetchObject()) {
- $item = [
- date("d-m-Y", $row->creation_date),
- "{$row->book}by {$row->author}",
- $row->name,
- date("d-m-Y", $row->completion_date),
- $row->failed_reminder,
- l("Remind", "textbook-companion/manage-proposal/failed/{$row->id}"),
- ];
- array_push($rows, $item);
- } //$row = $result->fetchObject()
- $page_content .= theme('table', [
- 'header' => $headers,
- 'rows' => $rows,
- ]);
}
+ return $this->buildTable(['Date of Submission', 'Contributor Name', 'Expected Completion Date', 'Reminders', 'Action'], $rows);
}
- return $page_content;
+ return ['#markup' => $page_content];
}
public function code_approval() {
- /* get a list of unapproved chapters */
- $query = db_select('textbook_companion_example', 'e');
- $query->fields('c', [
- 'id',
- 'number',
- 'name',
- 'preference_id',
- ]);
- $query->addField('c', 'id', 'c_id');
- $query->addField('c', 'number', 'c_number');
- $query->addField('c', 'name', 'c_name');
- $query->addField('c', 'preference_id', 'c_preference_id');
- $query->innerJoin('textbook_companion_chapter', 'c', 'c.id = e.chapter_id');
- $query->condition('e.approval_status', 0);
- $pending_chapter_q = $query->execute();
- if (!$pending_chapter_q) {
- drupal_set_message(t('There are no pending code approvals.'), 'status');
- return '';
- } //!$pending_chapter_q
+ $pending_q = $this->database->select('textbook_companion_example', 'e')
+ ->fields('e', [])
+ ->condition('e.approval_status', 0)
+ ->execute();
+ // We need chapter fields too — use a join.
+ $q = $this->database->select('textbook_companion_example', 'e');
+ $q->addField('c', 'id', 'c_id');
+ $q->addField('c', 'number', 'c_number');
+ $q->addField('c', 'name', 'c_name');
+ $q->addField('c', 'preference_id', 'c_preference_id');
+ $q->innerJoin('textbook_companion_chapter', 'c', 'c.id = e.chapter_id');
+ $q->condition('e.approval_status', 0);
+ $results = $q->execute();
$rows = [];
- while ($row = $pending_chapter_q->fetchObject()) {
- /* get preference data */
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $row->c_preference_id);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- /* get proposal data */
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $preference_data->proposal_id);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- /* setting table row information */
+ foreach ($results as $row) {
+ $pref = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('id', $row->c_preference_id)->execute()->fetchObject();
+ $proposal = $pref ? $this->database->select('textbook_companion_proposal', 'pr')
+ ->fields('pr')->condition('id', $pref->proposal_id)->execute()->fetchObject() : NULL;
+ $edit_url = Url::fromRoute('textbook_companion.code_approval_form', [], ['query' => ['chapter_id' => $row->c_id]]);
$rows[] = [
- $preference_data->book,
+ $pref ? $pref->book : '',
$row->c_number,
$row->c_name,
- $proposal_data->full_name,
- l('Edit', 'textbook-companion/code-approval/approve/' . $row->c_id),
+ $proposal ? $proposal->full_name : '',
+ Link::fromTextAndUrl($this->t('Edit'), $edit_url)->toString(),
];
- } //$row = $pending_chapter_q->fetchObject()
- /* check if there are any pending proposals */
+ }
if (!$rows) {
- drupal_set_message(t('There are no pending proposals'), 'status');
- return '';
- } //!$rows
- $header = [
- 'Title of the Book',
- 'Chapter Number',
- 'Title of the Chapter',
- 'Contributor Name',
- 'Actions',
- ];
- $output = theme('table', [
- 'header' => $header,
- 'rows' => $rows,
- ]);
- return $output;
+ $this->messenger->addStatus($this->t('There are no pending code approvals.'));
+ return ['#markup' => ''];
+ }
+ return $this->buildTable(['Title of the Book', 'Chapter Number', 'Title of the Chapter', 'Contributor Name', 'Actions'], $rows);
}
public function list_chapters() {
- $user = \Drupal::currentUser();
- /************************ start approve book details ************************/
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
+ $proposal_data = $this->loadLatestUserProposal();
+ $proposal_link = Link::fromTextAndUrl($this->t('proposal'), Url::fromRoute('textbook_companion.proposal_all'))->toString();
if (!$proposal_data) {
- drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error');
- drupal_goto('');
- } //!$proposal_data
- if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) {
+ $this->messenger->addError($this->t('Please submit a @link.', ['@link' => $proposal_link]));
+ return $this->redirectFrontRender();
+ }
+ if (!in_array($proposal_data->proposal_status, [1, 4])) {
switch ($proposal_data->proposal_status) {
case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
+ $this->messenger->addStatus($this->t('We have already received your proposal. We will get back to you soon.'));
break;
case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error');
- drupal_goto('');
- return;
+ $this->messenger->addError($this->t('Your proposal has been dis-approved. Please create another proposal @link.', ['@link' => $proposal_link]));
break;
case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status');
- drupal_goto('');
- return;
+ $this->messenger->addStatus($this->t('Congratulations! You have completed your last book proposal. You can create another proposal @link.', ['@link' => $proposal_link]));
break;
default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4
-
-
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if ($preference_data->submited_all_examples_code == 1) {
- drupal_set_message(t('You have already submited your all codes for this book to review, hence you can not upload more code, for any query please write us.'), 'status');
- drupal_goto('');
- return;
- } //$preference_data->submited_all_examples_code == 1
+ $this->messenger->addError($this->t('Invalid proposal state. Please contact site administrator.'));
+ }
+ return $this->redirectFrontRender();
+ }
+ $preference_data = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('proposal_id', $proposal_data->id)->condition('approval_status', 1)->range(0, 1)->execute()->fetchObject();
if (!$preference_data) {
- drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
- /************************ end approve book details **************************/
- $return_html = ' ';
- $return_html .= 'Title of the Book: ' . $preference_data->book . ' ';
- $return_html .= 'Contributor Name: ' . $proposal_data->full_name . ' ';
- $return_html .= l('Upload Example Code', 'textbook-companion/code/upload') . ' ';
- /* get chapter list */
+ $this->messenger->addError($this->t('Invalid Book Preference status. Please contact site administrator.'));
+ return $this->redirectFrontRender();
+ }
+ if ($preference_data->submited_all_examples_code == 1) {
+ $this->messenger->addStatus($this->t('You have already submitted all codes for this book for review. You cannot upload more code.'));
+ return $this->redirectFrontRender();
+ }
+ $upload_url = Url::fromRoute('textbook_companion.upload_examples');
+ $build = [
+ '#markup' => '' . $this->t('Title of the Book:') . ' ' . $preference_data->book
+ . '' . $this->t('Contributor Name:') . ' ' . $proposal_data->full_name
+ . ' ' . Link::fromTextAndUrl($this->t('Upload Example Code'), $upload_url)->toString() . ' ',
+ ];
$chapter_rows = [];
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number ASC", $preference_data->id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $preference_data->id);
- $query->orderBy('number', 'ASC');
- $chapter_q = $query->execute();
+ $chapter_q = $this->database->select('textbook_companion_chapter', 'c')
+ ->fields('c')->condition('preference_id', $preference_data->id)->orderBy('number', 'ASC')->execute();
while ($chapter_data = $chapter_q->fetchObject()) {
- /* get example list */
- /* $example_q = db_query("SELECT count(*) as example_count FROM {textbook_companion_example} WHERE chapter_id = %d", $chapter_data->id);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->addExpression('count(*)', 'example_count');
- $query->condition('chapter_id', $chapter_data->id);
- $result = $query->execute();
- $example_data = $result->fetchObject();
+ $example_count = $this->database->select('textbook_companion_example', 'e')
+ ->condition('chapter_id', $chapter_data->id)->countQuery()->execute()->fetchField();
+ $edit_url = Url::fromRoute('textbook_companion.edit_chapter_title_form', [], ['query' => ['chapter_id' => $chapter_data->id]]);
+ $view_url = Url::fromRoute('textbook_companion.list_examples', ['chapter_id' => $chapter_data->id]);
$chapter_rows[] = [
$chapter_data->number,
- $chapter_data->name . ' (' . l('Edit', 'textbook-companion/code/chapter/edit/' . $chapter_data->id) . ')',
- $example_data->example_count,
- l('View', 'textbook-companion/code/list-examples/' . $chapter_data->id),
+ $chapter_data->name . ' (' . Link::fromTextAndUrl($this->t('Edit'), $edit_url)->toString() . ')',
+ $example_count,
+ Link::fromTextAndUrl($this->t('View'), $view_url)->toString(),
];
- } //$chapter_data = $chapter_q->fetchObject()
- /* check if there are any chapters */
+ }
if (!$chapter_rows) {
- drupal_set_message(t('No uploads found.'), 'status');
- return $return_html;
- } //!$chapter_rows
- $chapter_header = [
- 'Chapter No.',
- 'Title of the Chapter',
- 'Uploaded Examples',
- 'Actions',
- ];
- $return_html .= theme('table', [
- 'header' => $chapter_header,
- 'rows' => $chapter_rows,
- ]);
- $submited_all_example = drupal_get_form("all_example_submitted_check_form", $preference_data->id);
- $return_html .= drupal_render($submited_all_example);
- return $return_html;
+ $this->messenger->addStatus($this->t('No uploads found.'));
+ return $build;
+ }
+ $build['table'] = $this->buildTable(['Chapter No.', 'Title of the Chapter', 'Uploaded Examples', 'Actions'], $chapter_rows);
+ return $build;
}
public function upload_examples() {
- return drupal_get_form('upload_examples_form');
+ return $this->formBuilder->getForm('Drupal\textbook_companion\Form\UploadExamplesForm');
}
- public function _upload_examples_delete() {
- $user = \Drupal::currentUser();
- $root_path = textbook_companion_path();
- $example_id = arg(3);
- //var_dump($example_id);die;
- /* check example */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $example_id);
- $query->range(0, 1);
- $result = $query->execute();
- $example_data = $result->fetchObject();
+ public function _upload_examples_delete($example_id = NULL) {
+ if (!$example_id) {
+ $example_id = $this->requestStack->getCurrentRequest()->query->get('example_id');
+ }
+ $uid = $this->currentUser->id();
+ $root_path = $this->globalService->textbook_companion_path();
+
+ $example_data = $this->database->select('textbook_companion_example', 'e')
+ ->fields('e')->condition('id', $example_id)->range(0, 1)->execute()->fetchObject();
if (!$example_data) {
- drupal_set_message('Invalid example.', 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //!$example_data
+ $this->messenger->addError($this->t('Invalid example.'));
+ return $this->redirect('textbook_companion.list_chapters');
+ }
if ($example_data->approval_status != 0) {
- drupal_set_message('You cannnot delete an example after it has been approved. Please contact site administrator if you want to delete this example.', 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //$example_data->approval_status != 0
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d LIMIT 1", $example_data->chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $query->range(0, 1);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- if (!$chapter_data) {
- drupal_set_message('You do not have permission to delete this example.', 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //!$chapter_data
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d LIMIT 1", $chapter_data->preference_id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if (!$preference_data) {
- drupal_set_message('You do not have permission to delete this example.', 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //!$preference_data
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d AND uid = %d LIMIT 1", $preference_data->proposal_id, $user->uid);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $preference_data->proposal_id);
- $query->condition('uid', $user->uid);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
+ $this->messenger->addError($this->t('You cannot delete an approved example. Please contact site administrator.'));
+ return $this->redirect('textbook_companion.list_chapters');
+ }
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'c')
+ ->fields('c')->condition('id', $example_data->chapter_id)->range(0, 1)->execute()->fetchObject();
+ $preference_data = $chapter_data ? $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('id', $chapter_data->preference_id)->range(0, 1)->execute()->fetchObject() : NULL;
+ $proposal_data = $preference_data ? $this->database->select('textbook_companion_proposal', 'pr')
+ ->fields('pr')->condition('id', $preference_data->proposal_id)->condition('uid', $uid)->range(0, 1)->execute()->fetchObject() : NULL;
if (!$proposal_data) {
- drupal_set_message('You do not have permission to delete this example.', 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //!$proposal_data
- /* deleting example files */
- if (delete_example($example_data->id)) {
- drupal_set_message('Example deleted.', 'status');
- /* sending email */
- $email_to = $user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
+ $this->messenger->addError($this->t('You do not have permission to delete this example.'));
+ return $this->redirect('textbook_companion.list_chapters');
+ }
+ if (function_exists('delete_example') && delete_example($example_data->id)) {
+ $this->messenger->addStatus($this->t('Example deleted.'));
$params['example_deleted_user']['book_title'] = $preference_data->book;
$params['example_deleted_user']['chapter_title'] = $chapter_data->name;
$params['example_deleted_user']['example_number'] = $example_data->number;
- $params['example_deleted_user']['example_caption'] = $example_data->caption;
- $params['example_deleted_user']['user_id'] = $user->uid;
- $params['example_deleted_user']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'example_deleted_user', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ $params['example_deleted_user']['user_id'] = $uid;
+ $email_to = $this->currentUser->getEmail();
+ if (!$this->mailService->sendMail('textbook_companion', 'example_deleted_user', $email_to, $params)) {
+ $this->messenger->addError($this->t('Error sending email message.'));
}
- } //delete_example($example_data->id)
+ }
else {
- drupal_set_message('Error deleting example.', 'status');
+ $this->messenger->addError($this->t('Error deleting example.'));
}
- drupal_goto('textbook-companion/code');
- return;
+ return $this->redirect('textbook_companion.list_chapters');
}
- public function list_examples() {
- $user = \Drupal::currentUser();
- /************************ start approve book details ************************/
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
+ public function list_examples($chapter_id = NULL) {
+ if (!$chapter_id) {
+ $chapter_id = $this->requestStack->getCurrentRequest()->query->get('chapter_id');
+ }
+ $proposal_data = $this->loadLatestUserProposal();
+ $proposal_link = Link::fromTextAndUrl($this->t('proposal'), Url::fromRoute('textbook_companion.proposal_all'))->toString();
if (!$proposal_data) {
- drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error');
- drupal_goto('');
- } //!$proposal_data
- if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) {
- switch ($proposal_data->proposal_status) {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error');
- drupal_goto('');
- return;
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status');
- drupal_goto('');
- return;
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
+ $this->messenger->addError($this->t('Please submit a @link.', ['@link' => $proposal_link]));
+ return $this->redirectFrontRender();
+ }
+ if (!in_array($proposal_data->proposal_status, [1, 4])) {
+ $this->messenger->addError($this->t('Your proposal is not in an approved state.'));
+ return $this->redirectFrontRender();
+ }
+ $preference_data = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('proposal_id', $proposal_data->id)->condition('approval_status', 1)->range(0, 1)->execute()->fetchObject();
if (!$preference_data) {
- drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
- /************************ end approve book details **************************/
- /* get chapter details */
- $chapter_id = arg(3);
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d LIMIT 1", $chapter_id, $preference_data->id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $chapter_id);
- $query->condition('preference_id', $preference_data->id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if ($chapter_data = $chapter_q->fetchObject()) {
- $return_html = ' ';
- $return_html .= 'Title of the Book: ' . $preference_data->book . ' ';
- $return_html .= 'Contributor Name: ' . $proposal_data->full_name . ' ';
- $return_html .= 'Chapter Number: ' . $chapter_data->number . ' ';
- $return_html .= 'Title of the Chapter: ' . $chapter_data->name . ' ';
- } //$chapter_data = $chapter_q->fetchObject()
- else {
- drupal_set_message(t('Invalid chapter.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
+ $this->messenger->addError($this->t('Invalid Book Preference status. Please contact site administrator.'));
+ return $this->redirectFrontRender();
+ }
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'c')
+ ->fields('c')->condition('id', $chapter_id)->condition('preference_id', $preference_data->id)->range(0, 1)->execute()->fetchObject();
+ if (!$chapter_data) {
+ $this->messenger->addError($this->t('Invalid chapter.'));
+ return $this->redirect('textbook_companion.list_chapters');
}
- $return_html .= ' ' . l('Back to Chapter List', 'textbook-companion/code');
- /* get example list */
+ $back_url = Url::fromRoute('textbook_companion.list_chapters');
+ $build = [
+ '#markup' => '' . $this->t('Title of the Book:') . ' ' . $preference_data->book
+ . '' . $this->t('Contributor Name:') . ' ' . $proposal_data->full_name
+ . '' . $this->t('Chapter Number:') . ' ' . $chapter_data->number
+ . '' . $this->t('Title of the Chapter:') . ' ' . $chapter_data->name
+ . ' ' . Link::fromTextAndUrl($this->t('Back to Chapter List'), $back_url)->toString(),
+ ];
$example_rows = [];
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_id);
- $example_q = $query->execute();
+ $example_q = $this->database->select('textbook_companion_example', 'e')
+ ->fields('e')->condition('chapter_id', $chapter_id)->execute();
while ($example_data = $example_q->fetchObject()) {
- /* approval status */
- $approval_status = '';
- switch ($example_data->approval_status) {
- case 0:
- $approval_status = 'Pending';
- break;
- case 1:
- $approval_status = 'Approved';
- break;
- case 2:
- $approval_status = 'Rejected';
- break;
- } //$example_data->approval_status
- /* example files */
+ $status_map = [0 => 'Pending', 1 => 'Approved', 2 => 'Rejected'];
+ $approval_label = $status_map[$example_data->approval_status] ?? '';
$example_files = '';
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d ORDER BY filetype", $example_data->id);*/
- $query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_data->id);
- $query->orderBy('filetype', 'ASC');
- $example_files_q = $query->execute();
- while ($example_files_data = $example_files_q->fetchObject()) {
- $file_type = '';
- switch ($example_files_data->filetype) {
- case 'S':
- $file_type = 'Main or Source';
- break;
- case 'R':
- $file_type = 'Result';
- break;
- case 'X':
- $file_type = 'xcos';
- break;
- default:
- } //$example_files_data->filetype
- $example_files .= l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id) . ' (' . $file_type . ') ';
- } //$example_files_data = $example_files_q->fetchObject()
+ $files_q = $this->database->select('textbook_companion_example_files', 'f')
+ ->fields('f')->condition('example_id', $example_data->id)->orderBy('filetype', 'ASC')->execute();
+ while ($file = $files_q->fetchObject()) {
+ $type_map = ['S' => 'Main or Source', 'R' => 'Result', 'X' => 'xcos'];
+ $file_type = $type_map[$file->filetype] ?? '';
+ $dl_url = Url::fromRoute('textbook_companion.download_example_file', ['example_file_id' => $file->id]);
+ $example_files .= Link::fromTextAndUrl($file->filename, $dl_url)->toString() . ' (' . $file_type . ') ';
+ }
if ($example_data->approval_status == 0) {
- $example_rows[] = [
- 'data' => [
- $example_data->number,
- $example_data->caption,
- $approval_status,
- $example_files,
- l('Edit', 'textbook-companion/code/edit/' . $example_data->id) . ' | ' . l('Delete', 'textbook-companion/code/delete/' . $example_data->id, [
- 'attributes' => [
- 'onClick' => 'return confirm("Are you sure you want to delete the example?")'
- ]
- ]),
- ],
- 'valign' => 'top',
- ];
- } //$example_data->approval_status == 0
+ $edit_url = Url::fromRoute('textbook_companion.upload_examples_admin_edit_form', [], ['query' => ['example_id' => $example_data->id]]);
+ $del_url = Url::fromRoute('textbook_companion.upload_examples_delete', ['example_id' => $example_data->id]);
+ $actions = Link::fromTextAndUrl($this->t('Edit'), $edit_url)->toString() . ' | ' . Link::fromTextAndUrl($this->t('Delete'), $del_url)->toString();
+ }
else {
- $example_rows[] = [
- 'data' => [
- $example_data->number,
- $example_data->caption,
- $approval_status,
- $example_files,
- l('Download', 'textbook-companion/download/example/' . $example_data->id),
- ],
- 'valign' => 'top',
- ];
+ $dl_url = Url::fromRoute('textbook_companion.download_example', ['example_id' => $example_data->id]);
+ $actions = Link::fromTextAndUrl($this->t('Download'), $dl_url)->toString();
}
- } //$example_data = $example_q->fetchObject()
- $example_header = [
- 'Example No.',
- 'Caption',
- 'Status',
- 'Files',
- 'Action',
- ];
- $return_html .= theme('table', [
- 'header' => $example_header,
- 'rows' => $example_rows,
- ]);
-
- return $return_html;
+ $example_rows[] = [
+ 'data' => [$example_data->number, $example_data->caption, $approval_label, $example_files, $actions],
+ 'valign' => 'top',
+ ];
+ }
+ $build['table'] = $this->buildTable(['Example No.', 'Caption', 'Status', 'Files', 'Action'], $example_rows);
+ return $build;
}
- public function textbook_companion_browse_book() {
- $return_html = _browse_list('book');
- $return_html .= ' ';
- $query_character = arg(2);
+ public function textbook_companion_browse_book($character = NULL) {
+ $query_character = $character;
+ $build = [
+ 'browse_list' => $this->browseList('book'),
+ 'spacing' => [
+ '#markup' => ' ',
+ ],
+ ];
if (!$query_character) {
- /* all books */
- $return_html .= "Please select the starting character of the title of the book";
- return $return_html;
- }
- $book_rows = [];
- /*$book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE book like '%s%%' AND approval_status = 1", $query_character);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('book', '' . $query_character . '%%', 'like');
- $query->condition('approval_status', 1);
- $book_q = $query->execute();
- while ($book_data = $book_q->fetchObject()) {
- $book_rows[] = [
- l($book_data->book, 'textbook_run/' . $book_data->id),
- $book_data->author,
+ $build['message'] = [
+ '#markup' => $this->t('Please select the starting character of the title of the book.'),
];
+ return $build;
}
- if (!$book_rows) {
- $return_html .= "Sorry no books are available with that title";
+ $book_q = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')
+ ->condition('book', $query_character . '%', 'LIKE')
+ ->condition('approval_status', 1)
+ ->execute();
+ $rows = [];
+ foreach ($book_q as $d) {
+ $url = Url::fromRoute('textbook_companion.run_form', ['book_pref_id' => $d->id]);
+ $rows[] = [Link::fromTextAndUrl($d->book, $url)->toString(), $d->author];
}
- else {
- $book_header = [
- 'Title of the Book',
- 'Author Name',
+ if (!$rows) {
+ $build['message'] = [
+ '#markup' => $this->t('Sorry, no books are available with that title.'),
];
- $return_html .= theme('table', [
- 'headers' => $book_header,
- 'rows' => $book_rows,
- ]);
+ return $build;
}
- return $return_html;
+ $build['table'] = $this->buildTable(['Title of the Book', 'Author Name'], $rows);
+ return $build;
}
- public function textbook_companion_browse_author() {
- $return_html = _browse_list('author');
- $return_html .= ' ';
- $query_character = arg(2);
+ public function textbook_companion_browse_author($character = NULL) {
+ $query_character = $character;
+
+ $build = [
+ 'browse_list' => $this->browseList('author'),
+ 'spacing' => [
+ '#markup' => ' ',
+ ],
+ ];
+
if (!$query_character) {
- /* all books */
- $return_html .= "Please select the starting character of the author's name";
- return $return_html;
+ $build['message'] = [
+ '#markup' => $this->t("Please select the starting character of the author's name"),
+ ];
+ return $build;
}
+
$book_rows = [];
- /*$book_q = db_query("SELECT pe.book as book, pe.author as author, pe.publisher as publisher, pe.year as year, pe.id as id FROM {textbook_companion_preference} pe RIGHT JOIN {textbook_companion_proposal} po on pe.proposal_id=po.id WHERE po.proposal_status=3 and pe.approval_status = 1", $query_character);*/
- $query = db_select('textbook_companion_preference', 'pe');
- $query->fields('pe', [
- 'book',
- 'author',
- 'publisher',
- 'year',
- 'id',
- ]);
+ $query = $this->database->select('textbook_companion_preference', 'pe');
+ $query->fields('pe', ['book', 'author', 'publisher', 'year', 'id']);
$query->rightJoin('textbook_companion_proposal', 'po', 'pe.proposal_id = po.id');
$query->condition('po.proposal_status', 3);
$query->condition('pe.approval_status', 1);
$book_q = $query->execute();
+
while ($book_data = $book_q->fetchObject()) {
- /* Initial's fix algorithm */
- preg_match_all("/{$query_character}[a-z]+/", $book_data->author, $matches);
+ preg_match_all("/" . preg_quote($query_character, '/') . "[a-z]+/i", $book_data->author, $matches);
if (count($matches) > 0) {
- /* Remove the word "And"/i from the match array and make match bold */
if (count($matches[0]) > 0) {
foreach ($matches[0] as $key => $value) {
if (strtolower($value) == "and") {
unset($matches[$key]);
- }
- else {
+ } else {
$matches[0][$key] = "" . $value . " ";
$book_data->author = str_replace($value, $matches[0][$key], $book_data->author);
}
}
}
- /* Check count of matches after removing And */
if (count($matches[0]) > 0) {
$book_rows[] = [
- l($book_data->book, 'textbook_run/' . $book_data->id),
- $book_data->author,
+ Link::fromTextAndUrl($book_data->book, Url::fromRoute('textbook_companion.run_form', ['book_pref_id' => $book_data->id]))->toString(),
+ [
+ 'data' => [
+ '#markup' => $book_data->author,
+ ],
+ ],
];
}
}
}
+
if (!$book_rows) {
- $return_html .= "Sorry no books are available with that author's name";
- }
- else {
- $book_header = [
- 'Title of the Book',
- 'Author Name',
+ $build['message'] = [
+ '#markup' => $this->t("Sorry no books are available with that author's name"),
];
- $return_html .= theme('table', [
- 'headers' => $book_header,
- 'rows' => $book_rows,
- ]);
+ } else {
+ $build['table'] = $this->buildTable(['Title of the Book', 'Author Name'], $book_rows);
}
- return $return_html;
+
+ return $build;
}
- public function textbook_companion_browse_student() {
- $return_html = _browse_list('student');
- $return_html .= ' ';
- $query_character = arg(2);
- //print $query_character;
- //die();
+ public function textbook_companion_browse_student($character = NULL) {
+ $query_character = $character;
+
+ $build = [
+ 'browse_list' => $this->browseList('student'),
+ 'spacing' => [
+ '#markup' => ' ',
+ ],
+ ];
+
if (!$query_character) {
- /* all books */
- $return_html .= "Please select the starting character of the student's name";
- return $return_html;
+ $build['message'] = [
+ '#markup' => $this->t("Please select the starting character of the student's name"),
+ ];
+ return $build;
}
+
$book_rows = [];
- /*$student_q = db_query("
- SELECT po.full_name, pe.book as book, pe.author as author, pe.publisher as publisher, pe.year as year, pe.id as pe_id, po.approval_date as approval_date
- FROM textbook_companion_preference pe LEFT JOIN textbook_companion_proposal po ON pe.proposal_id = po.id
- WHERE po.proposal_status = 3 AND pe.approval_status = 1 AND full_name LIKE '%s%%'
- ", $query_character);*/
- $query = db_select('textbook_companion_preference', 'pe');
- $query->fields('po', [
- 'full_name',
- 'approval_date',
- ]);
- $query->fields('pe', [
- 'book',
- 'author',
- 'publisher',
- 'year',
- 'id',
- ]);
+ $query = $this->database->select('textbook_companion_preference', 'pe');
+ $query->fields('po', ['full_name', 'approval_date']);
+ $query->fields('pe', ['book', 'author', 'publisher', 'year', 'id']);
$query->leftJoin('textbook_companion_proposal', 'po', 'pe.proposal_id = po.id');
$query->condition('po.proposal_status', 3);
$query->condition('pe.approval_status', 1);
- $query->condition('full_name', '' . $query_character . '%%', 'LIKE');
+ $query->condition('full_name', $query_character . '%', 'LIKE');
$student_q = $query->execute();
+
while ($student_data = $student_q->fetchObject()) {
$book_rows[] = [
- l($student_data->book, 'textbook_run/' . $student_data->pe_id),
+ Link::fromTextAndUrl($student_data->book, Url::fromRoute('textbook_companion.run_form', ['book_pref_id' => $student_data->id]))->toString(),
$student_data->full_name,
];
}
+
if (!$book_rows) {
- $return_html .= "Sorry no books are available with that student's name";
- }
- else {
- $book_header = [
- 'Title of the Book',
- 'Student Name',
+ $build['message'] = [
+ '#markup' => $this->t("Sorry no books are available with that student's name"),
];
- $return_html .= theme('table', [
- 'headers' => $book_header,
- 'rows' => $book_rows,
- ]);
+ } else {
+ $build['table'] = $this->buildTable(['Title of the Book', 'Student Name'], $book_rows);
+ }
+
+ return $build;
+ }
+
+ protected function browseList(string $type): array {
+ $links = [];
+ $char_list = range('A', 'Z');
+ foreach ($char_list as $char) {
+ $url = Url::fromRoute('textbook_companion.browse_' . $type, ['character' => $char]);
+ $links[] = Link::fromTextAndUrl($char, $url)->toString();
}
- return $return_html;
+ return [
+ '#markup' => '' . implode(' | ', $links) . '
',
+ ];
}
// public function textbook_companion_download_example_file() {
@@ -1068,43 +709,21 @@ public function textbook_companion_browse_student() {
// readfile($root_path . $example_file_data->directory_name . '/' . $example_file_data->filepath);
// }
public function textbook_companion_download_example_file($example_file_id) {
- // Get the example file ID from the route.
- $example_file_id = \Drupal::routeMatch()->getParameter('example_file_id');
-
if (empty($example_file_id)) {
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
}
- // Get root path (assuming this function exists in your module).
- $root_path =\Drupal::service("textbook_companion_global")->textbook_companion_path();
-
- // Database query using Drupal 10 Database API.
- // $connection = \Drupal::database();
- // $query = $connection->select('textbook_companion_preference', 'tcp')
- // ->join('textbook_companion_chapter', 'tcc', 'tcp.id = tcc.preference_id')
- // ->join('textbook_companion_example', 'tce', 'tcc.id = tce.chapter_id')
- // ->join('textbook_companion_example_files', 'tcef', 'tce.id = tcef.example_id')
- // ->fields('tcef')
-
- // ->condition('tcef.id', $example_file_id)
- // ->range(0, 1);
-
- $connection = \Drupal::database();
-
-$query = $connection->select('textbook_companion_preference', 'tcp');
-$query->join('textbook_companion_chapter', 'tcc', 'tcp.id = tcc.preference_id');
-$query->join('textbook_companion_example', 'tce', 'tcc.id = tce.chapter_id');
-$query->join('textbook_companion_example_files', 'tcef', 'tce.id = tcef.example_id');
-
-// Fetch both file info and directory name
-$query->fields('tcef');
-$query->addField('tcp', 'directory_name', 'directory_name');
+ // Get root path via injected global service.
+ $root_path = $this->globalService->textbook_companion_path();
-$query->condition('tcef.id', $example_file_id);
-$query->range(0, 1);
-
-
-// Execute.
+ $query = $this->database->select('textbook_companion_preference', 'tcp');
+ $query->join('textbook_companion_chapter', 'tcc', 'tcp.id = tcc.preference_id');
+ $query->join('textbook_companion_example', 'tce', 'tcc.id = tce.chapter_id');
+ $query->join('textbook_companion_example_files', 'tcef', 'tce.id = tcef.example_id');
+ $query->fields('tcef');
+ $query->addField('tcp', 'directory_name', 'directory_name');
+ $query->condition('tcef.id', $example_file_id);
+ $query->range(0, 1);
$example_file_data = $query->execute()->fetchObject();
@@ -1112,15 +731,12 @@ public function textbook_companion_download_example_file($example_file_id) {
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
}
- // Build full file path.
$file_path = $root_path . $example_file_data->directory_name . '/' . $example_file_data->filepath;
- // var_dump( $example_file_data->directory_name);die;
if (!file_exists($file_path)) {
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('File not found.');
}
- // Prepare response using Symfony's BinaryFileResponse.
$response = new BinaryFileResponse($file_path);
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
@@ -1132,23 +748,31 @@ public function textbook_companion_download_example_file($example_file_id) {
return $response;
}
-
-
- public function textbook_companion_download_sample_code() {
- $proposal_id = arg(3);
- $root_path = textbook_companion_samplecode_path();
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $proposal_id);
- $query->range(0, 1);
- $result = $query->execute();
- $example_file_data = $result->fetchObject();
+ public function textbook_companion_download_sample_code($proposal_id = NULL) {
+ if (!$proposal_id) {
+ $proposal_id = $this->requestStack->getCurrentRequest()->query->get('proposal_id');
+ }
+ $root_path = $this->globalService->textbook_companion_samplecode_path();
+ $example_file_data = $this->database->select('textbook_companion_proposal')
+ ->fields('textbook_companion_proposal')
+ ->condition('id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+ if (!$example_file_data || empty($example_file_data->samplefilepath)) {
+ throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('Sample code file not found.');
+ }
+ $file_path = $root_path . $example_file_data->samplefilepath;
+ if (!file_exists($file_path)) {
+ throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('File does not exist.');
+ }
$samplecodename = substr($example_file_data->samplefilepath, strrpos($example_file_data->samplefilepath, '/') + 1);
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . $samplecodename . '"');
- header('Content-Length: ' . filesize($root_path . $example_file_data->samplefilepath));
- ob_clean();
- readfile($root_path . $example_file_data->samplefilepath);
+ $response = new BinaryFileResponse($file_path);
+ $response->setContentDisposition(
+ ResponseHeaderBag::DISPOSITION_ATTACHMENT,
+ $samplecodename
+ );
+ return $response;
}
// public function textbook_companion_download_example() {
@@ -1325,22 +949,19 @@ public function textbook_companion_download_sample_code() {
public function textbook_companion_download_chapter() {
- // Get chapter id from route
- $route_match = \Drupal::routeMatch();
- $chapter_id = (int) $route_match->getParameter('chapter_id');
+ // Get chapter id from route.
+ $chapter_id = (int) $this->requestStack->getCurrentRequest()->attributes->get('chapter_id');
- // Get root path (ensure trailing slash)
- $root_path = \Drupal::service("textbook_companion_global")->textbook_companion_path();
- $root_path = rtrim($root_path, '/') . '/';
+ // Get root path via injected global service.
+ $root_path = rtrim($this->globalService->textbook_companion_path(), '/') . '/';
- // Fetch chapter data
- $query = \Drupal::database()->select('textbook_companion_chapter', 'tcc');
- $query->fields('tcc');
- $query->condition('id', $chapter_id);
- $chapter_data = $query->execute()->fetchObject();
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'tcc')
+ ->fields('tcc')
+ ->condition('id', $chapter_id)
+ ->execute()->fetchObject();
if (!$chapter_data) {
- \Drupal::messenger()->addError("Invalid chapter.");
+ $this->messenger->addError($this->t('Invalid chapter.'));
return $this->redirect('textbook_companion.run_form');
}
@@ -1361,7 +982,7 @@ public function textbook_companion_download_chapter() {
}
// Fetch approved examples
- $db = \Drupal::database();
+ $db = $this->database;
$example_q = $db->select('textbook_companion_example', 'tce')
->fields('tce')
->condition('chapter_id', $chapter_id)
@@ -1390,7 +1011,7 @@ public function textbook_companion_download_chapter() {
$zip->addFile($file_full_path, $CH_PATH . $EX_PATH . $example_files_row->filename);
}
else {
- \Drupal::logger('textbook_companion')->warning('Missing file: ' . $file_full_path);
+ $this->loggerFactory->get('textbook_companion')->warning('Missing file: ' . $file_full_path);
}
}
}
@@ -1400,7 +1021,7 @@ public function textbook_companion_download_chapter() {
if ($zip_file_count < 1) {
unlink($zip_filename);
- \Drupal::messenger()->addError("There are no examples in this chapter to download.");
+ $this->messenger->addError($this->t('There are no examples in this chapter to download.'));
return $this->redirect('textbook_companion.run_form');
}
@@ -1418,509 +1039,500 @@ public function textbook_companion_download_chapter() {
}
-
-public function textbook_companion_download_book() {
- // $book_id = arg(3);
- $route_match = \Drupal::routeMatch();
-
-$book_id = (int) $route_match->getParameter('book_id');
- /* get solution data */
- $root_path = \Drupal::service("textbook_companion_global")->textbook_companion_path();
- /* get example data */
- // var_dump($root_path);die;
- /*$book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id);
- $book_data = db_fetch_object($book_q);*/
- $query = \Drupal::database()->select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $book_id);
- $result = $query->execute();
- $book_data = $result->fetchObject();
- $zipname = str_replace(' ', '_', ($book_data->book));
+ public function textbook_companion_download_book($book_id = NULL) {
+ if (!$book_id) {
+ $book_id = (int) $this->requestStack->getCurrentRequest()->attributes->get('book_id');
+ }
+ $root_path = rtrim($this->globalService->textbook_companion_path(), '/') . '/';
+
+ $book_data = $this->database->select('textbook_companion_preference', 'tcp')
+ ->fields('tcp')
+ ->condition('id', $book_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$book_data) {
+ $this->messenger->addError($this->t('Invalid book preference ID.'));
+ return $this->redirect('textbook_companion.run_form');
+ }
+
+ $zipname = str_replace(' ', '_', $book_data->book);
$directory_name = $book_data->directory_name;
$BK_PATH = $zipname . '/';
-
- // var_dump($book_data);die;
- /* zip filename */
- $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
-
- // var_Dump($zip_filename);die;
- /* creating zip archive on the server */
- $zip = new \ZipArchive();
- $zip->open($zip_filename,\ZipArchive::CREATE);
-
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $book_id);*/
- $query = \Drupal::database()->select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $book_id);
- $chapter_q = $query->execute();
+
+ $temp_dir = $root_path . 'tbc_download_temp/';
+ if (!is_dir($temp_dir)) {
+ mkdir($temp_dir, 0777, TRUE);
+ }
+ $zip_filename = $temp_dir . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
+
+ $zip = new \ZipArchive();
+ if ($zip->open($zip_filename, \ZipArchive::CREATE) !== TRUE) {
+ $this->messenger->addError($this->t('Unable to create zip file.'));
+ return $this->redirect('textbook_companion.run_form', ['book_pref_id' => $book_id]);
+ }
+
+ $chapter_q = $this->database->select('textbook_companion_chapter', 'tcc')
+ ->fields('tcc')
+ ->condition('preference_id', $book_id)
+ ->execute();
+
+ $fs = $this->fileSystem;
+
while ($chapter_row = $chapter_q->fetchObject()) {
$CH_PATH = 'CH' . $chapter_row->number . '/';
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_row->id);*/
- $query = \Drupal::database()->select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_row->id);
- $query->condition('approval_status', 1);
- $example_q = $query->execute();
+
+ $example_q = $this->database->select('textbook_companion_example', 'tce')
+ ->fields('tce')
+ ->condition('chapter_id', $chapter_row->id)
+ ->condition('approval_status', 1)
+ ->execute();
+
while ($example_row = $example_q->fetchObject()) {
$EX_PATH = 'EX' . $example_row->number . '/';
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/
- $query = \Drupal::database()->select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_row->id);
- $example_files_q = $query->execute();
+
+ $example_files_q = $this->database->select('textbook_companion_example_files', 'tcef')
+ ->fields('tcef')
+ ->condition('example_id', $example_row->id)
+ ->execute();
+
while ($example_files_row = $example_files_q->fetchObject()) {
- // $zip->addFile($root_path . $directory_name . '/' . $example_files_row->filepath, $BK_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
-
- $fs = \Drupal::service('file_system');
-
-$full_path = $root_path . $directory_name . '/' . $example_files_row->filepath;
-
-// Convert to real filesystem path
-$real_path = $fs->realpath($full_path);
-
-// Debug: Check if file exists
-if (!file_exists($real_path)) {
- \Drupal::logger('tbc')->error('Missing file: ' . $real_path);
- continue;
-}
-
-// Add file to ZIP
-$zip->addFile(
- $real_path,
- $BK_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename
-);
-
+ $full_path = $root_path . $directory_name . '/' . $example_files_row->filepath;
+ $real_path = $fs->realpath($full_path);
+
+ if ($real_path && file_exists($real_path)) {
+ $zip->addFile($real_path, $BK_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
+ } else {
+ $this->loggerFactory->get('textbook_companion')->error('Missing file: ' . $full_path);
+ }
}
}
}
+
$zip_file_count = $zip->numFiles;
$zip->close();
+
if ($zip_file_count > 0) {
- /* download zip file */
- $user = \Drupal::currentUser();
- if ($user->uid) {
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . str_replace(' ', '_', ($book_data->book)) . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- ob_clean();
- readfile($zip_filename);
- unlink($zip_filename);
- }
- else {
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . str_replace(' ', '_', ($book_data->book)) . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- ob_end_flush();
- ob_clean();
- flush();
- readfile($zip_filename);
+ $response = new BinaryFileResponse($zip_filename);
+ $response->setContentDisposition(
+ ResponseHeaderBag::DISPOSITION_ATTACHMENT,
+ str_replace(' ', '_', $book_data->book) . '.zip'
+ );
+ $response->deleteFileAfterSend(TRUE);
+ return $response;
+ } else {
+ if (file_exists($zip_filename)) {
unlink($zip_filename);
}
- }
- else {
- \Drupal::messenger()->addMessage("There are no examples in this book to download", 'error');
- //drupal_goto('textbook-companion/textbook-run');
-return $this->redirect('textbook_companion.run_form', ['book_pref_id' => $book_id]);
-
-
+ $this->messenger->addError($this->t('There are no examples in this book to download.'));
+ return $this->redirect('textbook_companion.run_form', ['book_pref_id' => $book_id]);
}
}
- public function textbook_companion_download_full_chapter() {
- $chapter_id = arg(3);
- $root_path = textbook_companion_path();
+ public function textbook_companion_download_full_chapter($chapter_id = NULL) {
+ if (!$chapter_id) {
+ $chapter_id = $this->requestStack->getCurrentRequest()->query->get('chapter_id');
+ }
+ $root_path = rtrim($this->globalService->textbook_companion_path(), '/') . '/';
$APPROVE_PATH = 'APPROVED/';
$PENDING_PATH = 'PENDING/';
- /* get example data */
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $chapter_id);
- $chapter_q = $query->execute();
- $chapter_data = $chapter_q->fetchObject();
+
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'tcc')
+ ->fields('tcc')
+ ->condition('id', $chapter_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$chapter_data) {
+ $this->messenger->addError($this->t('Invalid chapter ID.'));
+ return $this->redirect('textbook_companion.bulk_approval_form');
+ }
+
$CH_PATH = 'CH' . $chapter_data->number . '/';
- /* zip filename */
- $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
- /* creating zip archive on the server */
- $zip = new ZipArchive();
- $zip->open($zip_filename, ZipArchive::CREATE);
- /* approved examples */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_id);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_id);
- $query->condition('approval_status', 1);
- $example_q = $query->execute();
+
+ $temp_dir = $root_path . 'tbc_download_temp/';
+ if (!is_dir($temp_dir)) {
+ mkdir($temp_dir, 0777, TRUE);
+ }
+ $zip_filename = $temp_dir . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
+
+ $zip = new \ZipArchive();
+ if ($zip->open($zip_filename, \ZipArchive::CREATE) !== TRUE) {
+ $this->messenger->addError($this->t('Unable to create zip file.'));
+ return $this->redirect('textbook_companion.bulk_approval_form');
+ }
+
+ // Approved examples
+ $example_q = $this->database->select('textbook_companion_example', 'tce')
+ ->fields('tce')
+ ->condition('chapter_id', $chapter_id)
+ ->condition('approval_status', 1)
+ ->execute();
+
while ($example_row = $example_q->fetchObject()) {
$EX_PATH = 'EX' . $example_row->number . '/';
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/
- $query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_row->id);
- $example_files_q = $query->execute();
+
+ $example_files_q = $this->database->select('textbook_companion_example_files', 'tcef')
+ ->fields('tcef')
+ ->condition('example_id', $example_row->id)
+ ->execute();
+
while ($example_files_row = $example_files_q->fetchObject()) {
- $zip->addFile($root_path . $example_files_row->filepath, $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
- } //$example_files_row = $example_files_q->fetchObject()
- } //$example_row = $example_q->fetchObject()
- /* unapproved examples */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_id);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_id);
- $query->condition('approval_status', 0);
- $example_q = $query->execute();
+ $file_path = $root_path . $example_files_row->filepath;
+ if (file_exists($file_path)) {
+ $zip->addFile($file_path, $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
+ }
+ }
+ }
+
+ // Unapproved examples
+ $example_q = $this->database->select('textbook_companion_example', 'tce')
+ ->fields('tce')
+ ->condition('chapter_id', $chapter_id)
+ ->condition('approval_status', 0)
+ ->execute();
+
while ($example_row = $example_q->fetchObject()) {
$EX_PATH = 'EX' . $example_row->number . '/';
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/
- $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", [
- ':example_id' => $example_row->id
- ]);
- /*$query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_row->id);
- $example_files_q = $query->execute();*/
+
+ $example_files_q = $this->database->query("
+ SELECT tcef.*, tcp.directory_name
+ FROM textbook_companion_preference tcp
+ JOIN textbook_companion_chapter tcc ON tcp.id = tcc.preference_id
+ JOIN textbook_companion_example tce ON tcc.id = tce.chapter_id
+ JOIN textbook_companion_example_files tcef ON tce.id = tcef.example_id
+ WHERE tcef.example_id = :example_id
+ ", [':example_id' => $example_row->id]);
+
while ($example_files_row = $example_files_q->fetchObject()) {
- $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
- } //$example_files_row = $example_files_q->fetchObject()
- } //$example_row = $example_q->fetchObject()
+ $file_path = $root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath;
+ if (file_exists($file_path)) {
+ $zip->addFile($file_path, $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
+ }
+ }
+ }
+
$zip_file_count = $zip->numFiles;
$zip->close();
+
if ($zip_file_count > 0) {
- /* download zip file */
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="CH' . $chapter_data->number . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- ob_end_flush();
- ob_clean();
- flush();
- readfile($zip_filename);
- unlink($zip_filename);
- } //$zip_file_count > 0
- else {
- drupal_set_message("There are no examples in this chapter to download", 'error');
- drupal_goto('textbook-companion/code-approval/bulk');
+ $response = new BinaryFileResponse($zip_filename);
+ $response->setContentDisposition(
+ ResponseHeaderBag::DISPOSITION_ATTACHMENT,
+ 'CH' . $chapter_data->number . '.zip'
+ );
+ $response->deleteFileAfterSend(TRUE);
+ return $response;
+ } else {
+ if (file_exists($zip_filename)) {
+ unlink($zip_filename);
+ }
+ $this->messenger->addError($this->t('There are no examples in this chapter to download.'));
+ return $this->redirect('textbook_companion.bulk_approval_form');
}
}
- public function textbook_companion_download_full_book() {
- $book_id = arg(3);
- $root_path = textbook_companion_path();
+ public function textbook_companion_download_full_book($book_id = NULL) {
+ if (!$book_id) {
+ $book_id = $this->requestStack->getCurrentRequest()->query->get('book_id');
+ }
+ $root_path = rtrim($this->globalService->textbook_companion_path(), '/') . '/';
$APPROVE_PATH = 'APPROVED/';
$PENDING_PATH = 'PENDING/';
- /* get example data */
- /*$book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id);
- $book_data = db_fetch_object($book_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $book_id);
- $book_q = $query->execute();
- $book_data = $book_q->fetchObject();
- //$zipname = str_replace(' ','_',($book_data->book));
- //$BK_PATH = $zipname . '/';
+
+ $book_data = $this->database->select('textbook_companion_preference', 'tcp')
+ ->fields('tcp')
+ ->condition('id', $book_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$book_data) {
+ $this->messenger->addError($this->t('Invalid book preference ID.'));
+ return $this->redirect('textbook_companion.bulk_approval_form');
+ }
+
$BK_PATH = $book_data->book . '/';
- /* zip filename */
- $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
- /* creating zip archive on the server */
- $zip = new ZipArchive();
- $zip->open($zip_filename, ZipArchive::CREATE);
- /* approved examples */
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $book_id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $book_id);
- $chapter_q = $query->execute();
+
+ $temp_dir = $root_path . 'tbc_download_temp/';
+ if (!is_dir($temp_dir)) {
+ mkdir($temp_dir, 0777, TRUE);
+ }
+ $zip_filename = $temp_dir . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
+
+ $zip = new \ZipArchive();
+ if ($zip->open($zip_filename, \ZipArchive::CREATE) !== TRUE) {
+ $this->messenger->addError($this->t('Unable to create zip file.'));
+ return $this->redirect('textbook_companion.bulk_approval_form');
+ }
+
+ $chapter_q = $this->database->select('textbook_companion_chapter', 'tcc')
+ ->fields('tcc')
+ ->condition('preference_id', $book_id)
+ ->execute();
+
while ($chapter_row = $chapter_q->fetchObject()) {
$CH_PATH = 'CH' . $chapter_row->number . '/';
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_row->id);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_row->id);
- $query->condition('approval_status', 1);
- $example_q = $query->execute();
+
+ // Approved examples
+ $example_q = $this->database->select('textbook_companion_example', 'tce')
+ ->fields('tce')
+ ->condition('chapter_id', $chapter_row->id)
+ ->condition('approval_status', 1)
+ ->execute();
+
while ($example_row = $example_q->fetchObject()) {
$EX_PATH = 'EX' . $example_row->number . '/';
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/
- $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", [
- ':example_id' => $example_row->id
- ]);
- /*$query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_row->id);
- $example_files_q = $query->execute();*/
+
+ $example_files_q = $this->database->query("
+ SELECT tcef.*, tcp.directory_name
+ FROM textbook_companion_preference tcp
+ JOIN textbook_companion_chapter tcc ON tcp.id = tcc.preference_id
+ JOIN textbook_companion_example tce ON tcc.id = tce.chapter_id
+ JOIN textbook_companion_example_files tcef ON tce.id = tcef.example_id
+ WHERE tcef.example_id = :example_id
+ ", [':example_id' => $example_row->id]);
+
while ($example_files_row = $example_files_q->fetchObject()) {
- $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $BK_PATH . $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
- } //$example_files_row = $example_files_q->fetchObject()
- } //$example_row = $example_q->fetchObject()
- /* unapproved examples */
- /* $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_row->id);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_row->id);
- $query->condition('approval_status', 0);
- $example_q = $query->execute();
+ $file_path = $root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath;
+ if (file_exists($file_path)) {
+ $zip->addFile($file_path, $BK_PATH . $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
+ }
+ }
+ }
+
+ // Unapproved examples
+ $example_q = $this->database->select('textbook_companion_example', 'tce')
+ ->fields('tce')
+ ->condition('chapter_id', $chapter_row->id)
+ ->condition('approval_status', 0)
+ ->execute();
+
while ($example_row = $example_q->fetchObject()) {
$EX_PATH = 'EX' . $example_row->number . '/';
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/
- $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", [
- ':example_id' => $example_row->id
- ]);
- /*$query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_row->id);
- $example_files_q = $query->execute();*/
+
+ $example_files_q = $this->database->query("
+ SELECT tcef.*, tcp.directory_name
+ FROM textbook_companion_preference tcp
+ JOIN textbook_companion_chapter tcc ON tcp.id = tcc.preference_id
+ JOIN textbook_companion_example tce ON tcc.id = tce.chapter_id
+ JOIN textbook_companion_example_files tcef ON tce.id = tcef.example_id
+ WHERE tcef.example_id = :example_id
+ ", [':example_id' => $example_row->id]);
+
while ($example_files_row = $example_files_q->fetchObject()) {
- $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $BK_PATH . $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
- } //$example_files_row = $example_files_q->fetchObject()
- } //$example_row = $example_q->fetchObject()
- } //$chapter_row = $chapter_q->fetchObject()
+ $file_path = $root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath;
+ if (file_exists($file_path)) {
+ $zip->addFile($file_path, $BK_PATH . $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename);
+ }
+ }
+ }
+ }
+
$zip_file_count = $zip->numFiles;
$zip->close();
+
if ($zip_file_count > 0) {
- /* download zip file */
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . str_replace(' ', '_', ($book_data->book)) . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- ob_clean();
- readfile($zip_filename);
- unlink($zip_filename);
- } //$zip_file_count > 0
- else {
- drupal_set_message("There are no examples in this book to download", 'error');
- drupal_goto('textbook-companion/code-approval/bulk');
+ $response = new BinaryFileResponse($zip_filename);
+ $response->setContentDisposition(
+ ResponseHeaderBag::DISPOSITION_ATTACHMENT,
+ str_replace(' ', '_', $book_data->book) . '.zip'
+ );
+ $response->deleteFileAfterSend(TRUE);
+ return $response;
+ } else {
+ if (file_exists($zip_filename)) {
+ unlink($zip_filename);
+ }
+ $this->messenger->addError($this->t('There are no examples in this book to download.'));
+ return $this->redirect('textbook_companion.bulk_approval_form');
}
}
- public function textbook_companion_delete_book() {
- $book_id = arg(2);
- del_book_pdf($book_id);
- drupal_set_message(t('Book schedule for regeneration.'), 'status');
- drupal_goto('code_approval/bulk');
- return;
+ public function textbook_companion_delete_book($book_id = NULL) {
+ if (!$book_id) {
+ $book_id = $this->requestStack->getCurrentRequest()->attributes->get('book_id');
+ }
+ if (function_exists('del_book_pdf')) {
+ del_book_pdf($book_id);
+ }
+ $this->messenger->addStatus($this->t('Book scheduled for regeneration.'));
+ return $this->redirect('textbook_companion.bulk_approval_form');
}
public function textbook_companion_ajax() {
- $query_type = arg(2);
+ $request = $this->requestStack->getCurrentRequest();
+ $path_info = $request->getPathInfo();
+ $path_parts = explode('/', trim($path_info, '/'));
+
+ // textbook-companion/ajax////
+ $query_type = isset($path_parts[2]) ? $path_parts[2] : '';
+
if ($query_type == 'chapter_title') {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if ($chapter_data = $chapter_q->fetchObject()) {
- echo $chapter_data->name;
- return;
- } //$chapter_data = $chapter_q->fetchObject()
- } //$query_type == 'chapter_title'
- else {
- if ($query_type == 'example_exists') {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- $example_number = arg(5);
- $chapter_id = 0;
- /* $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if (!$chapter_data = $chapter_q->fetchObject()) {
- echo '';
- return;
- } //!$chapter_data = $chapter_q->fetchObject()
+ $chapter_number = isset($path_parts[3]) ? $path_parts[3] : '';
+ $preference_id = isset($path_parts[4]) ? $path_parts[4] : '';
+
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'tcc')
+ ->fields('tcc')
+ ->condition('number', $chapter_number)
+ ->condition('preference_id', $preference_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if ($chapter_data) {
+ return new Response($chapter_data->name);
+ }
+ }
+ elseif ($query_type == 'example_exists') {
+ $chapter_number = isset($path_parts[3]) ? $path_parts[3] : '';
+ $preference_id = isset($path_parts[4]) ? $path_parts[4] : '';
+ $example_number = isset($path_parts[5]) ? $path_parts[5] : '';
+
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'tcc')
+ ->fields('tcc')
+ ->condition('number', $chapter_number)
+ ->condition('preference_id', $preference_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if (!$chapter_data) {
+ return new Response('');
+ }
+
+ $example_data = $this->database->select('textbook_companion_example', 'tce')
+ ->fields('tce')
+ ->condition('chapter_id', $chapter_data->id)
+ ->condition('number', $example_number)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if ($example_data) {
+ if ($example_data->approval_status == 1) {
+ return new Response('Warning! Example already approved. You cannot upload the same example again.');
+ }
else {
- $chapter_id = $chapter_data->id;
+ return new Response('Warning! Example already uploaded. Delete the example and reupload it.');
}
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND number = '%s' LIMIT 1", $chapter_id, $example_number);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_id);
- $query->condition('number', $example_number);
- $query->range(0, 1);
- $example_q = $query->execute();
- if ($example_data = $example_q->fetchObject()) {
- if ($example_data->approval_status == 1) {
- echo 'Warning! Example already approved. You cannot upload the same example again.';
- }
- else {
- echo 'Warning! Example already uploaded. Delete the example and reupload it.';
- }
- return;
- } //$example_data = $example_q->fetchObject()
}
- } //$query_type == 'example_exists'
- echo '';
+ }
+
+ return new Response('');
}
public function _data_entry_proposal_all() {
- /* get pending proposals to be approved */
$proposal_rows = [];
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 ORDER BY book ASC");*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('approval_status', 1);
- $query->orderBy('book', 'ASC');
- $preference_q = $query->execute();
+ $preference_q = $this->database->select('textbook_companion_preference', 'tcp')
+ ->fields('tcp')
+ ->condition('approval_status', 1)
+ ->orderBy('book', 'ASC')
+ ->execute();
+
$sno = 1;
while ($preference_data = $preference_q->fetchObject()) {
+ $url = Url::fromRoute('textbook_companion.dataentry_edit', ['id' => $preference_data->id]);
$proposal_rows[] = [
$sno++,
$preference_data->book,
$preference_data->author,
$preference_data->isbn,
- l('Edit', 'textbook-companion/dataentry-edit/' . $preference_data->id),
+ Link::fromTextAndUrl($this->t('Edit'), $url)->toString(),
];
- } //$preference_data = $preference_q->fetchObject()
- /* check if there are any pending proposals */
+ }
+
if (!$proposal_rows) {
- drupal_set_message(t('There are no proposals.'), 'status');
- return '';
- } //!$proposal_rows
+ $this->messenger->addStatus($this->t('There are no proposals.'));
+ return [
+ '#markup' => $this->t('There are no proposals.'),
+ ];
+ }
+
$proposal_header = [
- 'SNO',
- 'Title of the Book',
- 'Author',
- 'ISBN',
+ $this->t('SNO'),
+ $this->t('Title of the Book'),
+ $this->t('Author'),
+ $this->t('ISBN'),
'',
];
- $output = theme('table', [
- 'headers' => $proposal_header,
- 'rows' => $proposal_rows,
- ]);
- return $output;
+
+ return [
+ '#type' => 'table',
+ '#header' => $proposal_header,
+ '#rows' => $proposal_rows,
+ ];
}
public function dataentry_edit($id = NULL) {
if ($id) {
- return drupal_get_form('dataentry_edit_form', $id);
- } //$id
- else {
- return 'Access denied';
+ return $this->formBuilder->getForm('\Drupal\textbook_companion\Form\DataentryEditForm', $id);
}
+ return [
+ '#markup' => $this->t('Access denied'),
+ ];
}
public function cheque_proposal_all() {
-
-
- $form['#redirect'] = FALSE;
- $form['search_cheque'] = [
- '#type' => 'textfield',
- '#title' => t('Search'),
- '#size' => 48,
- ];
- $form['submit_cheque'] = [
- '#type' => 'submit',
- '#value' => t('Search'),
- ];
- $form['cancel_cheque'] = [
- '#type' => 'markup',
- '#value' => l(t('Cancel'), ''),
- ];
-
-
$count = 20;
- /* get pending proposals to be approved */
$proposal_rows = [];
- /*$proposal_q = "SELECT * FROM {textbook_companion_proposal} ORDER BY id DESC";*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->orderBy('id', 'DESC');
-
-
- /*$pagerquery = pager_query($proposal_q, $count); */
- $pagerquery = $query->extend('PagerDefault')->limit($count)->execute();
-
- while ($proposal_data = $pagerquery->fetchObject()) {
- /* get preference */
-
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
+ $query = $this->database->select('textbook_companion_proposal', 'tcp')
+ ->fields('tcp')
+ ->orderBy('id', 'DESC');
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
+ $pager_select = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit($count);
+ $result = $pager_select->execute();
- /*$preference_q1 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data1 = db_fetch_object($preference_q1);*/
+ while ($proposal_data = $result->fetchObject()) {
+ $contributor_url = Url::fromUri('internal:/user/' . $proposal_data->uid);
+ $submission_url = Url::fromRoute('textbook_companion.paper_submission_form', ['proposal_id' => $proposal_data->id]);
+ $cheque_url = Url::fromRoute('textbook_companion.cheque_status_form', ['proposal_id' => $proposal_data->id]);
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $proposal_data->id);
- $query->condition('proposal_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data1 = $result->fetchObject();
+ $status_links = Link::fromTextAndUrl($this->t('Form Submission'), $submission_url)->toString() . ' | ' .
+ Link::fromTextAndUrl($this->t('Cheque Details'), $cheque_url)->toString();
-
- $proposal_status = '';
- switch ($proposal_data->proposal_status) {
- case 0:
- $proposal_status = 'Pending';
- break;
- case 1:
- $proposal_status = 'Approved';
- break;
- case 2:
- $proposal_status = 'Dis-approved';
- break;
- case 3:
- $proposal_status = 'Completed';
- break;
- default:
- $proposal_status = 'Unknown';
- break;
- }
$proposal_rows[] = [
date('d-m-Y', $proposal_data->creation_date),
- l($proposal_data->full_name, 'user/' . $proposal_data->uid),
+ Link::fromTextAndUrl($proposal_data->full_name, $contributor_url)->toString(),
date('d-m-Y', $proposal_data->completion_date),
- l('Form Submission', 'manage_proposal/paper_submission/' . $proposal_data->id) . ' | ' . l('Cheque Details', 'cheque_contact/status/' . $proposal_data->id),
+ [
+ 'data' => [
+ '#markup' => $status_links,
+ ],
+ ],
];
}
- /* check if there are any pending proposals */
if (!$proposal_rows) {
- drupal_set_message(t('There are no proposals.'), 'status');
- return '';
+ $this->messenger->addStatus($this->t('There are no proposals.'));
+ return [
+ '#markup' => $this->t('There are no proposals.'),
+ ];
}
$proposal_header = [
- 'Date of Submission',
- 'Contributor Name',
- 'Expected Date of Completion',
- 'Status',
+ $this->t('Date of Submission'),
+ $this->t('Contributor Name'),
+ $this->t('Expected Date of Completion'),
+ $this->t('Status'),
];
- $output = theme('table', [
- 'header' => $proposal_header,
- 'rows' => $proposal_rows,
- ]);
- return $output . theme_pager($count);
- }
- // ---Added new functions
- public function textbook_companion_completed_books() {
- $output = '';
+ return [
+ 'table' => [
+ '#type' => 'table',
+ '#header' => $proposal_header,
+ '#rows' => $proposal_rows,
+ ],
+ 'pager' => [
+ '#type' => 'pager',
+ ],
+ ];
+ }
- $database = \Drupal::database();
- $query = $database->select('textbook_companion_preference', 'pe');
+ public function textbook_companion_completed_books() {
+ $query = $this->database->select('textbook_companion_preference', 'pe');
$query->fields('pe', ['book', 'author', 'publisher', 'year', 'id']);
$query->leftJoin('textbook_companion_proposal', 'po', 'pe.proposal_id = po.id');
$query->fields('po', ['full_name', 'university', 'completion_date']);
@@ -1931,78 +1543,78 @@ public function textbook_companion_completed_books() {
$results = $query->execute()->fetchAll();
if (empty($results)) {
- $output = [
- '#markup' => $this->t('Work has been completed on the following books under the Textbook Companion Project.') .
- '' .
- $this->t('The list below is not the books as named but only are the solved example for DWSIM') .
- ' ',
- ];
-}
-else {
- $output = [
- '#markup' => $this->t('Work has been completed on the following books under the Textbook Companion Project.') .
- '' .
- $this->t('The list below is not the books as named but only are the solved example for DWSIM.') .
- ' ',
- ];
-
- $rows = [];
- $i = count($results);
- foreach ($results as $row) {
- $completion_year = date("Y", $row->completion_date);
-
- $link = Link::fromTextAndUrl(
- $row->book . ' by ' . $row->author . ', ' . $row->publisher . ', ' . $row->year,
- Url::fromUserInput('/textbook-companion/textbook-run/' . $row->id)
- )->toString();
-
- $rows[] = [
- $i,
- $link,
- $row->full_name,
- $row->university,
- $completion_year,
- ];
- $i--;
- }
+ return [
+ '#markup' => $this->t('Work has been completed on the following books under the Textbook Companion Project.') .
+ '' .
+ $this->t('The list below is not the books as named but only are the solved example for DWSIM') .
+ ' ',
+ ];
+ }
- $header = [
- 'No',
- 'Title of the Book',
- 'Contributor Name',
- 'University / Institute',
- 'Year of Completion'
- ];
+ $rows = [];
+ $i = count($results);
+ foreach ($results as $row) {
+ $completion_year = date("Y", $row->completion_date);
- $output = [
- '#type' => 'table',
- '#header' => $header,
- '#rows' => $rows,
- //'#empty' => 'no rows found',
- ]; }
+ $link = Link::fromTextAndUrl(
+ $row->book . ' by ' . $row->author . ', ' . $row->publisher . ', ' . $row->year,
+ Url::fromUserInput('/textbook-companion/textbook-run/' . $row->id)
+ )->toString();
- return $output;
-}
- public function textbook_companion_download_example($example_id) {
- $root_path = \Drupal::service("textbook_companion_global")->textbook_companion_path();
+ $rows[] = [
+ $i,
+ [
+ 'data' => [
+ '#markup' => $link,
+ ],
+ ],
+ $row->full_name,
+ $row->university,
+ $completion_year,
+ ];
+ $i--;
+ }
- $connection = \Drupal::database();
+ $header = [
+ $this->t('No'),
+ $this->t('Title of the Book'),
+ $this->t('Contributor Name'),
+ $this->t('University / Institute'),
+ $this->t('Year of Completion')
+ ];
+
+ return [
+ 'intro' => [
+ '#markup' => $this->t('Work has been completed on the following books under the Textbook Companion Project.') .
+ '' .
+ $this->t('The list below is not the books as named but only are the solved example for DWSIM.') .
+ ' ',
+ ],
+ 'table' => [
+ '#type' => 'table',
+ '#header' => $header,
+ '#rows' => $rows,
+ ],
+ ];
+ }
+
+ public function textbook_companion_download_example($example_id) {
+ $root_path = rtrim($this->globalService->textbook_companion_path(), '/') . '/';
- // Fetch example data
- $example_data = \Drupal::database()->select('textbook_companion_example', 'tce')
+ $example_data = $this->database->select('textbook_companion_example', 'tce')
->fields('tce')
->condition('id', $example_id)
->execute()
->fetchObject();
- // if (!$example_data) {
- // $this->messenger()->addError($this->t('Example not found.'));
- // return $this->redirect('/textbook-companion/textbook-run');
- // }
+ if (!$example_data) {
+ $this->messenger->addError($this->t('Example not found.'));
+ return $this->redirect('textbook_companion.run_form');
+ }
- // Fetch example files
- $example_files = \Drupal::database()->query("
- SELECT * FROM textbook_companion_preference tcp
+ $example_files = $this->database->query("
+ SELECT tcp.directory_name, tcef.filepath, tcef.filename
+ FROM textbook_companion_preference tcp
JOIN textbook_companion_chapter tcc ON tcp.id = tcc.preference_id
JOIN textbook_companion_example tce ON tcc.id = tce.chapter_id
JOIN textbook_companion_example_files tcef ON tce.id = tcef.example_id
@@ -2010,41 +1622,43 @@ public function textbook_companion_download_example($example_id) {
", [':example_id' => $example_id]);
$EX_PATH = 'EX' . $example_data->number . '/';
- $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
-
- // var_dump($zip_filename);die;
+
+ $temp_dir = $root_path . 'tbc_download_temp/';
+ if (!is_dir($temp_dir)) {
+ mkdir($temp_dir, 0777, TRUE);
+ }
+ $zip_filename = $temp_dir . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
$zip = new \ZipArchive();
- $zip->open($zip_filename, \ZipArchive::CREATE);
-
+ if ($zip->open($zip_filename, \ZipArchive::CREATE) !== TRUE) {
+ $this->messenger->addError($this->t('Unable to create zip file.'));
+ return $this->redirect('textbook_companion.run_form');
+ }
foreach ($example_files as $file_row) {
- $zip->addFile($root_path . $file_row->directory_name . '/' . $file_row->filepath, $EX_PATH . $file_row->filename);
+ $file_path = $root_path . $file_row->directory_name . '/' . $file_row->filepath;
+ if (file_exists($file_path)) {
+ $zip->addFile($file_path, $EX_PATH . $file_row->filename);
+ }
}
-//
- // var_dump($root_path . $file_row->directory_name . '/' . $file_row->filepath, $EX_PATH . $file_row->filename );die;
- $zip_file_count = $zip->numFiles;
-
+ $zip_file_count = $zip->numFiles;
$zip->close();
if ($zip_file_count > 0) {
- $response = new Response(file_get_contents($zip_filename));
- $response->headers->set('Content-Type', 'application/octet-stream');
- $response->headers->set('Content-Disposition', 'attachment; filename="EX' . $example_data->number . '.zip"');
- $response->headers->set('Content-Length', filesize($zip_filename));
-
- unlink($zip_filename);
+ $response = new BinaryFileResponse($zip_filename);
+ $response->setContentDisposition(
+ ResponseHeaderBag::DISPOSITION_ATTACHMENT,
+ 'EX' . $example_data->number . '.zip'
+ );
+ $response->deleteFileAfterSend(TRUE);
return $response;
- }
- else {
- $this->messenger()->addError($this->t('There are no files in this example to download.'));
- // return $this->redirect('/textbook-companion/textbook-run');
+ } else {
+ if (file_exists($zip_filename)) {
+ unlink($zip_filename);
+ }
+ $this->messenger->addError($this->t('There are no files in this example to download.'));
+ return $this->redirect('textbook_companion.run_form');
}
}
-
-
-
-
-
}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/BookNotesForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/BookNotesForm.php
index 281da52..269b856 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/BookNotesForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/BookNotesForm.php
@@ -9,7 +9,10 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Form\EnforcedResponseException;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Url;
+use Drupal\Core\Link;
class BookNotesForm extends FormBase {
@@ -20,13 +23,24 @@ public function getFormId() {
return 'book_notes_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $preference_id = arg(2);
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $preference_id = NULL) {
+ if (empty($preference_id)) {
+ $preference_id = \Drupal::routeMatch()->getParameter('preference_id')
+ ?? \Drupal::request()->attributes->get('preference_id')
+ ?? \Drupal::request()->query->get('preference_id');
+ }
$preference_id = (int) $preference_id;
- /*$result = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id);*/
- $query = db_select('textbook_companion_preference');
+
+ if (empty($preference_id)) {
+ $this->messenger()->addError($this->t('Invalid book selected. Please try again.'));
+ $url = Url::fromRoute('textbook_companion.bulk_approval_form')->toString();
+ throw new EnforcedResponseException(new RedirectResponse($url));
+ }
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
$query->condition('id', $preference_id);
$result = $query->execute();
@@ -35,57 +49,72 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
/* everything ok */
}
else {
- drupal_set_message(t('Invalid book selected. Please try again.'), 'error');
- drupal_goto('code_approval/bulk');
- return;
+ $this->messenger()->addError($this->t('Invalid book selected. Please try again.'));
+ $url = Url::fromRoute('textbook_companion.bulk_approval_form')->toString();
+ throw new EnforcedResponseException(new RedirectResponse($url));
}
}
else {
- drupal_set_message(t('Invalid book selected. Please try again.'), 'error');
- drupal_goto('code_approval/bulk');
- return;
+ $this->messenger()->addError($this->t('Invalid book selected. Please try again.'));
+ $url = Url::fromRoute('textbook_companion.bulk_approval_form')->toString();
+ throw new EnforcedResponseException(new RedirectResponse($url));
}
+
+ $form_state->set('preference_id', $preference_id);
+
/* get current notes */
$notes = '';
- /*$notes_q = db_query("SELECT * FROM {textbook_companion_notes} WHERE preference_id = %d LIMIT 1", $preference_id);*/
- $query = db_select('textbook_companion_notes');
+ $query = \Drupal::database()->select('textbook_companion_notes');
$query->fields('textbook_companion_notes');
$query->condition('preference_id', $preference_id);
$query->range(0, 1);
$notes_q = $query->execute();
if ($notes_q) {
$notes_data = $notes_q->fetchObject();
- $notes = $notes_data->notes;
+ if ($notes_data) {
+ $notes = $notes_data->notes;
+ }
}
- $book_details = _book_information($preference_id);
- $form['book_details'] = [
- '#type' => 'item',
- '#markup' => 'About the Book ' . 'Author: ' . $book_details->author . ' ' . 'Title of the Book: ' . $book_details->book . ' ' . 'Publisher: ' . $book_details->publisher . ' ' . 'Year: ' . $book_details->year . ' ' . 'Edition: ' . $book_details->edition . ' ' . 'About the Contributor ' . 'Contributor Name: ' . $book_details->full_name . ', ' . $book_details->course . ', ' . $book_details->branch . ', ' . $book_details->university . ' ',
- ];
+
+ $book_details = $this->bookInformation($preference_id);
+ if ($book_details) {
+ $form['book_details'] = [
+ '#type' => 'item',
+ '#markup' => 'About the Book ' .
+ 'Author: ' . $book_details->author . ' ' .
+ 'Title of the Book: ' . $book_details->book . ' ' .
+ 'Publisher: ' . $book_details->publisher . ' ' .
+ 'Year: ' . $book_details->year . ' ' .
+ 'Edition: ' . $book_details->edition . ' ' .
+ 'About the Contributor ' .
+ 'Contributor Name: ' . $book_details->full_name . ', ' . $book_details->course . ', ' . $book_details->branch . ', ' . $book_details->university . ' ',
+ ];
+ }
+
$form['notes'] = [
'#type' => 'textarea',
'#rows' => 20,
- '#title' => t('Notes for Reviewers'),
+ '#title' => $this->t('Notes for Reviewers'),
'#default_value' => $notes,
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
$form['cancel'] = [
'#type' => 'markup',
- '#value' => l(t('Back'), 'code_approval/bulk'),
+ '#markup' => Link::fromTextAndUrl($this->t('Back'), Url::fromRoute('textbook_companion.bulk_approval_form'))->toString(),
];
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $preference_id = arg(2);
- $preference_id = (int) $preference_id;
- /*$result = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id);*/
- $query = db_select('textbook_companion_preference');
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $preference_id = $form_state->get('preference_id');
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
$query->condition('id', $preference_id);
$result = $query->execute();
@@ -94,46 +123,70 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
/* everything ok */
}
else {
- drupal_set_message(t('Invalid book selected. Please try again.'), 'error');
- drupal_goto('code_approval/bulk');
+ $this->messenger()->addError($this->t('Invalid book selected. Please try again.'));
+ $form_state->setRedirect('textbook_companion.bulk_approval_form');
return;
}
}
else {
- drupal_set_message(t('Invalid book selected. Please try again.'), 'error');
- drupal_goto('code_approval/bulk');
+ $this->messenger()->addError($this->t('Invalid book selected. Please try again.'));
+ $form_state->setRedirect('textbook_companion.bulk_approval_form');
return;
}
+
/* find existing notes */
- /*$notes_q = db_query("SELECT * FROM {textbook_companion_notes} WHERE preference_id = %d LIMIT 1", $preference_id);
- $notes_data = db_fetch_object($notes_q);*/
- $query = db_select('textbook_companion_notes');
+ $query = \Drupal::database()->select('textbook_companion_notes');
$query->fields('textbook_companion_notes');
$query->condition('preference_id', $preference_id);
$query->range(0, 1);
$notes_q = $query->execute();
$notes_data = $notes_q->fetchObject();
+
/* add or update notes in database */
if ($notes_data) {
- /*db_query("UPDATE {textbook_companion_notes} SET notes = '%s' WHERE id = %d", $form_state['values']['notes'], $notes_data->id);*/
- $query = db_update('textbook_companion_notes');
- $query->fields(['notes' => $form_state->getValue(['notes'])]);
+ $query = \Drupal::database()->update('textbook_companion_notes');
+ $query->fields(['notes' => $form_state->getValue('notes')]);
$query->condition('id', $notes_data->id);
- $num_updated = $query->execute();
- drupal_set_message('Notes updated successfully.', 'status');
+ $query->execute();
+ $this->messenger()->addMessage($this->t('Notes updated successfully.'), 'status');
}
else {
- /*db_query("INSERT INTO {textbook_companion_notes} (preference_id, notes) VALUES (%d, '%s')", $preference_id, $form_state['values']['notes']);*/
- $query = "INSERT INTO {textbook_companion_notes} (preference_id, notes) VALUES
- (:preference_id, :notes)";
- $args = [
- ":preference_id" => $preference_id,
- ":notes" => $form_state->getValue(['notes']),
- ];
- $result = db_query($query, $args, ['return' => Database::RETURN_INSERT_ID]);
- drupal_set_message('Notes added successfully.', 'status');
+ \Drupal::database()->insert('textbook_companion_notes')
+ ->fields([
+ 'preference_id' => $preference_id,
+ 'notes' => $form_state->getValue('notes'),
+ ])
+ ->execute();
+ $this->messenger()->addMessage($this->t('Notes added successfully.'), 'status');
}
+
+ $form_state->setRedirect('textbook_companion.bulk_approval_form');
+ }
+
+ /**
+ * Helper to retrieve book information.
+ */
+ protected function bookInformation($preference_id) {
+ $query = \Drupal::database()->select('textbook_companion_proposal', 'proposal');
+ $query->leftJoin('textbook_companion_preference', 'preference', 'proposal.id = preference.proposal_id');
+ $query->fields('preference', [
+ 'book',
+ 'author',
+ 'isbn',
+ 'publisher',
+ 'edition',
+ 'year',
+ ]);
+ $query->fields('proposal', [
+ 'full_name',
+ 'faculty',
+ 'reviewer',
+ 'course',
+ 'branch',
+ 'university',
+ ]);
+ $query->condition('preference.id', $preference_id);
+ return $query->execute()->fetchObject();
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/BulkApprovalForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/BulkApprovalForm.php
index b7832fc..6da6d49 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/BulkApprovalForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/BulkApprovalForm.php
@@ -9,10 +9,105 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Render\RendererInterface;
+use Drupal\textbook_companion\Services\MailService;
+use Drupal\textbook_companion\Services\AjaxHelper;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\Core\Url;
+use Drupal\Core\Link;
class BulkApprovalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The renderer service.
+ *
+ * @var \Drupal\Core\Render\RendererInterface
+ */
+ protected $renderer;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\textbook_companion\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * The reusable AJAX helper.
+ *
+ * @var \Drupal\textbook_companion\Services\AjaxHelper
+ */
+ protected $ajaxHelper;
+
+ /**
+ * Constructs a new BulkApprovalForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ RendererInterface $renderer,
+ MailService $mail_service,
+ AjaxHelper $ajax_helper
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->renderer = $renderer;
+ $this->mailService = $mail_service;
+ $this->ajaxHelper = $ajax_helper;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('renderer'),
+ $container->get('textbook_companion.mail_service'),
+ $container->get('textbook_companion.ajax_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,24 +115,23 @@ public function getFormId() {
return 'bulk_approval_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $options_first = _bulk_list_of_books();
- $options_two = _ajax_bulk_get_chapter_list();
- $selected = !$form_state->getValue(['book']) ? $form_state->getValue([
- 'book'
- ]) : key($options_first);
- $select_two = !$form_state->getValue(['chapter']) ? $form_state->getValue([
- 'chapter'
- ]) : key($options_two);
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $options_first = $this->bulkListOfBooks();
+ $selected = $form_state->getValue('book') ?? key($options_first);
+
+ $options_two = $this->ajaxBulkGetChapterList($selected);
+
$form['book'] = [
'#type' => 'select',
- '#title' => t('Title of the Book'),
- '#options' => _bulk_list_of_books(),
+ '#title' => $this->t('Title of the Book'),
+ '#options' => $options_first,
'#default_value' => $selected,
- '#tree' => TRUE,
'#ajax' => [
- 'callback' => 'ajax_bulk_chapter_list_callback'
- ],
+ 'callback' => '::ajaxBulkChapterListCallback'
+ ],
'#validated' => TRUE,
];
$form['download_book'] = [
@@ -50,35 +144,34 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['book_actions'] = [
'#type' => 'select',
- '#title' => t('Please select action for selected book'),
- '#options' => _bulk_list_book_actions(),
+ '#title' => $this->t('Please select action for selected book'),
+ '#options' => $this->bulkListBookActions(),
'#prefix' => '',
'#suffix' => '
',
'#states' => [
'invisible' => [
':input[name="book"]' => [
'value' => 0
- ]
]
- ],
+ ]
+ ],
'#validated' => TRUE,
];
$form['chapter'] = [
'#type' => 'select',
- '#title' => t('Title of the Chapter'),
- '#options' => _ajax_bulk_get_chapter_list($selected),
+ '#title' => $this->t('Title of the Chapter'),
+ '#options' => $options_two,
'#prefix' => '',
'#suffix' => '
',
'#validated' => TRUE,
- '#tree' => TRUE,
'#ajax' => [
- 'callback' => 'ajax_bulk_example_list_callback'
- ],
+ 'callback' => '::ajaxBulkExampleListCallback'
+ ],
'#states' => [
'invisible' => [
':input[name="book"]' => ['value' => 0]
- ]
- ],
+ ]
+ ],
];
$form['download_chapter'] = [
'#type' => 'item',
@@ -86,35 +179,34 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['chapter_actions'] = [
'#type' => 'select',
- '#title' => t('Please select action for selected chapter'),
- '#options' => _bulk_list_chapter_actions(),
+ '#title' => $this->t('Please select action for selected chapter'),
+ '#options' => $this->bulkListChapterActions(),
'#prefix' => '',
'#suffix' => '
',
'#states' => [
'invisible' => [
':input[name="book"]' => [
'value' => 0
- ]
]
- ],
- '#ajax' => ['callback' => 'ajax_bulk_chapter_actions_callback'],
+ ]
+ ],
+ '#ajax' => ['callback' => '::ajaxBulkChapterActionsCallback'],
];
$form['example'] = [
'#type' => 'select',
- '#title' => t('Example No. (Caption)'),
- '#options' => _ajax_bulk_get_examples(),
- // '#default_value' => $example_default_value,
- '#validated' => TRUE,
+ '#title' => $this->t('Example No. (Caption)'),
+ '#options' => $this->ajaxBulkGetExamples(),
+ '#validated' => TRUE,
'#prefix' => '',
'#suffix' => '
',
'#states' => [
'invisible' => [
':input[name="book"]' => [
'value' => 0
- ]
]
- ],
- '#ajax' => ['callback' => 'ajax_bulk_example_files_callback'],
+ ]
+ ],
+ '#ajax' => ['callback' => '::ajaxBulkExampleFilesCallback'],
];
$form['download_example'] = [
'#type' => 'item',
@@ -132,41 +224,41 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['example_actions'] = [
'#type' => 'select',
- '#title' => t('Please select action for selected example'),
- '#options' => _bulk_list_example_actions(),
+ '#title' => $this->t('Please select action for selected example'),
+ '#options' => $this->bulkListExampleActions(),
'#prefix' => '',
'#suffix' => '
',
'#states' => [
'invisible' => [
':input[name="book"]' => [
'value' => 0
- ]
]
- ],
+ ]
+ ],
];
$form['message'] = [
'#type' => 'textarea',
- '#title' => t('If Dis-Approved please specify reason for Dis-Approval'),
+ '#title' => $this->t('If Dis-Approved please specify reason for Dis-Approval'),
'#states' => [
'visible' => [
[
[
':input[name="book_actions"]' => [
'value' => 3
- ]
- ],
+ ]
+ ],
'or',
[':input[name="chapter_actions"]' => ['value' => 3]],
'or',
[
':input[name="example_actions"]' => [
'value' => 3
- ]
- ],
+ ]
+ ],
'or',
[':input[name="book_actions"]' => ['value' => 4]],
]
- ],
+ ],
'required' => [
[
[':input[name="book_actions"]' => ['value' => 3]],
@@ -174,614 +266,1000 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
[
':input[name="chapter_actions"]' => [
'value' => 3
- ]
- ],
+ ]
+ ],
'or',
[':input[name="example_actions"]' => ['value' => 3]],
'or',
[
':input[name="book_actions"]' => [
'value' => 4
- ]
- ],
+ ]
+ ],
]
- ],
+ ],
],
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
'#states' => [
'invisible' => [
':input[name="book"]' => [
'value' => 0
- ]
]
- ],
+ ]
+ ],
];
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $user = $this->currentUser;
$root_path = textbook_companion_path();
- if ($form_state->get(['clicked_button', '#value']) == 'Submit') {
- if ($form_state->getValue(['book'])) {
- del_book_pdf($form_state->getValue(['book']));
+
+ $triggering_element = $form_state->getTriggeringElement();
+ if ($triggering_element && $triggering_element['#value'] == $this->t('Submit')) {
+ $book_id = $form_state->getValue('book');
+ if ($book_id) {
+ del_book_pdf($book_id);
}
- if (user_access('bulk manage code')) {
- $query = db_select('textbook_companion_preference');
+
+ if ($this->currentUser->hasPermission('bulk manage code')) {
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$result = $query->execute();
$pref_data = $result->fetchObject();
+ if (!$pref_data) {
+ $this->messenger->addError($this->t('Invalid book selected.'));
+ return;
+ }
$prop_id = $pref_data->proposal_id;
- $query = db_select('textbook_companion_proposal');
+
+ $query = $this->database->select('textbook_companion_proposal');
$query->fields('textbook_companion_proposal');
$query->condition('id', $prop_id);
$user_query = $query->execute();
$user_info = $user_query->fetchObject();
- $user_data = user_load($user_info->uid);
- if (($form_state->getValue(['book_actions']) == 1) && ($form_state->getValue(['chapter_actions']) == 0) && ($form_state->getValue(['example_actions']) == 0)) {
+ if (!$user_info) {
+ $this->messenger->addError($this->t('Invalid proposal data.'));
+ return;
+ }
+
+ $user_data = $this->entityTypeManager->getStorage('user')->load($user_info->uid);
+ if (!$user_data) {
+ $this->messenger->addError($this->t('User could not be loaded.'));
+ return;
+ }
+
+ $email_subject = '';
+ $email_body = [];
+
+ $book_actions = $form_state->getValue('book_actions');
+ $chapter_actions = $form_state->getValue('chapter_actions');
+ $example_actions = $form_state->getValue('example_actions');
+
+ $site_name = \Drupal::config('system.site')->get('name');
+
+ if (($book_actions == 1) && ($chapter_actions == 0) && ($example_actions == 0)) {
/* approving entire book */
- $query = db_select('textbook_companion_preference');
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$preference_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+ if (!$preference_data) {
+ $this->messenger->addError($this->t('Preference details not found or not approved.'));
+ return;
+ }
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
+ $query->condition('preference_id', $book_id);
$chapter_q = $query->execute();
while ($chapter_data = $chapter_q->fetchObject()) {
- $query = db_update('textbook_companion_example');
+ $query = $this->database->update('textbook_companion_example');
$query->fields([
'approval_status' => 1,
- 'approver_uid' => $user->uid,
+ 'approver_uid' => $user->id(),
]);
$query->condition('chapter_id', $chapter_data->id);
$query->condition('approval_status', 0);
- $num_updated = $query->execute();
- } //$chapter_data = $chapter_q->fetchObject()
- $query = db_update('textbook_companion_preference');
+ $query->execute();
+ }
+
+ $query = $this->database->update('textbook_companion_preference');
$query->fields(['submited_all_examples_code' => 2]);
- $query->condition('id', $form_state->getValue(['book']));
- $num_updated = $query->execute();
- drupal_set_message(t('Approved Entire Book.'), 'status');
+ $query->condition('id', $book_id);
+ $query->execute();
+
+ $this->messenger->addStatus($this->t('Approved Entire Book.'));
/* email */
- $email_subject = t('[!site_name][Textbook Companion] Your uploaded Textbook Companion examples have been approved', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name][Textbook Companion] Your uploaded Textbook Companion examples have been approved', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your all the uploaded examples for the book have been approved.
-Title of the book : ' . $preference_data->book . '
-Author name : ' . $preference_data->author . '
-ISBN No. : ' . $preference_data->isbn . '
-Publisher and Place : ' . $preference_data->publisher . '
-Edition : ' . $preference_data->edition . '
-Year of publication : ' . $preference_data->year . '
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 1) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 0)
- elseif (($form_state->getValue(['book_actions']) == 2) && ($form_state->getValue(['chapter_actions']) == 0) && ($form_state->getValue(['example_actions']) == 0)) {
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $preference_data->book,
+ '@author' => $preference_data->author,
+ '@isbn' => $preference_data->isbn,
+ '@publisher' => $preference_data->publisher,
+ '@edition' => $preference_data->edition,
+ '@year' => $preference_data->year,
+ ])->render()
+ ];
+ }
+ elseif (($book_actions == 2) && ($chapter_actions == 0) && ($example_actions == 0)) {
/* pending entire book */
- $query = db_select('textbook_companion_preference');
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$preference_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+ if (!$preference_data) {
+ $this->messenger->addError($this->t('Preference details not found or not approved.'));
+ return;
+ }
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
+ $query->condition('preference_id', $book_id);
$chapter_q = $query->execute();
while ($chapter_data = $chapter_q->fetchObject()) {
- $query = db_update('textbook_companion_example');
+ $query = $this->database->update('textbook_companion_example');
$query->fields(['approval_status' => 0]);
$query->condition('chapter_id', $chapter_data->id);
- $num_updated = $query->execute();
- } //$chapter_data = $chapter_q->fetchObject()
- drupal_set_message(t('Pending Review Entire Book.'), 'status');
+ $query->execute();
+ }
+
+ $this->messenger->addStatus($this->t('Pending Review Entire Book.'));
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been marked as pending', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion examples have been marked as pending', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your all the uploaded examples for the book have been marked as pending to be reviewed.
You will be able to see the examples after they have been approved by one of our reviewers.
-Title of the book : ' . $preference_data->book . '
-Author name : ' . $preference_data->author . '
-ISBN No. : ' . $preference_data->isbn . '
-Publisher and Place : ' . $preference_data->publisher . '
-Edition : ' . $preference_data->edition . '
-Year of publication : ' . $preference_data->year . '
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 2) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 0)
- elseif (($form_state->getValue(['book_actions']) == 3) && ($form_state->getValue(['chapter_actions']) == 0) && ($form_state->getValue(['example_actions']) == 0)) {
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- $form_state->setErrorByName('message', t(''));
- drupal_set_message("Please mention the reason for disapproval. Minimum 30 character required", 'error');
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $preference_data->book,
+ '@author' => $preference_data->author,
+ '@isbn' => $preference_data->isbn,
+ '@publisher' => $preference_data->publisher,
+ '@edition' => $preference_data->edition,
+ '@year' => $preference_data->year,
+ ])->render()
+ ];
+ }
+ elseif (($book_actions == 3) && ($chapter_actions == 0) && ($example_actions == 0)) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $form_state->setErrorByName('message', $this->t(''));
+ $this->messenger->addError($this->t('Please mention the reason for disapproval. Minimum 30 character required.'));
return;
- } //strlen(trim($form_state['values']['message'])) <= 30
- $query = db_select('textbook_companion_preference');
+ }
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$preference_data = $result->fetchObject();
- if (!user_access('bulk delete code')) {
- drupal_set_message(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Book.'), 'error');
+ if (!$preference_data) {
+ $this->messenger->addError($this->t('Preference details not found or not approved.'));
+ return;
+ }
+
+ if (!$this->currentUser->hasPermission('bulk delete code')) {
+ $this->messenger->addError($this->t('You do not have permission to Bulk Dis-Approved and Deleted Entire Book.'));
return;
- } //!user_access('bulk delete code')
- if (delete_book($form_state->getValue(['book']))) {
- drupal_set_message(t('Dis-Approved and Deleted Entire Book.'), 'status');
- } //delete_book($form_state['values']['book'])
+ }
+
+ if (delete_book($book_id)) {
+ $this->messenger->addStatus($this->t('Dis-Approved and Deleted Entire Book.'));
+ }
else {
- drupal_set_message(t('Error Dis-Approving and Deleting Entire Book.'), 'error');
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Entire Book.'));
}
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been marked as
- dis-approved', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion examples have been marked as dis-approved', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your all the uploaded examples for the whole book have been marked as dis-approved.
-Title of the book : ' . $preference_data->book . '
-Author name : ' . $preference_data->author . '
-ISBN No. : ' . $preference_data->isbn . '
-Publisher and Place : ' . $preference_data->publisher . '
-Edition : ' . $preference_data->edition . '
-Year of publication : ' . $preference_data->year . '
-
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
-Reason for dis-approval:' . $form_state->getValue(['message']) . '
+Reason for dis-approval: @message
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $preference_data->book,
+ '@author' => $preference_data->author,
+ '@isbn' => $preference_data->isbn,
+ '@publisher' => $preference_data->publisher,
+ '@edition' => $preference_data->edition,
+ '@year' => $preference_data->year,
+ '@message' => $form_state->getValue('message'),
+ ])->render()
+ ];
}
- elseif (($form_state->getValue(['book_actions']) == 4) && ($form_state->getValue(['chapter_actions']) == 0) && ($form_state->getValue(['example_actions']) == 0)) {
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- $form_state->setErrorByName('message', t(''));
- drupal_set_message("Please mention the reason for disapproval/deletion. Minimum 30 character required", 'error');
+ elseif (($book_actions == 4) && ($chapter_actions == 0) && ($example_actions == 0)) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $form_state->setErrorByName('message', $this->t(''));
+ $this->messenger->addError($this->t('Please mention the reason for disapproval/deletion. Minimum 30 character required.'));
return;
- } //strlen(trim($form_state['values']['message'])) <= 30
- $query = db_select('textbook_companion_preference');
+ }
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$pref_data = $result->fetchObject();
- if (!user_access('bulk delete code')) {
- drupal_set_message(t('You do not have permission to Bulk Delete Entire Book Including Proposal.'), 'error');
+ if (!$pref_data) {
+ $this->messenger->addError($this->t('Preference details not found or not approved.'));
+ return;
+ }
+
+ if (!$this->currentUser->hasPermission('bulk delete code')) {
+ $this->messenger->addError($this->t('You do not have permission to Bulk Delete Entire Book Including Proposal.'));
return;
- } //!user_access('bulk delete code')
- /* check if dependency files are present */
- if (delete_book($form_state->getValue(['book']))) {
- drupal_set_message(t('Dis-Approved and Deleted Entire Book examples.'), 'status');
- $dir_path = $root_path . $form_state->getValue(['book']);
+ }
+
+ if (delete_book($book_id)) {
+ $this->messenger->addStatus($this->t('Dis-Approved and Deleted Entire Book examples.'));
+ $dir_path = $root_path . $book_id;
if (is_dir($dir_path)) {
$res = rmdir($dir_path);
if (!$res) {
- drupal_set_message(t("Cannot delete Book directory : " . $dir_path . ". Please contact administrator."), 'error');
+ $this->messenger->addError($this->t("Cannot delete Book directory : @dir_path. Please contact administrator.", ['@dir_path' => $dir_path]));
return;
- } //!$res
- } //is_dir($dir_path)
+ }
+ }
else {
- drupal_set_message(t("Book directory not present : " . $dir_path . ". Skipping deleting book directory."), 'status');
+ $this->messenger->addStatus($this->t("Book directory not present : @dir_path. Skipping deleting book directory.", ['@dir_path' => $dir_path]));
}
/* deleting preference and proposal */
- $query = db_select('textbook_companion_preference');
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$result = $query->execute();
$preference_data = $result->fetchObject();
$proposal_id = $preference_data->proposal_id;
- $query = db_delete('textbook_companion_preference');
+
+ $query = $this->database->delete('textbook_companion_preference');
$query->condition('proposal_id', $proposal_id);
- $num_deleted = $query->execute();
- $query = db_delete('textbook_companion_proposal');
+ $query->execute();
+
+ $query = $this->database->delete('textbook_companion_proposal');
$query->condition('id', $proposal_id);
- $num_deleted = $query->execute();
- drupal_set_message(t('Deleted Book Proposal.'), 'status');
+ $query->execute();
+
+ $this->messenger->addStatus($this->t('Deleted Book Proposal.'));
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion examples including the book proposal have been deleted', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion examples including the book proposal have been deleted', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
We regret to inform you that all the uploaded examples including the book with following details have been deleted permanently.
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
-Title of the book : ' . $pref_data->book . '
-Author name : ' . $pref_data->author . '
-ISBN No. : ' . $pref_data->isbn . '
-Publisher and Place : ' . $pref_data->publisher . '
-Edition : ' . $pref_data->edition . '
-Year of publication : ' . $pref_data->year . '
-
-Reason for deletion:' . $form_state->getValue(['message']) . '
-
+Reason for deletion: @message
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //delete_book($form_state['values']['book'])
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $pref_data->book,
+ '@author' => $pref_data->author,
+ '@isbn' => $pref_data->isbn,
+ '@publisher' => $pref_data->publisher,
+ '@edition' => $pref_data->edition,
+ '@year' => $pref_data->year,
+ '@message' => $form_state->getValue('message'),
+ ])->render()
+ ];
+ }
else {
- drupal_set_message(t('Error Dis-Approving and Deleting Entire Book.'), 'error');
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Entire Book.'));
}
- } //($form_state['values']['book_actions'] == 4) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 0)
- elseif (($form_state->getValue(['book_actions']) == 0) && ($form_state->getValue(['chapter_actions']) == 1) && ($form_state->getValue(['example_actions']) == 0)) {
- $query = db_select('textbook_companion_preference');
+ }
+ elseif (($book_actions == 0) && ($chapter_actions == 1) && ($example_actions == 0)) {
+ $chapter_id = $form_state->getValue('chapter');
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$pref_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
- $query->condition('id', $form_state->getValue(['chapter']));
+ $query->condition('preference_id', $book_id);
+ $query->condition('id', $chapter_id);
$result = $query->execute();
$chap_data = $result->fetchObject();
- $query = db_update('textbook_companion_example');
+
+ $query = $this->database->update('textbook_companion_example');
$query->fields([
'approval_status' => 1,
- 'approver_uid' => $user->uid,
+ 'approver_uid' => $user->id(),
]);
- $query->condition('chapter_id', $form_state->getValue(['chapter']));
+ $query->condition('chapter_id', $chapter_id);
$query->condition('approval_status', 0);
- $num_updated = $query->execute();
- drupal_set_message(t('Approved Entire Chapter.'), 'status');
+ $query->execute();
+
+ $this->messenger->addStatus($this->t('Approved Entire Chapter.'));
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been approved', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion examples have been approved', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your all the uploaded examples for the chapter have been approved.
-Title of the book : ' . $pref_data->book . '
-Title of the chapter : ' . $chap_data->name . '
+Title of the book : @book
+Title of the chapter : @chapter
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 1) && ($form_state['values']['example_actions'] == 0)
- elseif (($form_state->getValue(['book_actions']) == 0) && ($form_state->getValue(['chapter_actions']) == 2) && ($form_state->getValue(['example_actions']) == 0)) {
- $query = db_select('textbook_companion_preference');
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $pref_data->book,
+ '@chapter' => $chap_data->name,
+ ])->render()
+ ];
+ }
+ elseif (($book_actions == 0) && ($chapter_actions == 2) && ($example_actions == 0)) {
+ $chapter_id = $form_state->getValue('chapter');
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$pref_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
- $query->condition('id', $form_state->getValue(['chapter']));
+ $query->condition('preference_id', $book_id);
+ $query->condition('id', $chapter_id);
$result = $query->execute();
$chap_data = $result->fetchObject();
- $query = db_update('textbook_companion_example');
+
+ $query = $this->database->update('textbook_companion_example');
$query->fields(['approval_status' => 0]);
- $query->condition('chapter_id', $form_state->getValue(['chapter']));
- $num_updated = $query->execute();
- drupal_set_message(t('Entire Chapter marked as Pending Review.'), 'status');
+ $query->condition('chapter_id', $chapter_id);
+ $query->execute();
+
+ $this->messenger->addStatus($this->t('Entire Chapter marked as Pending Review.'));
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been marked as pending', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion examples have been marked as pending', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your all the uploaded examples for the chapter have been marked as pending to be reviewed.
-Title of the book : ' . $pref_data->book . '
-Title of the chapter : ' . $chap_data->name . '
+Title of the book : @book
+Title of the chapter : @chapter
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 2) && ($form_state['values']['example_actions'] == 0)
- elseif (($form_state->getValue(['book_actions']) == 0) && ($form_state->getValue(['chapter_actions']) == 3) && ($form_state->getValue(['example_actions']) == 0)) {
- $query = db_select('textbook_companion_preference');
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $pref_data->book,
+ '@chapter' => $chap_data->name,
+ ])->render()
+ ];
+ }
+ elseif (($book_actions == 0) && ($chapter_actions == 3) && ($example_actions == 0)) {
+ $chapter_id = $form_state->getValue('chapter');
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$pref_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
- $query->condition('id', $form_state->getValue(['chapter']));
+ $query->condition('preference_id', $book_id);
+ $query->condition('id', $chapter_id);
$result = $query->execute();
$chap_data = $result->fetchObject();
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- $form_state->setErrorByName('message', t(''));
- drupal_set_message("Please mention the reason for disapproval. Minimum 30 character required", 'error');
+
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $form_state->setErrorByName('message', $this->t(''));
+ $this->messenger->addError($this->t('Please mention the reason for disapproval. Minimum 30 character required.'));
return;
- } //strlen(trim($form_state['values']['message'])) <= 30
- if (!user_access('bulk delete code')) {
- drupal_set_message(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Chapter.'), 'error');
+ }
+
+ if (!$this->currentUser->hasPermission('bulk delete code')) {
+ $this->messenger->addError($this->t('You do not have permission to Bulk Dis-Approved and Deleted Entire Chapter.'));
return;
- } //!user_access('bulk delete code')
- if (delete_chapter($form_state->getValue(['chapter']))) {
- drupal_set_message(t('Dis-Approved and Deleted Entire Chapter.'), 'status');
- } //delete_chapter($form_state['values']['chapter'])
+ }
+
+ if (delete_chapter($chapter_id)) {
+ $this->messenger->addStatus($this->t('Dis-Approved and Deleted Entire Chapter.'));
+ }
else {
- drupal_set_message(t('Error Dis-Approving and Deleting Entire Chapter.'), 'error');
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Entire Chapter.'));
}
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion example have been marked as dis-approved', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion example have been marked as dis-approved', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your uploaded example for the entire chapter have been marked as dis-approved.
-Title of the book : ' . $pref_data->book . '
-Title of the chapter : ' . $chap_data->name . '
-
+Title of the book : @book
+Title of the chapter : @chapter
-Reason for dis-approval:' . $form_state->getValue(['message']) . '
+Reason for dis-approval: @message
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 3) && ($form_state['values']['example_actions'] == 0)
- elseif (($form_state->getValue(['book_actions']) == 0) && ($form_state->getValue(['chapter_actions']) == 0) && ($form_state->getValue(['example_actions']) == 1)) {
- $query = db_select('textbook_companion_preference');
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $pref_data->book,
+ '@chapter' => $chap_data->name,
+ '@message' => $form_state->getValue('message'),
+ ])->render()
+ ];
+ }
+ elseif (($book_actions == 0) && ($chapter_actions == 0) && ($example_actions == 1)) {
+ $chapter_id = $form_state->getValue('chapter');
+ $example_id = $form_state->getValue('example');
+
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$pref_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
- $query->condition('id', $form_state->getValue(['chapter']));
+ $query->condition('preference_id', $book_id);
+ $query->condition('id', $chapter_id);
$result = $query->execute();
$chap_data = $result->fetchObject();
- $query = db_select('textbook_companion_example');
+
+ $query = $this->database->select('textbook_companion_example');
$query->fields('textbook_companion_example');
- $query->condition('id', $form_state->getValue(['example']));
+ $query->condition('id', $example_id);
$result = $query->execute();
$examp_data = $result->fetchObject();
- $query = db_update('textbook_companion_example');
+
+ $query = $this->database->update('textbook_companion_example');
$query->fields([
'approval_status' => 1,
- 'approver_uid' => $user->uid,
+ 'approver_uid' => $user->id(),
]);
- $query->condition('id', $form_state->getValue(['example']));
- $num_updated = $query->execute();
- drupal_set_message(t('Example approved.'), 'status');
+ $query->condition('id', $example_id);
+ $query->execute();
+
+ $this->messenger->addStatus($this->t('Example approved.'));
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion example have been approved', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion example have been approved', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your example for DWSIM Textbook Companion with the following details is approved.
-Title of the book : ' . $pref_data->book . '
-Title of the chapter : ' . $chap_data->name . '
-Example number : ' . $examp_data->number . '
-Caption : ' . $examp_data->caption . '
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 1)
- elseif (($form_state->getValue(['book_actions']) == 0) && ($form_state->getValue(['chapter_actions']) == 0) && ($form_state->getValue(['example_actions']) == 2)) {
- $query = db_select('textbook_companion_preference');
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $pref_data->book,
+ '@chapter' => $chap_data->name,
+ '@number' => $examp_data->number,
+ '@caption' => $examp_data->caption,
+ ])->render()
+ ];
+ }
+ elseif (($book_actions == 0) && ($chapter_actions == 0) && ($example_actions == 2)) {
+ $chapter_id = $form_state->getValue('chapter');
+ $example_id = $form_state->getValue('example');
+
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$pref_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
- $query->condition('id', $form_state->getValue(['chapter']));
+ $query->condition('preference_id', $book_id);
+ $query->condition('id', $chapter_id);
$result = $query->execute();
$chap_data = $result->fetchObject();
- $query = db_select('textbook_companion_example');
+
+ $query = $this->database->select('textbook_companion_example');
$query->fields('textbook_companion_example');
- $query->condition('id', $form_state->getValue(['example']));
+ $query->condition('id', $example_id);
$result = $query->execute();
$examp_data = $result->fetchObject();
- $query = db_update('textbook_companion_example');
+
+ $query = $this->database->update('textbook_companion_example');
$query->fields(['approval_status' => 0]);
- $query->condition('id', $form_state->getValue(['example']));
- $num_updated = $query->execute();
- drupal_set_message(t('Example marked as Pending Review.'), 'status');
+ $query->condition('id', $example_id);
+ $query->execute();
+
+ $this->messenger->addStatus($this->t('Example marked as Pending Review.'));
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion example has been marked as pending', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion example has been marked as pending', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your uploaded example for DWSIM Textbook Companion with the following details has been marked as pending to be reviewed.
-Title of the book : ' . $pref_data->book . '
-Title of the chapter : ' . $chap_data->name . '
-Example number : ' . $examp_data->number . '
-Caption : ' . $examp_data->caption . '
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 2)
- elseif (($form_state->getValue(['book_actions']) == 0) && ($form_state->getValue(['chapter_actions']) == 0) && ($form_state->getValue(['example_actions']) == 3)) {
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- $form_state->setErrorByName('message', t(''));
- drupal_set_message("Please mention the reason for disapproval. Minimum 30 character required", 'error');
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $pref_data->book,
+ '@chapter' => $chap_data->name,
+ '@number' => $examp_data->number,
+ '@caption' => $examp_data->caption,
+ ])->render()
+ ];
+ }
+ elseif (($book_actions == 0) && ($chapter_actions == 0) && ($example_actions == 3)) {
+ $chapter_id = $form_state->getValue('chapter');
+ $example_id = $form_state->getValue('example');
+
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $form_state->setErrorByName('message', $this->t(''));
+ $this->messenger->addError($this->t('Please mention the reason for disapproval. Minimum 30 character required.'));
return;
- } //strlen(trim($form_state['values']['message'])) <= 30
- $query = db_select('textbook_companion_preference');
+ }
+
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
- $query->condition('id', $form_state->getValue(['book']));
+ $query->condition('id', $book_id);
$query->condition('approval_status', 1);
$result = $query->execute();
$pref_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
+
+ $query = $this->database->select('textbook_companion_chapter');
$query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $form_state->getValue(['book']));
- $query->condition('id', $form_state->getValue(['chapter']));
+ $query->condition('preference_id', $book_id);
+ $query->condition('id', $chapter_id);
$result = $query->execute();
$chap_data = $result->fetchObject();
- $query = db_select('textbook_companion_example');
+
+ $query = $this->database->select('textbook_companion_example');
$query->fields('textbook_companion_example');
- $query->condition('id', $form_state->getValue(['example']));
+ $query->condition('id', $example_id);
$result = $query->execute();
$examp_data = $result->fetchObject();
- if (delete_example($form_state->getValue(['example']))) {
- drupal_set_message(t('Example Dis-Approved and Deleted.'), 'status');
- } //delete_example($form_state['values']['example'])
+
+ if (delete_example($example_id)) {
+ $this->messenger->addStatus($this->t('Example Dis-Approved and Deleted.'));
+ }
else {
- drupal_set_message(t('Error Dis-Approving and Deleting Example.'), 'error');
+ $this->messenger->addError($this->t('Error Dis-Approving and Deleting Example.'));
}
/* email */
- $email_subject = t('[!site_name] Your uploaded Textbook Companion example has been marked as
- dis-approved', [
- '!site_name' => variable_get('site_name', '')
- ]);
+ $email_subject = $this->t('[@site_name] Your uploaded Textbook Companion example has been marked as dis-approved', [
+ '@site_name' => $site_name,
+ ])->render();
$email_body = [
- 0 => t('
-
-Dear !user_name,
+ 0 => $this->t('
+Dear @user_name,
Your example for DWSIM Textbook Companion has been marked as dis-approved and deleted.
-Title of the book : ' . $pref_data->book . '
-Title of the chapter : ' . $chap_data->name . '
-Example number : ' . $examp_data->number . '
-Caption : ' . $examp_data->caption . '
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
-Reason for dis-approval:' . $form_state->getValue(['message']) . '
+Reason for dis-approval: @message
Best Wishes,
-!site_name Team,
+@site_name Team,
FOSSEE,IIT Bombay', [
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name,
- ])
- ];
- } //($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 3)
+ '@site_name' => $site_name,
+ '@user_name' => $user_data->getDisplayName(),
+ '@book' => $pref_data->book,
+ '@chapter' => $chap_data->name,
+ '@number' => $examp_data->number,
+ '@caption' => $examp_data->caption,
+ '@message' => $form_state->getValue('message'),
+ ])->render()
+ ];
+ }
else {
- drupal_set_message(t('Please select only one action at a time'), 'error');
+ $this->messenger->addError($this->t('Please select only one action at a time.'));
return;
}
+
/****** sending email when everything done ******/
if ($email_subject) {
- $email_to = $user_data->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $params['standard']['subject'] = $email_subject;
- $params['standard']['body'] = $email_body;
- $params['standard']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ $email_to = $user_data->getEmail();
+ if (!$this->mailService->sendNotification('textbook_companion', 'standard', $email_to, $email_subject, implode("\n", $email_body))) {
+ $this->messenger->addError($this->t('Error sending email message.'));
}
- } //$email_subject
- } //user_access('bulk manage code')
+ }
+ }
else {
- drupal_set_message(t('You do not have permission to bulk manage code.'), 'error');
+ $this->messenger->addError($this->t('You do not have permission to bulk manage code.'));
+ }
+ }
+ }
+
+ /**
+ * AJAX callback to refresh chapter and book actions select list when a book is selected.
+ */
+ public function ajaxBulkChapterListCallback(array &$form, FormStateInterface $form_state) {
+ $book_default_value = $form_state->getValue('book');
+ if ($book_default_value > 0) {
+ $download_uri = Url::fromUri('internal:/textbook-companion/full-download/book/' . $book_default_value);
+ $download_link = Link::fromTextAndUrl($this->t('Download'), $download_uri)->toString() . ' ' . $this->t('(Download all the approved and unapproved examples of the entire book)');
+
+ $form['book_actions']['#options'] = $this->bulkListBookActions();
+ $form['chapter']['#options'] = $this->ajaxBulkGetChapterList($book_default_value);
+ $form['chapter_actions']['#options'] = $this->bulkListChapterActions();
+ $form['example_actions']['#options'] = $this->bulkListExampleActions();
+ $form['example_files']['#title'] = '';
+ $form['example_files']['#markup'] = '';
+
+ // Preserve original final command per selector (replace-then-clear => html '').
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_selected_book' => ['type' => 'html', 'content' => $download_link],
+ '#ajax_selected_book_action' => ['type' => 'replace', 'content' => $form['book_actions']],
+ '#ajax_select_chapter_list' => ['type' => 'replace', 'content' => $form['chapter']],
+ '#ajax_download_chapter' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_chapter_action' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_example_action' => ['type' => 'html', 'content' => ''],
+ '#ajax_download_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_edit_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_example_files_list' => ['type' => 'replace', 'content' => $form['example_files']],
+ ]);
+ }
+
+ $form['chapter']['#options'] = $this->ajaxBulkGetChapterList();
+ $form['book_actions']['#options'] = $this->bulkListBookActions();
+ $form['chapter_actions']['#options'] = $this->bulkListChapterActions();
+ $form['example_actions']['#options'] = $this->bulkListExampleActions();
+ $form['example_files']['#title'] = '';
+ $form['example_files']['#markup'] = '';
+
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_selected_book' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_book_pdf' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_book_regenerate_pdf' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_book_notes' => ['type' => 'html', 'content' => ''],
+ '#ajax_select_chapter_list' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_book_action' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_chapter_action' => ['type' => 'html', 'content' => ''],
+ '#ajax_download_chapter' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_example_action' => ['type' => 'html', 'content' => ''],
+ '#ajax_download_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_edit_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_example_files_list' => ['type' => 'replace', 'content' => $form['example_files']],
+ ]);
+ }
+
+ /**
+ * AJAX callback to refresh example list when a chapter is selected.
+ */
+ public function ajaxBulkExampleListCallback(array &$form, FormStateInterface $form_state) {
+ $chapter_default_value = $form_state->getValue('chapter');
+ if ($chapter_default_value > 0) {
+ $download_uri = Url::fromUri('internal:/textbook-companion/full-download/chapter/' . $chapter_default_value);
+ $download_link = Link::fromTextAndUrl($this->t('Download'), $download_uri)->toString() . ' ' . $this->t('(Download all the approved and unapproved examples of the entire chapter)');
+
+ $form['chapter_actions']['#options'] = $this->bulkListChapterActions();
+ $form['example']['#options'] = $this->ajaxBulkGetExamples($chapter_default_value);
+ $form['example_actions']['#options'] = $this->bulkListExampleActions();
+ $form['example_files']['#title'] = '';
+ $form['example_files']['#markup'] = '';
+
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_download_chapter' => ['type' => 'html', 'content' => $download_link],
+ '#ajax_selected_chapter_action' => ['type' => 'replace', 'content' => $form['chapter_actions']],
+ '#ajax_selected_example' => ['type' => 'replace', 'content' => $form['example']],
+ '#ajax_download_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_edit_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_example_action' => ['type' => 'html', 'content' => ''],
+ '#ajax_example_files_list' => ['type' => 'replace', 'content' => $form['example_files']],
+ ]);
+ }
+
+ $form['chapter_actions']['#options'] = $this->bulkListChapterActions();
+ $form['example']['#options'] = $this->ajaxBulkGetExamples();
+ $form['example_files']['#title'] = '';
+ $form['example_files']['#markup'] = '';
+ $form['example_actions']['#options'] = $this->bulkListExampleActions();
+
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_download_chapter' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_chapter_action' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_download_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_edit_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_example_files_list' => ['type' => 'replace', 'content' => $form['example_files']],
+ '#ajax_selected_example_action' => ['type' => 'html', 'content' => ''],
+ ]);
+ }
+
+ /**
+ * AJAX callback to refresh example files list when an example is selected.
+ */
+ public function ajaxBulkExampleFilesCallback(array &$form, FormStateInterface $form_state) {
+ $example_list_default_value = $form_state->getValue('example');
+ if ($example_list_default_value > 0) {
+ $query = $this->database->select('textbook_companion_example_files');
+ $query->fields('textbook_companion_example_files');
+ $query->condition('example_id', $example_list_default_value);
+ $example_list_q = $query->execute();
+ if ($example_list_q) {
+ $example_files_rows = [];
+ while ($example_list_data = $example_list_q->fetchObject()) {
+ $example_file_type = '';
+ switch ($example_list_data->filetype) {
+ case 'S':
+ $example_file_type = $this->t('Source or Main file');
+ break;
+ case 'R':
+ $example_file_type = $this->t('Result file');
+ break;
+ case 'X':
+ $example_file_type = $this->t('xcos file');
+ break;
+ default:
+ $example_file_type = $this->t('Unknown');
+ break;
+ }
+ $example_files_rows[] = [
+ Link::fromTextAndUrl($example_list_data->filename, Url::fromUri('internal:/textbook-companion/download/file/' . $example_list_data->id))->toString(),
+ $example_file_type
+ ];
+ }
+
+ $example_files_header = [$this->t('Filename'), $this->t('Type')];
+ $example_files_table = [
+ '#type' => 'table',
+ '#header' => $example_files_header,
+ '#rows' => $example_files_rows,
+ ];
+
+ $form['example_files']['#title'] = $this->t('List of example files');
+ $form['example_files']['#markup'] = $this->renderer->renderPlain($example_files_table);
+ $form['example_actions']['#options'] = $this->bulkListExampleActions();
+
+ $download_link = Link::fromTextAndUrl($this->t('Download Example'), Url::fromUri('internal:/textbook-companion/download/example/' . $example_list_default_value))->toString();
+ $edit_link = Link::fromTextAndUrl($this->t('Edit Example'), Url::fromUri('internal:/code_approval/editcode/' . $example_list_default_value))->toString();
+
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_example_files_list' => ['type' => 'replace', 'content' => $form['example_files']],
+ '#ajax_download_selected_example' => ['type' => 'html', 'content' => $download_link],
+ '#ajax_edit_selected_example' => ['type' => 'html', 'content' => $edit_link],
+ '#ajax_selected_example_action' => ['type' => 'replace', 'content' => $form['example_actions']],
+ ]);
}
- } //$form_state['clicked_button']['#value'] == 'Submit'
+
+ // Example selected but no files query result — empty response (same as before).
+ return $this->ajaxHelper->buildMultiCommandResponse([]);
+ }
+
+ $form['example_files']['#title'] = '';
+ $form['example_files']['#markup'] = '';
+ $form['example_actions']['#options'] = $this->bulkListExampleActions();
+
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_download_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_edit_selected_example' => ['type' => 'html', 'content' => ''],
+ '#ajax_example_files_list' => ['type' => 'replace', 'content' => $form['example_files']],
+ '#ajax_selected_example_action' => ['type' => 'html', 'content' => ''],
+ ]);
+ }
+
+ /**
+ * AJAX callback placeholder for chapter actions.
+ */
+ public function ajaxBulkChapterActionsCallback(array &$form, FormStateInterface $form_state) {
+ return $this->ajaxHelper->buildMultiCommandResponse([]);
+ }
+
+ /**
+ * Get list of books.
+ */
+ protected function bulkListOfBooks() {
+ $book_titles = [
+ '0' => $this->t('Please select...'),
+ ];
+ $query = $this->database->select('textbook_companion_preference', 'pp');
+ $query->join('textbook_companion_proposal', 'p', 'pp.proposal_id=p.id');
+ $query->join('users_field_data', 'u', 'p.uid=u.uid');
+ $query->fields('u', ['name']);
+ $query->fields('pp', ['id', 'book', 'author']);
+
+ $or = $this->database->condition('or');
+ $or->condition('approval_status', 1);
+ $or->condition('approval_status', 3);
+ $query->condition($or);
+ $query->orderBy('book', 'ASC');
+ $book_titles_q = $query->execute();
+ while ($book_titles_data = $book_titles_q->fetchObject()) {
+ $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')' . ' (Proposed by ' . $book_titles_data->name . ')';
+ }
+ return $book_titles;
+ }
+
+ /**
+ * Get list of chapters for selected book.
+ */
+ protected function ajaxBulkGetChapterList($preference_id = 0) {
+ $book_chapters = [
+ '0' => $this->t('Please select...'),
+ ];
+ if ($preference_id > 0) {
+ $query = $this->database->select('textbook_companion_chapter');
+ $query->fields('textbook_companion_chapter');
+ $query->condition('preference_id', $preference_id);
+ $query->orderBy('number', 'ASC');
+ $book_chapters_q = $query->execute();
+ while ($book_chapters_data = $book_chapters_q->fetchObject()) {
+ $book_chapters[$book_chapters_data->id] = $book_chapters_data->number . '. ' . $book_chapters_data->name;
+ }
+ }
+ return $book_chapters;
+ }
+
+ /**
+ * Get list of examples for selected chapter.
+ */
+ protected function ajaxBulkGetExamples($chapter_id = 0) {
+ $book_examples = [
+ '0' => $this->t('Please select...'),
+ ];
+ if ($chapter_id > 0) {
+ $query = $this->database->select('textbook_companion_example');
+ $query->fields('textbook_companion_example');
+ $query->condition('chapter_id', $chapter_id);
+ $book_examples_q = $query->execute();
+ while ($book_examples_data = $book_examples_q->fetchObject()) {
+ $book_examples[$book_examples_data->id] = $book_examples_data->number . ' (' . $book_examples_data->caption . ')';
+ }
+ }
+ return $book_examples;
+ }
+
+ /**
+ * Get book actions.
+ */
+ protected function bulkListBookActions() {
+ return [
+ '0' => $this->t('Please select...'),
+ '1' => $this->t('Approve Entire Book'),
+ '2' => $this->t('Pending Review Entire Book'),
+ '3' => $this->t('Dis-Approve Entire Book (This will delete all the examples in the book)'),
+ '4' => $this->t('Delete Entire Book Including Proposal'),
+ ];
+ }
+
+ /**
+ * Get chapter actions.
+ */
+ protected function bulkListChapterActions() {
+ return [
+ '0' => $this->t('Please select...'),
+ '1' => $this->t('Approve Entire Chapter'),
+ '2' => $this->t('Pending Review Entire Chapter'),
+ '3' => $this->t('Dis-Approve Entire Chapter (This will delete all the examples in the chapter)'),
+ ];
+ }
+
+ /**
+ * Get example actions.
+ */
+ protected function bulkListExampleActions() {
+ return [
+ '0' => $this->t('Please select...'),
+ '1' => $this->t('Approve Example'),
+ '2' => $this->t('Pending Review Example'),
+ '3' => $this->t('Dis-approve Example (This will delete the example)'),
+ ];
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/ChequeContctForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/ChequeContctForm.php
index eca1fa8..79b8fae 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/ChequeContctForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/ChequeContctForm.php
@@ -9,10 +9,51 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class ChequeContctForm extends FormBase {
+ /**
+ * The database connection service.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The current user service.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * Constructs a ChequeContctForm object.
+ *
+ * @param \Drupal\Core\Database\Connection $database
+ * The database connection.
+ * @param \Drupal\Core\Session\AccountProxyInterface $current_user
+ * The current user.
+ */
+ public function __construct(Connection $database, AccountProxyInterface $current_user) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,183 +61,173 @@ public function getFormId() {
return 'cheque_contct_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
-
- /*$preference4_q = db_query("SELECT id FROM {textbook_companion_proposal} WHERE uid=".$user->uid);*/
-
- $query = db_select('textbook_companion_proposal');
- $query->fields('id', ['']);
- $query->condition('uid', $user->uid);
- $result = $query->execute();
- $data = $result->fetchObject();
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $uid = $this->currentUser->id();
- $form1 = $data->id;
+ // Query for logged-in user proposal to pre-populate / check.
+ $form1 = NULL;
+ $data = NULL;
+ if ($uid) {
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->fields('p', ['id', 'how_project']);
+ $query->condition('uid', $uid);
+ $data = $query->execute()->fetchObject();
+ if ($data) {
+ $form1 = $data->id;
+ }
+ }
- if ($user->uid) {
- $form['#redirect'] = FALSE;
+ if ($uid) {
+ $search_term = \Drupal::request()->query->get('search') ?: '';
$form['search'] = [
'#type' => 'textfield',
- '#title' => t('Search'),
+ '#title' => $this->t('Search'),
'#size' => 48,
+ '#default_value' => $search_term,
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Search'),
+ '#value' => $this->t('Search'),
];
$form['cancel'] = [
- '#type' => 'markup',
- '#value' => l(t('Cancel'), ''),
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute(''),
+ '#attributes' => [
+ 'class' => ['button'],
+ ],
];
$form['submit2'] = [
- '#type' => 'markup',
- '#value' => l(t('Generate Report'), 'cheque_contct/report'),
+ '#type' => 'link',
+ '#title' => $this->t('Generate Report'),
+ '#url' => Url::fromRoute('textbook_companion.cheque_report_form'),
'#attributes' => [
- 'id' => 'perm_report'
- ],
+ 'id' => 'perm_report',
+ 'class' => ['button'],
+ ],
];
- /*$search_q = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id)");*/
- $query = db_select('textbook_companion_proposal', 'p');
+ // Query submitted cheques.
+ $query = $this->database->select('textbook_companion_proposal', 'p');
$query->join('textbook_companion_cheque', 'c', 'p.id = c.proposal_id');
- $query->fields('p', ['textbook_companion_proposal']);
- $query->fields('c', ['textbook_companion_cheque']);
+ $query->fields('p', ['full_name']);
+ $query->fields('c', ['proposal_id', 'address_con', 'cheque_no', 'cheque_dispatch_date']);
$query->condition('c.address_con', 'Submitted');
+
+ if (!empty($search_term)) {
+ $query->condition('p.full_name', '%' . $this->database->escapeLike($search_term) . '%', 'LIKE');
+ }
+
$result = $query->execute();
+ $search_rows = [];
while ($search_data = $result->fetchObject()) {
+ $status_url = Url::fromRoute('textbook_companion.cheque_status_form', [
+ 'proposal_id' => $search_data->proposal_id,
+ ]);
+ $status_link = Link::fromTextAndUrl($search_data->full_name, $status_url)->toString();
+
$search_rows[] = [
- l($search_data->full_name, 'cheque_contct/status/' . $search_data->proposal_id),
+ $status_link,
$search_data->address_con,
$search_data->cheque_no,
$search_data->cheque_dispatch_date,
];
}
- if ($search_rows) {
+
+ if (!empty($search_rows)) {
$search_header = [
- 'Name Of The Student',
- 'Application Form Status',
- 'Cheque No',
- 'Cheque Clearance Date',
+ $this->t('Name Of The Student'),
+ $this->t('Application Form Status'),
+ $this->t('Cheque No'),
+ $this->t('Cheque Clearance Date'),
];
- $output .= theme('table', [
- 'headers' => $search_header,
- 'rows' => $search_rows,
- ]);
+
$form['search_results'] = [
'#type' => 'item',
- '#title' => $_POST['search'],
- '#markup' => $output,
+ '#title' => !empty($search_term) ? $this->t('Search results for "@term"', ['@term' => $search_term]) : '',
+ 'table' => [
+ '#type' => 'table',
+ '#header' => $search_header,
+ '#rows' => $search_rows,
+ ],
];
}
else {
$form['search_results'] = [
'#type' => 'item',
- '#title' => t('Search results for "') . $_POST['search'] . '"',
- '#markup' => 'No results found',
+ '#title' => !empty($search_term) ? $this->t('Search results for "@term"', ['@term' => $search_term]) : '',
+ '#markup' => $this->t('No results found'),
];
}
- if ($_POST) {
- $output = '';
- $search_rows = [];
- $search_quert = '';
-
- /*$search_q = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id) AND (p.full_name LIKE '%%%s%%')", $_POST['search']);*/
- $query = db_select('textbook_companion_proposal', 'p');
- $query->join('textbook_companion_cheque', 'c', 'p.id = c.proposal_id');
- $query->fields('p', ['textbook_companion_proposal']);
- $query->fields('c', ['textbook_companion_cheque']);
- $query->condition('c.address_con', 'Submitted');
- $query->condition('p.full_name', '%%' . $_POST['search'] . '%%', 'LIKE');
- $result = $query->execute();
-
-
- while ($search_data = $result->fetchObject()) {
- $search_rows[] = [
- l($search_data->full_name, 'cheque_contct/status/' . $search_data->proposal_id),
- $search_data->address_con,
- $search_data->cheque_no,
- $search_data->cheque_dispatch_date,
- ];
- }
- if ($search_rows) {
- $search_header = [
- 'Name Of The Student',
- 'Application Form Status',
- 'Cheque No',
- 'Cheque Clearance Date',
- ];
- $output .= theme('table', [
- 'headers' => $search_header,
- 'rows' => $search_rows,
- ]);
- $form['search_results'] = [
- '#type' => 'item',
- '#title' => t('Search results for "') . $_POST['search'] . '"',
- '#markup' => $output,
- ];
- }
- else {
- $form['search_results'] = [
- '#type' => 'item',
- '#title' => t('Search results for "') . $_POST['search'] . '"',
- '#markup' => 'No results found',
- ];
- }
- }
+
return $form;
}
else {
- /*$preference5_q = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$form1);
- $data1 = db_fetch_object($preference5_q);*/
- $query = db_select('textbook_companion_paper');
- $query->fields('textbook_companion_paper');
- $query->condition('proposal_id', $form1);
- $result = $query->execute();
- $data1 = $result->fetchObject();
+ $form2 = 0;
+ $form3 = 0;
+ $form4 = 0;
+ $form5 = 0;
+ $form9 = '';
+ $form8 = '';
+ $form10 = '';
+ $form11 = '';
+ $form12 = '';
+ $form13 = '';
- $form2 = $data1->internship_form;
- $form3 = $data1->copyright_form;
- $form4 = $data1->undertaking_form;
- $form5 = $data1->reciept_form;
+ if ($form1) {
+ $query = $this->database->select('textbook_companion_paper', 'p');
+ $query->fields('p');
+ $query->condition('proposal_id', $form1);
+ $data1 = $query->execute()->fetchObject();
- /*$chq_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id=".$form1);
- $data_chq = db_fetch_object($chq_q);*/
+ if ($data1) {
+ $form2 = $data1->internship_form;
+ $form3 = $data1->copyright_form;
+ $form4 = $data1->undertaking_form;
+ $form5 = $data1->reciept_form;
+ }
+
+ $query = $this->database->select('textbook_companion_proposal', 'pr');
+ $query->fields('pr');
+ $query->condition('id', $form1);
+ $data_chq = $query->execute()->fetchObject();
+
+ if ($data_chq) {
+ $form9 = $data_chq->full_name;
+ $form8 = $data ? $data->how_project : '';
+ $form10 = $data_chq->mobile;
+ $form11 = $data_chq->course;
+ $form12 = $data_chq->branch;
+ $form13 = $data_chq->university;
+ }
+ }
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $form1);
- $result = $query->execute();
- $data_chq = $result->fetchObject();
-
- $form9 = $data_chq->full_name;
- $form8 = $data->how_project;
- $form10 = $data_chq->mobile;
- $form11 = $data_chq->course;
- $form12 = $data_chq->branch;
- $form13 = $data_chq->university;
if ($form2 && $form3 && $form4 && $form5) {
$form['full_name'] = [
'#type' => 'textfield',
- '#title' => t('Full Name'),
+ '#title' => $this->t('Full Name'),
'#size' => 30,
'#maxlength' => 50,
'#default_value' => $form9,
];
$form['mobile'] = [
'#type' => 'textfield',
- '#title' => t('Mobile No.'),
+ '#title' => $this->t('Mobile No.'),
'#size' => 30,
'#maxlength' => 15,
'#default_value' => $form10,
];
$form['how_project'] = [
'#type' => 'select',
- '#title' => t('How did you come to know about this project'),
+ '#title' => $this->t('How did you come to know about this project'),
'#options' => [
'eSim Website' => 'eSim Website',
'Friend' => 'Friend',
@@ -209,14 +240,14 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['course'] = [
'#type' => 'textfield',
- '#title' => t('Course'),
+ '#title' => $this->t('Course'),
'#size' => 30,
'#maxlength' => 50,
'#default_value' => $form11,
];
$form['branch'] = [
'#type' => 'select',
- '#title' => t('Department/Branch'),
+ '#title' => $this->t('Department/Branch'),
'#options' => [
'Electrical Engineering' => 'Electrical Engineering',
'Electronics Engineering' => 'Electronics Engineering',
@@ -234,44 +265,52 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
$form['university'] = [
'#type' => 'textfield',
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
'#size' => 30,
'#maxlength' => 100,
'#default_value' => $form13,
];
$form['addressforcheque'] = [
'#type' => 'textfield',
- '#title' => t('Address For Mailing Cheque'),
- //'#required' => TRUE,
- '#size' => 30,
+ '#title' => $this->t('Address For Mailing Cheque'),
+ '#size' => 30,
'#maxlength' => 100,
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
$form['cancel'] = [
'#type' => 'markup',
- '#value' => t('Cancel'),
+ '#markup' => $this->t('Cancel'),
];
}
+
if (!$form2) {
- drupal_set_message(t('Internship Form has not been recieved.'), 'error');
+ $this->messenger()->addError($this->t('Internship Form has not been received.'));
}
if (!$form3) {
- drupal_set_message(t('Copyright Form has not been recieved.'), 'error');
+ $this->messenger()->addError($this->t('Copyright Form has not been received.'));
}
if (!$form4) {
- drupal_set_message(t('Undertaking Form has not been recieved.'), 'error');
+ $this->messenger()->addError($this->t('Undertaking Form has not been received.'));
}
+
return $form;
}
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
-
-}
-
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $uid = $this->currentUser->id();
+ if ($uid) {
+ $search = $form_state->getValue('search');
+ $form_state->setRedirect('textbook_companion.cheque_contct_form', [], [
+ 'query' => ['search' => $search],
+ ]);
+ }
+ }
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/ChequeReportForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/ChequeReportForm.php
new file mode 100644
index 0000000..7c6e06d
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/ChequeReportForm.php
@@ -0,0 +1,111 @@
+database = $database;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'cheque_report_form';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->join('textbook_companion_cheque', 'c', 'p.id = c.proposal_id');
+ $query->fields('p', ['full_name']);
+ $query->fields('c', ['address_con', 'cheque_no', 'cheque_dispatch_date']);
+ $query->condition('c.address_con', 'Submitted');
+ $result = $query->execute();
+
+ $rows = [];
+ while ($search_data = $result->fetchObject()) {
+ $rows[] = [
+ $search_data->full_name,
+ $search_data->address_con,
+ $search_data->cheque_no,
+ $search_data->cheque_dispatch_date,
+ ];
+ }
+
+ if (empty($rows)) {
+ throw new EnforcedResponseException(
+ new StreamedResponse(function () {
+ echo "Couldn't fetch records";
+ }, 200, ['Content-Type' => 'text/plain'])
+ );
+ }
+
+ $headers = [
+ 'Name Of The Student',
+ 'Application Form Status',
+ 'Cheque No',
+ 'Cheque Clearance Date',
+ ];
+
+ $response = new StreamedResponse(function () use ($headers, $rows) {
+ $handle = fopen('php://output', 'w');
+ fputcsv($handle, $headers);
+ foreach ($rows as $row) {
+ fputcsv($handle, $row);
+ }
+ fclose($handle);
+ });
+
+ $response->headers->set('Content-Type', 'text/csv');
+ $response->headers->set('Content-Disposition', 'attachment; filename="Report.csv"');
+ $response->headers->set('Pragma', 'no-cache');
+ $response->headers->set('Expires', '0');
+
+ throw new EnforcedResponseException($response);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/ChequeStatusForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/ChequeStatusForm.php
new file mode 100644
index 0000000..ba289bb
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/ChequeStatusForm.php
@@ -0,0 +1,615 @@
+database = $database;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('entity_type.manager'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'cheque_status_form';
+ }
+
+ /**
+ * Resolves proposal ID from query, route, or path.
+ */
+ protected function resolveProposalId($proposal_id = NULL) {
+ if (empty($proposal_id)) {
+ $proposal_id = \Drupal::request()->query->get('proposal_id')
+ ?? \Drupal::routeMatch()->getParameter('proposal_id');
+ }
+
+ if (empty($proposal_id)) {
+ $parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last = end($parts);
+ if (is_numeric($last)) {
+ $proposal_id = (int) $last;
+ }
+ }
+
+ return $proposal_id;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $proposal_id = NULL) {
+ $proposal_id = $this->resolveProposalId($proposal_id);
+
+ if (empty($proposal_id)) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse(Url::fromRoute('textbook_companion._proposal_all')->toString())
+ );
+ }
+
+ $proposal_data = $this->database->select('textbook_companion_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse(Url::fromRoute('textbook_companion._proposal_all')->toString())
+ );
+ }
+
+ $cheque_data = $this->database->select('textbook_companion_cheque', 'c')
+ ->fields('c')
+ ->condition('proposal_id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$cheque_data) {
+ $this->database->insert('textbook_companion_cheque')
+ ->fields(['proposal_id' => $proposal_id])
+ ->execute();
+ $cheque_data = (object) [
+ 'alt_mobno' => '',
+ 'cheque_no' => '',
+ 'address' => '',
+ 'cheque_amt' => '',
+ 'cheque_sent' => 0,
+ 'cheque_cleared' => 0,
+ 'perm_city' => '',
+ 'perm_state' => '',
+ 'perm_pincode' => '',
+ 'temp_chq_address' => '',
+ 'temp_city' => '',
+ 'temp_state' => '',
+ 'temp_pincode' => '',
+ 'commentf' => '',
+ 't_cheque_amt' => '',
+ 't_cheque_no' => '',
+ ];
+ }
+
+ $proposal_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+
+ $form['proposal_id'] = [
+ '#type' => 'hidden',
+ '#default_value' => $proposal_id,
+ ];
+
+ $form['candidate_detail'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Candidate Details'),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'candidate_detail'],
+ ];
+ $form['candidate_detail']['full_name'] = [
+ '#type' => 'item',
+ '#markup' => $proposal_data->full_name,
+ '#title' => $this->t('Contributor Name'),
+ ];
+ $form['candidate_detail']['email'] = [
+ '#type' => 'item',
+ '#markup' => $proposal_user ? $proposal_user->getEmail() : '',
+ '#title' => $this->t('Email'),
+ ];
+ $form['candidate_detail']['mobile'] = [
+ '#type' => 'item',
+ '#markup' => $proposal_data->mobile,
+ '#title' => $this->t('Mobile'),
+ ];
+ $form['candidate_detail']['alt_mobile'] = [
+ '#type' => 'item',
+ '#markup' => $cheque_data->alt_mobno ?? '',
+ '#title' => $this->t('Alternate Mobile No.'),
+ ];
+
+ $form_data = $this->database->select('textbook_companion_paper', 'p')
+ ->fields('p')
+ ->condition('proposal_id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ $preference_html = '';
+ $preference_q = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')
+ ->condition('proposal_id', $proposal_id)
+ ->orderBy('pref_number', 'ASC')
+ ->execute();
+
+ while ($preference_data = $preference_q->fetchObject()) {
+ if ($preference_data->approval_status == 1) {
+ $preference_html .= '' . $preference_data->book . ' (Written by ' . $preference_data->author . ') - Approved Book ';
+ }
+ else {
+ $preference_html .= '' . $preference_data->book . ' (Written by ' . $preference_data->author . ') ';
+ }
+ }
+ $preference_html .= ' ';
+
+ $form['book_preference_f'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Book Preferences/Application Status'),
+ '#collapsible' => FALSE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'book_preference_f'],
+ ];
+ $form['book_preference_f']['book_preference'] = [
+ '#type' => 'item',
+ '#markup' => $preference_html,
+ '#title' => $this->t('Book Preferences'),
+ ];
+
+ $form_html = '';
+ if (!empty($form_data->internship_form)) {
+ $form_html .= 'Internship Application Form Submitted ';
+ }
+ else {
+ $form_html .= 'Internship Application Form Not Submitted ';
+ }
+ if (!empty($form_data->copyright_form)) {
+ $form_html .= 'Copyright Application Form Submitted ';
+ }
+ else {
+ $form_html .= 'Copyright Application Form Not Submitted ';
+ }
+ if (!empty($form_data->undertaking_form)) {
+ $form_html .= 'Undertaking Application Form Submitted ';
+ }
+ else {
+ $form_html .= 'Undertaking Application Form Not Submitted ';
+ }
+ $form_html .= ' ';
+
+ $form['book_preference_f']['formsubmit'] = [
+ '#type' => 'item',
+ '#markup' => $form_html,
+ '#title' => $this->t('Application Form Status'),
+ ];
+
+ $form['stu_cheque_details'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Student Cheque Details'),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'stu_cheque_details'],
+ ];
+ $form['tea_cheque_details'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Teacher Cheque Details'),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'tea_cheque_details'],
+ ];
+ $form['perm_cheque_address'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Permanent Address'),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'perm_cheque_address'],
+ ];
+ $form['temp_cheque_address'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Temporary Address'),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'temp_cheque_address'],
+ ];
+ $form['cheque_delivery'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Cheque Delivery'),
+ '#collapsible' => FALSE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'cheque_delivery'],
+ ];
+ $form['commentf'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Remark'),
+ '#collapsible' => FALSE,
+ '#collapsed' => FALSE,
+ '#attributes' => ['id' => 'commentf'],
+ ];
+
+ $chqe = $this->database->select('textbook_companion_cheque', 'c')
+ ->fields('c')
+ ->condition('proposal_id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if ($chqe) {
+ $form['stu_cheque_details']['cheque_no'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->cheque_no,
+ '#title' => $this->t('Cheque No'),
+ '#size' => 54,
+ ];
+ $form['tea_cheque_details']['cheque_no_t'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->t_cheque_no,
+ '#title' => $this->t('Cheque No'),
+ '#size' => 54,
+ ];
+ $form['perm_cheque_address']['chq_address'] = [
+ '#type' => 'textarea',
+ '#default_value' => $chqe->address,
+ '#title' => $this->t('Address Street 1'),
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ $form['perm_cheque_address']['perm_city'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->perm_city,
+ '#title' => $this->t('City'),
+ '#size' => 35,
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ $form['perm_cheque_address']['perm_state'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->perm_state,
+ '#title' => $this->t('State'),
+ '#size' => 35,
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ $form['perm_cheque_address']['perm_pincode'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->perm_pincode,
+ '#title' => $this->t('Zip code'),
+ '#size' => 35,
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ $form['stu_cheque_details']['cheq_amt'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->cheque_amt,
+ '#title' => $this->t('Cheque Amount'),
+ '#size' => 54,
+ ];
+ $form['tea_cheque_details']['cheq_amt_t'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->t_cheque_no,
+ '#title' => $this->t('Cheque Amount'),
+ '#size' => 54,
+ ];
+ $form['temp_cheque_address']['temp_chq_address'] = [
+ '#type' => 'textarea',
+ '#default_value' => $chqe->temp_chq_address,
+ '#title' => $this->t('Address Street 1'),
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ $form['temp_cheque_address']['temp_city'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->temp_city,
+ '#title' => $this->t('City'),
+ '#size' => 35,
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ $form['temp_cheque_address']['temp_state'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->temp_state,
+ '#title' => $this->t('State'),
+ '#size' => 35,
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ $form['temp_cheque_address']['temp_pincode'] = [
+ '#type' => 'textfield',
+ '#default_value' => $chqe->temp_pincode,
+ '#title' => $this->t('Zipcode'),
+ '#size' => 35,
+ '#attributes' => ['readonly' => 'readonly'],
+ ];
+ }
+ else {
+ $form['stu_cheque_details']['cheque_no'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('Cheque No'),
+ ];
+ $form['tea_cheque_details']['cheque_no_t'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('Cheque No'),
+ ];
+ $form['perm_cheque_address']['chq_address'] = [
+ '#type' => 'textarea',
+ '#default_value' => '',
+ '#title' => $this->t('Address Street 1'),
+ ];
+ $form['perm_cheque_address']['perm_city'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('City'),
+ '#size' => 35,
+ ];
+ $form['perm_cheque_address']['perm_state'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('State'),
+ '#size' => 35,
+ ];
+ $form['perm_cheque_address']['perm_pincode'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('Zip code'),
+ '#size' => 35,
+ ];
+ $form['perm_cheque_address']['same_address'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Same As Permanent Address'),
+ '#attributes' => ['onclick' => 'copy_address()'],
+ ];
+ $form['stu_cheque_details']['cheq_amt'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('Cheque Amount'),
+ ];
+ $form['tea_cheque_details']['cheq_amt_t'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('Cheque Amount'),
+ ];
+ $form['temp_cheque_address']['temp_chq_address'] = [
+ '#type' => 'textarea',
+ '#default_value' => '',
+ '#title' => $this->t('Address Street 1'),
+ ];
+ $form['temp_cheque_address']['temp_city'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('City'),
+ '#size' => 35,
+ ];
+ $form['temp_cheque_address']['temp_state'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('State'),
+ '#size' => 35,
+ ];
+ $form['temp_cheque_address']['temp_pincode'] = [
+ '#type' => 'textfield',
+ '#default_value' => '',
+ '#title' => $this->t('Zip code'),
+ '#size' => 35,
+ ];
+ $form['temp_cheque_address']['same_address'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Same As Permanent Address'),
+ '#attributes' => ['onclick' => 'copy_address()'],
+ ];
+ }
+
+ $form['cheque_delivery']['cheque_sent'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Cheque Sent'),
+ '#default_value' => $chqe ? $chqe->cheque_sent : 0,
+ '#description' => $this->t('Check if the Cheque has been sent to the user.'),
+ '#attributes' => ['id' => 'cheque_sent'],
+ ];
+ $form['cheque_delivery']['cheque_cleared'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Cheque Cleared'),
+ '#default_value' => $chqe ? $chqe->cheque_cleared : 0,
+ '#description' => $this->t('Check if the Cheque has been Realised to the User Account.'),
+ '#attributes' => ['id' => 'cheque_cleared'],
+ ];
+ $form['commentf']['comment_cheque'] = [
+ '#type' => 'textarea',
+ '#attributes' => ['id' => 'comment'],
+ '#default_value' => $chqe ? $chqe->commentf : '',
+ ];
+
+ if (!$form_data) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse(Url::fromRoute('textbook_companion._proposal_all')->toString())
+ );
+ }
+
+ $form['submit'] = [
+ '#type' => 'submit',
+ '#value' => $this->t('Submit'),
+ ];
+ $form['cancel'] = [
+ '#type' => 'markup',
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Cancel'),
+ Url::fromRoute('textbook_companion._proposal_all')
+ )->toString(),
+ ];
+
+ return $form;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $proposal_id = $form_state->getValue('proposal_id');
+
+ $proposal_data = $this->database->select('textbook_companion_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirectUrl(Url::fromRoute('textbook_companion._proposal_all'));
+ return;
+ }
+
+ $this->database->update('textbook_companion_cheque')
+ ->fields([
+ 'cheque_no' => $form_state->getValue('cheque_no'),
+ 'cheque_amt' => $form_state->getValue('cheq_amt'),
+ 'alt_mobno' => $form_state->getValue('mobileno2'),
+ 'address' => $form_state->getValue('chq_address'),
+ 'perm_city' => $form_state->getValue('perm_city'),
+ 'perm_state' => $form_state->getValue('perm_state'),
+ 'perm_pincode' => $form_state->getValue('perm_pincode'),
+ 'temp_chq_address' => $form_state->getValue('temp_chq_address'),
+ 'temp_city' => $form_state->getValue('temp_city'),
+ 'temp_state' => $form_state->getValue('temp_state'),
+ 'temp_pincode' => $form_state->getValue('temp_pincode'),
+ 'commentf' => $form_state->getValue('comment_cheque'),
+ 't_cheque_no' => $form_state->getValue('cheque_no_t'),
+ 't_cheque_amt' => $form_state->getValue('cheq_amt_t'),
+ ])
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
+ $book_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ $email_to = $book_user ? $book_user->getEmail() : '';
+
+ $empty_book_params = [
+ 'book_title' => '',
+ 'chapter_number' => '',
+ 'chapter_title' => '',
+ 'example_no' => '',
+ ];
+
+ if ($form_state->getValue('cheque_sent') == 1) {
+ $this->database->update('textbook_companion_cheque')
+ ->fields(['cheque_sent' => $form_state->getValue('cheque_sent')])
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
+ $params = [
+ 'cheque_sent' => array_merge($empty_book_params, [
+ 'proposal_id' => $proposal_id,
+ 'user_id' => $proposal_data->uid,
+ ]),
+ ];
+ if (!$this->mailService->sendMail('textbook_companion', 'cheque_sent', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Cheque for Book proposal has been Sent. User has been notified .'));
+ }
+
+ if ($form_state->getValue('cheque_cleared') == 1) {
+ $this->database->update('textbook_companion_cheque')
+ ->fields(['cheque_cleared' => $form_state->getValue('cheque_cleared')])
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
+ $this->messenger()->addStatus($this->t('Cheque Has Been Debited into User Account.'));
+
+ $this->database->update('textbook_companion_cheque')
+ ->fields(['cheque_dispatch_date' => time()])
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+ }
+
+ if ($form_state->getValue('comment_cheque')) {
+ $params = [
+ 'remark' => array_merge($empty_book_params, [
+ 'proposal_id' => $proposal_id,
+ 'user_id' => $proposal_data->uid,
+ ]),
+ 'internshipform' => $empty_book_params,
+ ];
+ if (!$this->mailService->sendMail('textbook_companion', 'remark', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Remark Updated. User has been notified'));
+ }
+ else {
+ if (!$this->mailService->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ (string) $this->t('[Textbook Companion] No remark on cheque details'),
+ (string) $this->t('Dear user,
+
+No remark has been added to your cheque/contact details at this time.
+
+Regards,
+DWSIM TBC Team,
+FOSSEE.')
+ )) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('No Remarks. User has been notified .'));
+ }
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/CodeApprovalForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/CodeApprovalForm.php
index 114e511..4ec2c5d 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/CodeApprovalForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/CodeApprovalForm.php
@@ -9,10 +9,67 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\textbook_companion\Services\MailService;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CodeApprovalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The custom mail service.
+ *
+ * @var \Drupal\textbook_companion\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * Constructs a CodeApprovalForm object.
+ */
+ public function __construct(Connection $database, AccountProxyInterface $current_user, EntityTypeManagerInterface $entity_type_manager, MailService $mail_service) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user'),
+ $container->get('entity_type_manager'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,93 +77,135 @@ public function getFormId() {
return 'code_approval_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- /* get a list of unapproved chapters */
- $chapter_id = arg(3);
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $chapter_id = NULL) {
+ // Robustly extract chapter_id if not directly passed by routing wildcard.
+ if (!$chapter_id) {
+ $chapter_id = \Drupal::routeMatch()->getParameter('chapter_id');
+ }
+ if (!$chapter_id) {
+ $chapter_id = \Drupal::request()->query->get('chapter_id');
+ }
+ if (!$chapter_id) {
+ $path = \Drupal::request()->getPathInfo();
+ $parts = explode('/', trim($path, '/'));
+ $last_part = end($parts);
+ if (is_numeric($last_part)) {
+ $chapter_id = $last_part;
+ }
+ }
+
+ if (!$chapter_id) {
+ $this->messenger()->addError($this->t('Invalid chapter selected.'));
+ $form_state->setRedirect('textbook_companion.code_approval');
+ return [];
+ }
+
+ $query = $this->database->select('textbook_companion_chapter', 'c');
+ $query->fields('c');
$query->condition('id', $chapter_id);
- $pending_chapter_q = $query->execute();
- if ($pending_chapter_data = $pending_chapter_q->fetchObject()) {
- /* get preference data */
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $pending_chapter_data->preference_id);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- /* get proposal data */
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $preference_data->proposal_id);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- } //$pending_chapter_data = $pending_chapter_q->fetchObject()
- else {
- drupal_set_message(t('Invalid chapter selected.'), 'error');
- drupal_goto('textbook-companion/code-approval');
- return;
+ $pending_chapter_data = $query->execute()->fetchObject();
+
+ if (!$pending_chapter_data) {
+ $this->messenger()->addError($this->t('Invalid chapter selected.'));
+ $form_state->setRedirect('textbook_companion.code_approval');
+ return [];
+ }
+
+ /* get preference data */
+ $query = $this->database->select('textbook_companion_preference', 'p');
+ $query->fields('p');
+ $query->condition('id', $pending_chapter_data->preference_id);
+ $preference_data = $query->execute()->fetchObject();
+
+ if (!$preference_data) {
+ $this->messenger()->addError($this->t('Book preference data not found.'));
+ $form_state->setRedirect('textbook_companion.code_approval');
+ return [];
+ }
+
+ /* get proposal data */
+ $query = $this->database->select('textbook_companion_proposal', 'pr');
+ $query->fields('pr');
+ $query->condition('id', $preference_data->proposal_id);
+ $proposal_data = $query->execute()->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger()->addError($this->t('Proposal data not found.'));
+ $form_state->setRedirect('textbook_companion.code_approval');
+ return [];
}
+
$form['#tree'] = TRUE;
$form['contributor'] = [
'#type' => 'item',
'#markup' => $proposal_data->full_name,
- '#title' => t('Contributor Name'),
+ '#title' => $this->t('Contributor Name'),
];
$form['book_details']['book'] = [
'#type' => 'item',
'#markup' => $preference_data->book,
- '#title' => t('Title of the Book'),
+ '#title' => $this->t('Title of the Book'),
];
$form['book_details']['number'] = [
'#type' => 'item',
'#markup' => $pending_chapter_data->number,
- '#title' => t('Chapter Number'),
+ '#title' => $this->t('Chapter Number'),
];
$form['book_details']['name'] = [
'#type' => 'item',
'#markup' => $pending_chapter_data->name,
- '#title' => t('Title of the Chapter'),
+ '#title' => $this->t('Title of the Chapter'),
];
$form['book_details']['back_to_list'] = [
'#type' => 'item',
- '#markup' => l('Back to Code Approval List', 'textbook-companion/code-approval'),
+ '#markup' => Link::fromTextAndUrl($this->t('Back to Code Approval List'), Url::fromRoute('textbook_companion.code_approval'))->toString(),
];
+
/* get example data */
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
+ $query = $this->database->select('textbook_companion_example', 'e');
+ $query->fields('e');
$query->condition('chapter_id', $chapter_id);
$query->condition('approval_status', 0);
$example_q = $query->execute();
+
+ $has_examples = FALSE;
while ($example_data = $example_q->fetchObject()) {
+ $has_examples = TRUE;
$form['example_details'][$example_data->id] = [
'#type' => 'fieldset',
+ '#title' => $this->t('Example Details'),
'#collapsible' => FALSE,
'#collapsed' => TRUE,
];
$form['example_details'][$example_data->id]['example_number'] = [
'#type' => 'item',
'#markup' => $example_data->number,
- '#title' => t('Example Number'),
+ '#title' => $this->t('Example Number'),
];
$form['example_details'][$example_data->id]['example_caption'] = [
'#type' => 'item',
'#markup' => $example_data->caption,
- '#title' => t('Example Caption'),
+ '#title' => $this->t('Example Caption'),
];
+
+ $download_url = Url::fromRoute('textbook_companion.download_example', ['example_id' => $example_data->id]);
$form['example_details'][$example_data->id]['download'] = [
'#type' => 'markup',
- '#markup' => l('Download Example', 'textbook-companion/download/example/' . $example_data->id),
+ '#markup' => Link::fromTextAndUrl($this->t('Download Example'), $download_url)->toString(),
];
$form['example_details'][$example_data->id]['approved'] = [
'#type' => 'radios',
'#options' => [
- 'Approved',
- 'Dis-approved',
+ $this->t('Approved'),
+ $this->t('Dis-approved'),
],
];
$form['example_details'][$example_data->id]['message'] = [
'#type' => 'textfield',
- '#title' => t('Reason for dis-approval'),
+ '#title' => $this->t('Reason for dis-approval'),
];
$form['example_details'][$example_data->id]['example_id'] = [
'#type' => 'hidden',
@@ -117,117 +216,141 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#value' => $example_data->number,
];
}
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => t('Submit'),
- ];
+
+ if ($has_examples) {
+ $form['submit'] = [
+ '#type' => 'submit',
+ '#value' => $this->t('Submit'),
+ ];
+ }
+ else {
+ $form['no_examples'] = [
+ '#type' => 'item',
+ '#markup' => $this->t('No pending examples to approve for this chapter.'),
+ ];
+ }
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- foreach ($form_state->getValue(['example_details']) as $ex_id => $ex_data) {
- if ($ex_data['approved'] == "1") {
- if ($ex_data['message'] == NULL || $ex_data['message'] == '') {
- $form_state->setErrorByName($ex_id . '][message', t('Enter reason for disapproval for experiment no: ' . $ex_data['example_number_hidden']));
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ $example_details = $form_state->getValue('example_details');
+ if ($example_details) {
+ foreach ($example_details as $ex_id => $ex_data) {
+ if ($ex_data['approved'] == "1") {
+ if (empty($ex_data['message'])) {
+ $form_state->setErrorByName("example_details][$ex_id][message", $this->t('Enter reason for disapproval for experiment no: @num', ['@num' => $ex_data['example_number_hidden']]));
+ }
}
}
}
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- foreach ($form_state->getValue(['example_details']) as $ex_id => $ex_data) {
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $current_uid = $this->currentUser->id();
+ $example_details = $form_state->getValue('example_details') ?: [];
+
+ foreach ($example_details as $ex_id => $ex_data) {
+ $query = $this->database->select('textbook_companion_example', 'e');
+ $query->fields('e');
$query->condition('id', $ex_data['example_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $example_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
+ $example_data = $query->execute()->fetchObject();
+
+ if (!$example_data) {
+ continue;
+ }
+
+ $query = $this->database->select('textbook_companion_chapter', 'c');
+ $query->fields('c');
$query->condition('id', $example_data->chapter_id);
- $query->range(0, 1);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
+ $chapter_data = $query->execute()->fetchObject();
+
+ if (!$chapter_data) {
+ continue;
+ }
+
+ $query = $this->database->select('textbook_companion_preference', 'p');
+ $query->fields('p');
$query->condition('id', $chapter_data->preference_id);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
+ $preference_data = $query->execute()->fetchObject();
+
+ if (!$preference_data) {
+ continue;
+ }
+
+ $query = $this->database->select('textbook_companion_proposal', 'pr');
+ $query->fields('pr');
$query->condition('id', $preference_data->proposal_id);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- $user_data = user_load($proposal_data->uid);
- del_book_pdf($preference_data->id);
+ $proposal_data = $query->execute()->fetchObject();
+
+ if (!$proposal_data) {
+ continue;
+ }
+
+ /** @var \Drupal\user\UserInterface $user_data */
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ if (!$user_data) {
+ continue;
+ }
+
+ // Call module function to delete cache/generated PDF.
+ if (function_exists('del_book_pdf')) {
+ del_book_pdf($preference_data->id);
+ }
+
if ($ex_data['approved'] == "0") {
- $query = db_update('textbook_companion_example');
- $query->fields([
- 'approval_status' => 1,
- 'approver_uid' => $user->uid,
- 'approval_date' => time(),
- ]);
- $query->condition('id', $ex_data['example_id']);
- $num_updated = $query->execute();
+ $this->database->update('textbook_companion_example')
+ ->fields([
+ 'approval_status' => 1,
+ 'approver_uid' => $current_uid,
+ 'approval_date' => time(),
+ ])
+ ->condition('id', $ex_data['example_id'])
+ ->execute();
+
/* sending email */
- $email_to = $user_data->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
+ $email_to = $user_data->getEmail();
+ $params = [];
$params['example_approved']['example_id'] = $ex_data['example_id'];
- $params['example_approved']['user_id'] = $user_data->uid;
- $params['example_approved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'example_approved', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ $params['example_approved']['user_id'] = $user_data->id();
+
+ if (!$this->mailService->sendMail('textbook_companion', 'example_approved', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
}
- } //$ex_data['approved'] == "0"
- else {
- if ($ex_data['approved'] == "1") {
+ }
+ elseif ($ex_data['approved'] == "1") {
+ // Call module function to delete example.
+ if (function_exists('delete_example')) {
if (delete_example($ex_data['example_id'])) {
/* sending email */
- $email_to = $user_data->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
+ $email_to = $user_data->getEmail();
+ $params = [];
$params['example_disapproved']['preference_id'] = $chapter_data->preference_id;
$params['example_disapproved']['chapter_id'] = $example_data->chapter_id;
$params['example_disapproved']['example_number'] = $example_data->number;
$params['example_disapproved']['example_caption'] = $example_data->caption;
- $params['example_disapproved']['user_id'] = $user_data->uid;
+ $params['example_disapproved']['user_id'] = $user_data->id();
$params['example_disapproved']['message'] = $ex_data['message'];
- $params['example_disapproved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'example_disapproved', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+
+ if (!$this->mailService->sendMail('textbook_companion', 'example_disapproved', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
}
- } //delete_example($ex_data['example_id'])
+ }
else {
- drupal_set_message('Error disapproving and deleting example. Please contact administrator.', 'error');
+ $this->messenger()->addError($this->t('Error disapproving and deleting example. Please contact administrator.'));
}
}
- } //$ex_data['approved'] == "1"
- } //$form_state['values']['example_details'] as $ex_id => $ex_data
- drupal_set_message('Updated successfully.', 'status');
- drupal_goto('textbook-companion/code-approval');
+ }
+ }
+
+ $this->messenger()->addStatus($this->t('Updated successfully.'));
+ $form_state->setRedirect('textbook_companion.code_approval');
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/ContactDetails.php b/modules/custom/DWSIM_textbook_companion/src/Form/ContactDetails.php
index 829fa3a..4e77b7d 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/ContactDetails.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/ContactDetails.php
@@ -9,10 +9,46 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class ContactDetails extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * Constructs a ContactDetails form object.
+ */
+ public function __construct(Connection $database, AccountProxyInterface $current_user) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,70 +56,66 @@ public function getFormId() {
return 'contact_details';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- if (!isset($_REQUEST['msg'])) {
- drupal_set_message('Caution :Please update Contact Detail carefully as this will be used for future reference during Payment ', 'error');
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $msg = \Drupal::request()->query->get('msg');
+ if ($msg === NULL) {
+ $this->messenger()->addWarning($this->t('Caution: Please update Contact Detail carefully as this will be used for future reference during Payment.'));
}
- $x = $user->uid;
- /*$query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$x);
- $data2 = db_fetch_object($query2);*/
+ $x = $this->currentUser->id();
+ if (!$x) {
+ $this->messenger()->addError($this->t('You must be logged in to view this page.'));
+ return [];
+ }
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->fields('p');
$query->condition('uid', $x);
- $result = $query->execute();
- $data2 = $result->fetchObject();
-
+ $data2 = $query->execute()->fetchObject();
if (!$data2) {
- drupal_set_message('Fill Up The Book Proposal Form ', 'error');
- return '';
+ $proposal_url = Url::fromRoute('textbook_companion.proposal_all')->toString();
+ $form['message'] = [
+ '#type' => 'item',
+ '#markup' => $this->t('Fill Up The Book Proposal Form ', [':url' => $proposal_url]),
+ ];
+ return $form;
}
- /*$query3 = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status=1 AND proposal_id=".$data2->id);
- $data3 = db_fetch_object($query3);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
+ $query = $this->database->select('textbook_companion_preference', 'pref');
+ $query->fields('pref');
$query->condition('approval_status', 1);
$query->condition('proposal_id', $data2->id);
- $result = $query->execute();
- $data3 = $result->fetchObject();
+ $data3 = $query->execute()->fetchObject();
- if (!$data3->approval_status) {
- drupal_set_message('Book Proposal Has Not Been Accpeted .', 'error');
- return '';
+ if (!$data3) {
+ $form['message'] = [
+ '#type' => 'item',
+ '#markup' => $this->t('Book Proposal Has Not Been Accepted.'),
+ ];
+ return $form;
}
$proposal_id = $data2->id;
- /*$comment_qx = db_query("SELECT * FROM textbook_companion_cheque c WHERE proposal_id =".$proposal_id);
- $commentv = db_fetch_object($comment_qx);*/
-
- $query = db_select('textbook_companion_cheque', 'c');
+ $query = $this->database->select('textbook_companion_cheque', 'c');
$query->fields('c');
$query->condition('proposal_id', $proposal_id);
- $result = $query->execute();
- $commentv = $result->fetchObject();
+ $commentv = $query->execute()->fetchObject();
- $form16 = $commentv->commentf;
+ $form16 = $commentv ? $commentv->commentf : '';
$mob_no = $data2->mobile;
$full_name = $data2->full_name;
- /*$query1 = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id);*/
- $query = db_select('textbook_companion_cheque');
- $query->fields('textbook_companion_cheque');
+ $query = $this->database->select('textbook_companion_cheque', 'chq');
+ $query->fields('chq');
$query->condition('proposal_id', $proposal_id);
$result = $query->execute();
$form1 = 0;
- $form2 = 0;
- $form3 = 0;
- $form4 = 0;
- $form5 = 0;
- $form6 = 0;
- $form7 = 0;
$form8 = 0;
$form9 = 0;
$form10 = 0;
@@ -105,19 +137,17 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
$form15 = $data->temp_pincode;
}
else {
- /*db_query("insert into {textbook_companion_cheque} (proposal_id) values(%d)",$proposal_id);*/
-
- $query = "insert into {textbook_companion_cheque} (proposal_id) values (:proposal_id)";
- $args = [":proposal_id" => $proposal_id];
- $result = db_query($query, $args, ['return' => Database::RETURN_INSERT_ID]);
+ $this->database->insert('textbook_companion_cheque')
+ ->fields(['proposal_id' => $proposal_id])
+ ->execute();
}
+
$form['candidate_detail'] = [
'#type' => 'fieldset',
- '#value' => $form_html,
- '#title' => t('Candidate Detail'),
+ '#title' => $this->t('Candidate Detail'),
'#attributes' => [
- 'id' => 'candidate_detail'
- ],
+ 'id' => 'candidate_detail',
+ ],
];
$form['proposal_id'] = [
'#type' => 'hidden',
@@ -125,224 +155,210 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['candidate_detail']['fullname'] = [
'#type' => 'textfield',
- '#title' => t('Full Name'),
+ '#title' => $this->t('Full Name'),
'#size' => 48,
'#default_value' => $full_name,
];
$form['candidate_detail']['email'] = [
'#type' => 'textfield',
- '#title' => t('Email'),
+ '#title' => $this->t('Email'),
'#size' => 48,
- '#value' => $user->mail,
+ '#value' => $this->currentUser->getEmail(),
'#disabled' => TRUE,
];
$form['candidate_detail']['mobileno1'] = [
'#type' => 'textfield',
- '#title' => t('Mobile No'),
+ '#title' => $this->t('Mobile No'),
'#size' => 48,
'#default_value' => $mob_no,
];
$form['candidate_detail']['mobileno2'] = [
'#type' => 'textfield',
- '#title' => t('Alternate Mobile No'),
+ '#title' => $this->t('Alternate Mobile No'),
'#size' => 48,
'#default_value' => $form8,
];
- /*$chq_q=db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id);
- $chq_data=db_fetch_object($chq_q);*/
-
- $query = db_select('textbook_companion_cheque');
- $query->fields('textbook_companion_cheque');
+ $query = $this->database->select('textbook_companion_paper', 'pap');
+ $query->fields('pap');
$query->condition('proposal_id', $proposal_id);
- $result = $query->execute();
- $chq_data = $result->fetchObject();
-
-
- /*$q_form = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$proposal_id);
- $q_data = db_fetch_object($q_form);*/
-
- $query = db_select('textbook_companion_paper');
- $query->fields('textbook_companion_paper');
- $query->condition('proposal_id', $proposal_id);
- $result = $query->execute();
- $q_data = $result->fetchObject();
+ $q_data = $query->execute()->fetchObject();
- $form_html .= '';
- if ($q_data->internship_form) {
- $form_html .= 'Internship Application Form Submitted ';
+ $form_html = '';
+ if ($q_data && $q_data->internship_form) {
+ $form_html .= '' . $this->t('Internship Application') . ' ' . $this->t('Form Submitted') . ' ';
}
else {
- $form_html .= 'Internship Application Form Not Submitted. Please submit it as soon as possible. ';
+ $form_html .= '' . $this->t('Internship Application') . ' ' . $this->t('Form Not Submitted. Please submit it as soon as possible.') . ' ';
}
- if ($q_data->copyright_form) {
- $form_html .= 'Copyright Application Form Submitted ';
+ if ($q_data && $q_data->copyright_form) {
+ $form_html .= '' . $this->t('Copyright Application') . ' ' . $this->t('Form Submitted') . ' ';
}
else {
- $form_html .= 'Copyright Application Form Not Submitted. Please submit it as soon as possible. ';
+ $form_html .= '' . $this->t('Copyright Application') . ' ' . $this->t('Form Not Submitted. Please submit it as soon as possible.') . ' ';
}
- if ($q_data->undertaking_form) {
- $form_html .= 'Undertaking Application Form Submitted ';
+ if ($q_data && $q_data->undertaking_form) {
+ $form_html .= '' . $this->t('Undertaking Application') . ' ' . $this->t('Form Submitted') . ' ';
}
else {
- $form_html .= 'Undertaking Application Form Not Submitted. Please submit it as soon as possible. ';
+ $form_html .= '' . $this->t('Undertaking Application') . ' ' . $this->t('Form Not Submitted. Please submit it as soon as possible.') . ' ';
}
$form_html .= ' ';
+
$form['Application Status'] = [
'#type' => 'fieldset',
- '#value' => $form_html,
- '#title' => t('Application Form Status'),
+ '#markup' => $form_html,
+ '#title' => $this->t('Application Form Status'),
'#attributes' => [
- 'id' => 'app_status'
- ],
+ 'id' => 'app_status',
+ ],
];
+
$form['perm_cheque_address'] = [
'#type' => 'fieldset',
- '#title' => t('Permanent Address'),
+ '#title' => $this->t('Permanent Address'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#attributes' => [
- 'id' => 'perm_cheque_address'
- ],
+ 'id' => 'perm_cheque_address',
+ ],
];
$form['temp_cheque_address'] = [
'#type' => 'fieldset',
- '#title' => t('Temporary Address'),
+ '#title' => $this->t('Temporary Address'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#attributes' => [
- 'id' => 'temp_cheque_address'
- ],
+ 'id' => 'temp_cheque_address',
+ ],
];
$form['perm_cheque_address']['chq_address'] = [
'#type' => 'textarea',
- '#title' => t('Address'),
+ '#title' => $this->t('Address'),
'#size' => 35,
'#default_value' => $form1,
];
$form['perm_cheque_address']['perm_city'] = [
'#type' => 'textfield',
'#default_value' => $form9,
- '#title' => t('City'),
+ '#title' => $this->t('City'),
'#size' => 35,
];
$form['perm_cheque_address']['perm_state'] = [
'#type' => 'textfield',
'#default_value' => $form10,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
'#size' => 35,
];
$form['perm_cheque_address']['perm_pincode'] = [
'#type' => 'textfield',
'#default_value' => $form11,
- '#title' => t('Zip code'),
+ '#title' => $this->t('Zip code'),
'#size' => 35,
];
$form['temp_cheque_address']['temp_chq_address'] = [
'#type' => 'textarea',
'#default_value' => $form12,
- '#title' => t('Address'),
+ '#title' => $this->t('Address'),
'#size' => 35,
];
$form['temp_cheque_address']['temp_city'] = [
'#type' => 'textfield',
'#default_value' => $form13,
- '#title' => t('City'),
+ '#title' => $this->t('City'),
'#size' => 35,
];
$form['temp_cheque_address']['temp_state'] = [
'#type' => 'textfield',
'#default_value' => $form14,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
'#size' => 35,
];
$form['temp_cheque_address']['temp_pincode'] = [
'#type' => 'textfield',
'#default_value' => $form15,
- '#title' => t('Zip code'),
+ '#title' => $this->t('Zip code'),
'#size' => 35,
];
$form['temp_cheque_address']['same_address'] = [
'#type' => 'checkbox',
- '#title' => t('Same As Permanent Address'),
+ '#title' => $this->t('Same As Permanent Address'),
];
- if ($chq_data->commentf) {
+
+ if ($commentv && $commentv->commentf) {
$form['commentu'] = [
'#type' => 'fieldset',
- '#title' => t('Remarks'),
+ '#title' => $this->t('Remarks'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'#attributes' => [
- 'id' => 'comment_cheque'
- ],
+ 'id' => 'comment_cheque',
+ ],
];
$form['commentu']['comment_cheque'] = [
'#type' => 'textarea',
'#size' => 35,
'#default_value' => $form16,
+ '#attributes' => [
+ 'readonly' => 'readonly',
+ ],
];
}
- $form['commentu']['comment_cheque'] ['#attributes']['readonly'] = 'readonly';
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Update'),
+ '#value' => $this->t('Update'),
];
+
$form['cancel'] = [
- '#type' => 'markup',
- '#value' => l(t('Cancel'), 'manage_proposal/all'),
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute('textbook_companion.proposal_all'),
+ '#attributes' => [
+ 'class' => ['button'],
+ ],
];
+
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
-
- $user = \Drupal::currentUser();
- $x = $user->uid;
-
- /*$query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$x);
- $data2 = db_fetch_object($query2);*/
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $x = $this->currentUser->id();
+ if (!$x) {
+ return;
+ }
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->fields('p', ['id']);
$query->condition('uid', $x);
- $result = $query->execute();
- $data2 = $result->fetchObject();
-
-
- /*$query ="UPDATE {textbook_companion_cheque} SET
- alt_mobno = '".$form_state['values']['mobileno2']."' ,
- address = '".$form_state['values']['chq_address']."',
- perm_city = '".$form_state['values']['perm_city']."',
- perm_state = '".$form_state['values']['perm_state']."',
- perm_pincode = '".$form_state['values']['perm_pincode']."',
- temp_chq_address = '".$form_state['values']['temp_chq_address']."',
- temp_city = '".$form_state['values']['temp_city']."',
- temp_state = '".$form_state['values']['temp_state']."',
- temp_pincode = '".$form_state['values']['temp_pincode']."' ,
- address_con = 'Submitted'
- WHERE proposal_id = ".$data2->id;
- db_query($query);*/
-
- $query = db_update('textbook_companion_cheque');
- $query->fields([
- 'alt_mobno' => $form_state[ values ][ mobileno2 ],
- 'address' => $form_state[ values ][ chq_address ],
- 'perm_city' => $form_state[ values ][ perm_city ],
- 'perm_state' => $form_state[ values ][ perm_state ],
- 'perm_pincode' => $form_state[ values ][ perm_pincode ],
- 'temp_chq_address' => $form_state[ values ][ temp_chq_address ],
- 'temp_city' => $form_state[ values ][ temp_city ],
- 'temp_state' => $form_state[ values ][ temp_state ],
- 'temp_pincode' => $form_state[ values ][ temp_pincode ],
- 'address_con' => 'Submitted',
- ]);
- $query->condition('proposal_id', $data2->id);
- $num_updated = $query->execute();
-
- drupal_set_message('Contact Details Has Been Updated.....!', 'status');
- drupal_goto('mycontact', ['msg' => 0], $fragment = NULL, $http_response_code = 302);
+ $data2 = $query->execute()->fetchObject();
+
+ if ($data2) {
+ $this->database->update('textbook_companion_cheque')
+ ->fields([
+ 'alt_mobno' => $form_state->getValue('mobileno2'),
+ 'address' => $form_state->getValue('chq_address'),
+ 'perm_city' => $form_state->getValue('perm_city'),
+ 'perm_state' => $form_state->getValue('perm_state'),
+ 'perm_pincode' => $form_state->getValue('perm_pincode'),
+ 'temp_chq_address' => $form_state->getValue('temp_chq_address'),
+ 'temp_city' => $form_state->getValue('temp_city'),
+ 'temp_state' => $form_state->getValue('temp_state'),
+ 'temp_pincode' => $form_state->getValue('temp_pincode'),
+ 'address_con' => 'Submitted',
+ ])
+ ->condition('proposal_id', $data2->id)
+ ->execute();
+
+ $this->messenger()->addStatus($this->t('Contact Details Has Been Updated.....!'));
+ $form_state->setRedirect('textbook_companion.contact_details', [], [
+ 'query' => ['msg' => 0],
+ ]);
+ }
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/DataentryEditForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/DataentryEditForm.php
new file mode 100644
index 0000000..a8fb797
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/DataentryEditForm.php
@@ -0,0 +1,162 @@
+database = $database;
+ $this->messenger = $messenger;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'dataentry_edit_form';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $id = NULL) {
+ $preference_data = $this->database->select('textbook_companion_preference', 'tcp')
+ ->fields('tcp')
+ ->condition('id', $id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$preference_data) {
+ $this->messenger->addError($this->t('Invalid book preference ID.'));
+ return $form;
+ }
+
+ $form['id'] = [
+ '#type' => 'hidden',
+ '#value' => $id,
+ ];
+
+ $form['book'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Title of the book'),
+ '#size' => 30,
+ '#maxlength' => 100,
+ '#required' => TRUE,
+ '#default_value' => $preference_data->book,
+ ];
+
+ $form['author'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Author Name'),
+ '#size' => 30,
+ '#maxlength' => 100,
+ '#required' => TRUE,
+ '#default_value' => $preference_data->author,
+ ];
+
+ $form['isbn'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('ISBN No'),
+ '#size' => 30,
+ '#maxlength' => 25,
+ '#required' => TRUE,
+ '#attributes' => [
+ 'readonly' => 'readonly',
+ ],
+ '#default_value' => $preference_data->isbn,
+ ];
+
+ $form['publisher'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Publisher & Place'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE,
+ '#default_value' => $preference_data->publisher,
+ ];
+
+ $form['edition'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Edition'),
+ '#size' => 4,
+ '#maxlength' => 2,
+ '#required' => TRUE,
+ '#default_value' => $preference_data->edition,
+ ];
+
+ $form['year'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Year of publication'),
+ '#size' => 4,
+ '#maxlength' => 4,
+ '#required' => TRUE,
+ '#default_value' => $preference_data->year,
+ ];
+
+ $form['submit'] = [
+ '#type' => 'submit',
+ '#value' => $this->t('Submit'),
+ ];
+
+ return $form;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $values = $form_state->getValues();
+
+ $this->database->update('textbook_companion_preference')
+ ->fields([
+ 'book' => $values['book'],
+ 'author' => $values['author'],
+ 'isbn' => $values['isbn'],
+ 'publisher' => $values['publisher'],
+ 'edition' => $values['edition'],
+ 'year' => $values['year'],
+ ])
+ ->condition('id', $values['id'])
+ ->execute();
+
+ $this->messenger->addStatus($this->t('Book details updated successfully'));
+ $form_state->setRedirect('textbook_companion._data_entry_proposal_all');
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/EditChapterTitleForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/EditChapterTitleForm.php
index 9dc50e0..fcc75de 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/EditChapterTitleForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/EditChapterTitleForm.php
@@ -9,10 +9,48 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedResponseException;
class EditChapterTitleForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * Constructs an EditChapterTitleForm object.
+ */
+ public function __construct(Connection $database, AccountProxyInterface $current_user) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,192 +58,172 @@ public function getFormId() {
return 'edit_chapter_title_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /************************ start approve book details ************************/
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $chapter_id = NULL) {
+ $uid = $this->currentUser->id();
+
+ // Query for user proposal.
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->fields('p');
+ $query->condition('uid', $uid);
$query->orderBy('id', 'DESC');
$query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
+ $proposal_data = $query->execute()->fetchObject();
+
if (!$proposal_data) {
- drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error');
- drupal_goto('textbook-companion/code');
- } //!$proposal_data
+ $proposal_url = Url::fromRoute('textbook_companion.proposal_all')->toString();
+ $this->messenger()->addError($this->t('Please submit a proposal .', [':url' => $proposal_url]));
+
+ $redirect_url = Url::fromRoute('textbook_companion.list_chapters')->toString();
+ $response = new RedirectResponse($redirect_url);
+ throw new EnforcedResponseException($response);
+ }
+
if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) {
+ $redirect_url = Url::fromRoute('textbook_companion.list_chapters')->toString();
switch ($proposal_data->proposal_status) {
case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('textbook-companion/code');
- return;
+ $this->messenger()->addStatus($this->t('We have already received your proposal. We will get back to you soon.'));
break;
case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
+ $proposal_url = Url::fromRoute('textbook_companion.proposal_all')->toString();
+ $this->messenger()->addError($this->t('Your proposal has been dis-approved. Please create another proposal here .', [':url' => $proposal_url]));
break;
case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status');
- drupal_goto('textbook-companion/code');
- return;
+ $proposal_url = Url::fromRoute('textbook_companion.proposal_all')->toString();
+ $this->messenger()->addStatus($this->t('Congratulations! You have completed your last book proposal. You have to create another proposal here .', [':url' => $proposal_url]));
break;
default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
+ $this->messenger()->addError($this->t('Invalid proposal state. Please contact site administrator for further information.'));
break;
- } //$proposal_data->proposal_status
- } //$proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
+ }
+ $response = new RedirectResponse($redirect_url);
+ throw new EnforcedResponseException($response);
+ }
+
+ // Query preference details.
+ $query = $this->database->select('textbook_companion_preference', 'pref');
+ $query->fields('pref');
$query->condition('proposal_id', $proposal_data->id);
$query->condition('approval_status', 1);
$query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
+ $preference_data = $query->execute()->fetchObject();
+
if (!$preference_data) {
- drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //!$preference_data
- /************************ end approve book details **************************/
- $chapter_id = arg(4);
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d", $chapter_id, $preference_data->id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
+ $this->messenger()->addError($this->t('Invalid Book Preference status. Please contact site administrator for further information.'));
+ $redirect_url = Url::fromRoute('textbook_companion.list_chapters')->toString();
+ $response = new RedirectResponse($redirect_url);
+ throw new EnforcedResponseException($response);
+ }
+
+ // Robustly extract chapter_id from parameter, query or path fallback.
+ if (!$chapter_id) {
+ $chapter_id = \Drupal::routeMatch()->getParameter('chapter_id');
+ }
+ if (!$chapter_id) {
+ $chapter_id = \Drupal::request()->query->get('chapter_id');
+ }
+ if (!$chapter_id) {
+ $path = \Drupal::request()->getPathInfo();
+ $parts = explode('/', trim($path, '/'));
+ $last_part = end($parts);
+ if (is_numeric($last_part)) {
+ $chapter_id = $last_part;
+ }
+ }
+
+ if (!$chapter_id) {
+ $this->messenger()->addError($this->t('Invalid chapter.'));
+ $redirect_url = Url::fromRoute('textbook_companion.list_chapters')->toString();
+ $response = new RedirectResponse($redirect_url);
+ throw new EnforcedResponseException($response);
+ }
+
+ // Query chapter details.
+ $query = $this->database->select('textbook_companion_chapter', 'c');
+ $query->fields('c');
$query->condition('id', $chapter_id);
$query->condition('preference_id', $preference_data->id);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
+ $chapter_data = $query->execute()->fetchObject();
+
if (!$chapter_data) {
- drupal_set_message(t('Invalid chapter.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //!$chapter_data
- $form['#redirect'] = 'textbook-companion/code';
+ $this->messenger()->addError($this->t('Invalid chapter.'));
+ $redirect_url = Url::fromRoute('textbook_companion.list_chapters')->toString();
+ $response = new RedirectResponse($redirect_url);
+ throw new EnforcedResponseException($response);
+ }
+
$form['book_details']['book'] = [
'#type' => 'item',
'#markup' => $preference_data->book,
- '#title' => t('Title of the Book'),
+ '#title' => $this->t('Title of the Book'),
];
$form['contributor_name'] = [
'#type' => 'item',
'#markup' => $proposal_data->full_name,
- '#title' => t('Contributor Name'),
+ '#title' => $this->t('Contributor Name'),
];
$form['number'] = [
'#type' => 'item',
- '#title' => t('Chapter No'),
+ '#title' => $this->t('Chapter No'),
'#markup' => $chapter_data->number,
];
$form['chapter_title'] = [
'#type' => 'textfield',
- '#title' => t('Title of the Chapter'),
+ '#title' => $this->t('Title of the Chapter'),
'#size' => 40,
'#maxlength' => 255,
'#required' => TRUE,
'#default_value' => $chapter_data->name,
];
+
+ $form['chapter_id'] = [
+ '#type' => 'value',
+ '#value' => $chapter_id,
+ ];
+
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
$form['cancel'] = [
- '#type' => 'markup',
- '#value' => l(t('Cancel'), 'textbook_companion/code'),
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute('textbook_companion.list_chapters'),
+ '#attributes' => [
+ 'class' => ['button'],
+ ],
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if (!check_name($form_state->getValue(['chapter_title']))) {
- $form_state->setErrorByName('chapter_title', t('Title of the Chapter can contain only alphabets, numbers and spaces.'));
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (function_exists('check_name')) {
+ if (!check_name($form_state->getValue('chapter_title'))) {
+ $form_state->setErrorByName('chapter_title', $this->t('Title of the Chapter can contain only alphabets, numbers and spaces.'));
+ }
}
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /************************ start approve book details ************************/
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- if (!$proposal_data) {
- drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error');
- drupal_goto('textbook-companion/code');
- } //!$proposal_data
- if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) {
- switch ($proposal_data->proposal_status) {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('textbook-companion/code');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status');
- drupal_goto('textbook-companion/code');
- return;
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_data->id);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if (!$preference_data) {
- drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error');
- drupal_goto('textbook-companion/code');
- return;
- } //!$preference_data
- /************************ end approve book details **************************/
- $chapter_id = arg(4);
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d", $chapter_id, $preference_data->id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $chapter_id);
- $query->condition('preference_id', $preference_data->id);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- if (!$chapter_data) {
- drupal_set_message(t('Invalid chapter.'), 'error');
- drupal_goto('textbookcompanion/code');
- return;
- } //!$chapter_data
- /*db_query("UPDATE {textbook_companion_chapter} SET name = '%s' WHERE id = %d", $form_state['values']['chapter_title'], $chapter_id);*/
- $query = db_update('textbook_companion_chapter');
- $query->fields(['name' => $form_state->getValue(['chapter_title'])]);
- $query->condition('id', $chapter_id);
- $num_updated = $query->execute();
- drupal_set_message(t('Title of the Chapter updated.'), 'status');
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $chapter_id = $form_state->getValue('chapter_id');
+
+ $this->database->update('textbook_companion_chapter')
+ ->fields(['name' => $form_state->getValue('chapter_title')])
+ ->condition('id', $chapter_id)
+ ->execute();
+
+ $this->messenger()->addStatus($this->t('Title of the Chapter updated.'));
+ $form_state->setRedirect('textbook_companion.list_chapters');
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/EditCodeSubmissionForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/EditCodeSubmissionForm.php
index afc0fb7..5a23258 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/EditCodeSubmissionForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/EditCodeSubmissionForm.php
@@ -9,10 +9,68 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\textbook_companion\Services\MailService;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedResponseException;
class EditCodeSubmissionForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The custom mail service.
+ *
+ * @var \Drupal\textbook_companion\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * Constructs an EditCodeSubmissionForm object.
+ */
+ public function __construct(Connection $database, AccountProxyInterface $current_user, EntityTypeManagerInterface $entity_type_manager, MailService $mail_service) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user'),
+ $container->get('entity_type_manager'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,53 +78,93 @@ public function getFormId() {
return 'edit_code_submission_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state, $preference_id = NULL) {
- /* get current proposal */
- $preference_id = arg(4);
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $preference_id = NULL) {
+ // Robustly extract preference_id from parameter, routeMatch, query or path fallback.
+ if (!$preference_id) {
+ $preference_id = \Drupal::routeMatch()->getParameter('preference_id');
+ }
+ if (!$preference_id) {
+ $preference_id = \Drupal::request()->query->get('preference_id');
+ }
+ if (!$preference_id) {
+ $path = \Drupal::request()->getPathInfo();
+ $parts = explode('/', trim($path, '/'));
+ $last_part = end($parts);
+ if (is_numeric($last_part)) {
+ $preference_id = $last_part;
+ }
+ }
+
+ if (!$preference_id) {
+ $this->messenger()->addError($this->t('Invalid book selected. Please try again.'));
+ // Redirect back to list page if route exists, else front page.
+ $redirect_url = Url::fromRoute('')->toString();
+ try {
+ $redirect_url = Url::fromRoute('textbook_companion.edit_code_submission_form')->toString();
+ }
+ catch (\Exception $e) {
+ // Fallback if route not compiled yet
+ }
+ $response = new RedirectResponse($redirect_url);
+ throw new EnforcedResponseException($response);
+ }
+
+ $query = $this->database->select('textbook_companion_preference', 'pref');
+ $query->fields('pref');
$query->condition('id', $preference_id);
$preference_data = $query->execute()->fetchObject();
+
if (!$preference_data) {
- drupal_set_message(t('Invalid book selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/code-approval/edit-code-submission');
- return;
- } //!$preference_data
+ $this->messenger()->addError($this->t('Invalid book selected. Please try again.'));
+ $redirect_url = Url::fromRoute('')->toString();
+ try {
+ $redirect_url = Url::fromRoute('textbook_companion.edit_code_submission_form')->toString();
+ }
+ catch (\Exception $e) {
+ // Fallback
+ }
+ $response = new RedirectResponse($redirect_url);
+ throw new EnforcedResponseException($response);
+ }
+
$form = [];
$form['book'] = [
'#type' => 'item',
- '#title' => t('Title of the book'),
+ '#title' => $this->t('Title of the book'),
'#markup' => $preference_data->book,
];
$form['author'] = [
'#type' => 'item',
- '#title' => t('Author Name'),
+ '#title' => $this->t('Author Name'),
'#markup' => $preference_data->author,
];
$form['isbn'] = [
'#type' => 'item',
- '#title' => t('ISBN No'),
+ '#title' => $this->t('ISBN No'),
'#markup' => $preference_data->isbn,
];
$form['publisher'] = [
'#type' => 'item',
- '#title' => t('Publisher & Place'),
+ '#title' => $this->t('Publisher & Place'),
'#markup' => $preference_data->publisher,
];
$form['edition'] = [
'#type' => 'item',
- '#title' => t('Edition'),
+ '#title' => $this->t('Edition'),
'#markup' => $preference_data->edition,
];
$form['year'] = [
'#type' => 'item',
- '#title' => t('Year of pulication'),
+ '#title' => $this->t('Year of publication'),
'#markup' => $preference_data->year,
];
$form['all_example_submitted'] = [
'#type' => 'checkbox',
- '#title' => t('Enable code submission interface for user'),
- '#description' => 'Once you have submited this option user can upload more examples.',
+ '#title' => $this->t('Enable code submission interface for user'),
+ '#description' => $this->t('Once you have submitted this option user can upload more examples.'),
'#required' => TRUE,
];
$form['hidden_preference_id'] = [
@@ -75,64 +173,92 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
- $form['cancle'] = [
- '#type' => 'item',
- '#markup' => l('Cancle', 'textbook-companion/code-approval/edit-code-submission'),
+
+ $cancel_url = Url::fromRoute('');
+ try {
+ $cancel_url = Url::fromRoute('textbook_companion.edit_code_submission_form');
+ }
+ catch (\Exception $e) {
+ // Fallback
+ }
+
+ $form['cancel'] = [
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => $cancel_url,
+ '#attributes' => [
+ 'class' => ['button'],
+ ],
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if ($form_state->getValue(['all_example_submitted']) != 1) {
- $form_state->setErrorByName('all_example_submitted', t('Please check the field if you are intrested to submit the all uploaded examples for review!'));
- } //$form_state['values']['all_example_submitted'] != 1
- return;
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if ($form_state->getValue('all_example_submitted') != 1) {
+ $form_state->setErrorByName('all_example_submitted', $this->t('Please check the field if you are interested to submit all uploaded examples for review!'));
+ }
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- if ($form_state->getValue(['all_example_submitted']) == 1) {
- if (db_query('UPDATE textbook_companion_preference SET submited_all_examples_code = 0 WHERE id = :preference_id', [
- ':preference_id' => $form_state->getValue(['hidden_preference_id'])
- ])) {
- $query = ("SELECT proposal_id FROM textbook_companion_preference WHERE id= :preference_id");
- $args = [
- ":preference_id" => $form_state->getValue(['hidden_preference_id'])
- ];
- $proposal_data = db_query($query, $args);
- $proposal_data_result = $proposal_data->fetchObject();
- $proposal_query = db_select('textbook_companion_proposal');
- $proposal_query->fields('textbook_companion_proposal');
- $proposal_query->condition('proposal_status', 1);
- $proposal_query->condition('id', $proposal_data_result->proposal_id);
- $proposal_data_query = $proposal_query->execute()->fetchObject();
- /* sending email */
- $book_user = user_load($proposal_data_query->uid);
- $email_to = $book_user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $params['all_code_submitted_status_changed']['proposal_id'] = $proposal_data_result->proposal_id;
- $params['all_code_submitted_status_changed']['user_id'] = $user->uid;
- $params['all_code_submitted_status_changed']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'all_code_submitted_status_changed', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $current_uid = $this->currentUser->id();
+ $preference_id = $form_state->getValue('hidden_preference_id');
+
+ if ($form_state->getValue('all_example_submitted') == 1) {
+ $updated = $this->database->update('textbook_companion_preference')
+ ->fields(['submited_all_examples_code' => 0])
+ ->condition('id', $preference_id)
+ ->execute();
+
+ if ($updated) {
+ $query = $this->database->select('textbook_companion_preference', 'p');
+ $query->fields('p', ['proposal_id']);
+ $query->condition('id', $preference_id);
+ $proposal_data_result = $query->execute()->fetchObject();
+
+ if ($proposal_data_result) {
+ $proposal_query = $this->database->select('textbook_companion_proposal', 'pr');
+ $proposal_query->fields('pr');
+ $proposal_query->condition('proposal_status', 1);
+ $proposal_query->condition('id', $proposal_data_result->proposal_id);
+ $proposal_data_query = $proposal_query->execute()->fetchObject();
+
+ if ($proposal_data_query) {
+ /** @var \Drupal\user\UserInterface $book_user */
+ $book_user = $this->entityTypeManager->getStorage('user')->load($proposal_data_query->uid);
+ if ($book_user) {
+ $email_to = $book_user->getEmail();
+ $params = [];
+ $params['all_code_submitted_status_changed']['proposal_id'] = $proposal_data_result->proposal_id;
+ $params['all_code_submitted_status_changed']['user_id'] = $current_uid;
+
+ if (!$this->mailService->sendMail('textbook_companion', 'all_code_submitted_status_changed', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ }
+ }
}
- drupal_set_message('Enabled code submission interface for user');
- drupal_goto('textbook-companion/code-approval/edit-code-submission');
- } //db_query('UPDATE textbook_companion_preference SET submited_all_examples_code = 0 WHERE id = :preference_id', array( ':preference_id' => $form_state['values']['hidden_preference_id'] ))
- } //$form_state['values']['all_example_submitted'] == 1
+
+ $this->messenger()->addStatus($this->t('Enabled code submission interface for user'));
+ }
+ }
+
+ $redirect_route = 'textbook_companion.code_approval';
+ try {
+ $redirect_route = 'textbook_companion.edit_code_submission_form';
+ }
+ catch (\Exception $e) {
+ // Fallback
+ }
+ $form_state->setRedirect($redirect_route);
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/GeneratePdf.php b/modules/custom/DWSIM_textbook_companion/src/Form/GeneratePdf.php
new file mode 100644
index 0000000..33db21b
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/GeneratePdf.php
@@ -0,0 +1,331 @@
+connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $routeMatch;
+ $this->moduleList = $moduleList;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match'),
+ $container->get('extension.list.module')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'generate_pdf';
+ }
+
+ /**
+ * Resolves proposal ID from route, query, or path.
+ */
+ protected function resolveProposalId($proposal_id = NULL) {
+ if (empty($proposal_id)) {
+ $proposal_id = \Drupal::request()->query->get('proposal_id')
+ ?? $this->routeMatch->getParameter('proposal_id');
+ }
+
+ if (empty($proposal_id)) {
+ $parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last = end($parts);
+ if (is_numeric($last)) {
+ $proposal_id = (int) $last;
+ }
+ }
+
+ return $proposal_id;
+ }
+
+ /**
+ * Generates a random string for QR code verification.
+ */
+ private function generateRandomString($length = 5) {
+ $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ $charactersLength = strlen($characters);
+ $randomString = '';
+ for ($i = 0; $i < $length; $i++) {
+ $randomString .= $characters[rand(0, $charactersLength - 1)];
+ }
+ return $randomString;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $proposal_id = NULL) {
+ $mpath = $this->moduleList->getPath('textbook_companion');
+ require $mpath . '/pdf/fpdf/fpdf.php';
+ require $mpath . '/pdf/phpqrcode/qrlib.php';
+
+ $uid = $this->currentUser->id();
+ $proposal_id = $this->resolveProposalId($proposal_id);
+
+ $data2 = $this->connection->select('textbook_companion_preference', 'p')
+ ->fields('p')
+ ->condition('approval_status', 1)
+ ->condition('proposal_id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ $data3 = $this->connection->select('textbook_companion_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->condition('proposal_status', 3)
+ ->execute()
+ ->fetchObject();
+
+ if ($data3) {
+ if ($data3->uid != $uid) {
+ $this->messenger->addError($this->t('Certificate is not available'));
+ return [];
+ }
+ }
+
+ $data4 = $this->connection->query(
+ "SELECT COUNT(tce.id) AS example_count
+ FROM {textbook_companion_example} tce
+ LEFT JOIN {textbook_companion_chapter} tcc ON tce.chapter_id = tcc.id
+ LEFT JOIN {textbook_companion_preference} tcpe ON tcc.preference_id = tcpe.id
+ LEFT JOIN {textbook_companion_proposal} tcpo ON tcpe.proposal_id = tcpo.id
+ WHERE tcpo.proposal_status = 3
+ AND tce.approval_status = 1
+ AND tcpo.id = :prop_id",
+ [':prop_id' => $proposal_id]
+ )->fetchObject();
+
+ if (!$data4 || $data4->example_count == 0) {
+ $this->messenger->addError($this->t('Certificate is not available'));
+ return [];
+ }
+
+ $number_of_example = $data4->example_count;
+ $gender = [
+ 'salutation' => 'Mr. /Ms.',
+ 'gender' => 'He/She',
+ ];
+ if ($data3 && $data3->gender) {
+ if ($data3->gender == 'M') {
+ $gender = [
+ 'salutation' => 'Mr.',
+ 'gender' => 'He',
+ ];
+ }
+ else {
+ $gender = [
+ 'salutation' => 'Ms.',
+ 'gender' => 'She',
+ ];
+ }
+ }
+
+ $pdf = new \FPDF('L', 'mm', 'Letter');
+ $pdf->AddPage();
+ $image_bg = $mpath . '/pdf/images/bg.png';
+ $pdf->Image($image_bg, 0, 0, $pdf->w, $pdf->h);
+ $pdf->SetMargins(18, 1, 18);
+ $path = $mpath;
+ $pdf->Ln(15);
+ $pdf->Ln(20);
+ $pdf->SetFont('Arial', 'BI', 25);
+ $pdf->SetTextColor(139, 69, 19);
+ $pdf->Cell(240, 8, 'Certificate of Participation', '0', 1, 'C');
+ $pdf->Ln(4);
+ $pdf->SetFont('Arial', 'BI', 12);
+ $pdf->SetTextColor(0, 0, 0);
+ $pdf->Cell(240, 8, 'This is to certify that', '0', '1', 'C');
+ $pdf->Ln(4);
+ $pdf->SetFont('Arial', 'BI', 25);
+ $pdf->SetTextColor(139, 69, 19);
+ $pdf->Cell(240, 8, $data3->full_name, '0', '1', 'C');
+ $pdf->Ln(5);
+ $pdf->SetFont('Arial', 'I', 12);
+ if (strtolower($data3->branch) != 'others') {
+ $pdf->SetTextColor(0, 0, 0);
+ $pdf->MultiCell(240, 8, 'from ' . $data3->university . ' has successfully', '0', 'C');
+ $pdf->Ln(0);
+ $pdf->Cell(240, 8, 'completed Internship under DWSIM Textbook Companion', '0', '1', 'C');
+ $pdf->Ln(0);
+ $pdf->Cell(240, 8, 'He/she has coded ' . $number_of_example . ' solved examples using DWSIM from the', '0', '1', 'C');
+ $pdf->Ln(0);
+ $pdf->MultiCell(240, 8, 'Book: ' . $data2->book . ', Author: ' . $data2->author . '.', '0', 'C');
+ $pdf->Ln(0);
+ }
+ else {
+ $pdf->SetTextColor(0, 0, 0);
+ $pdf->Cell(240, 8, 'from ' . $data3->university . ' has successfully', '0', '1', 'C');
+ $pdf->Ln(0);
+ $pdf->Cell(240, 8, 'completed Internship under DWSIM Textbook Companion', '0', '1', 'C');
+ $pdf->Ln(0);
+ $pdf->Cell(240, 8, 'He/she has coded ' . $number_of_example . ' solved examples using DWSIM from the', '0', '1', 'C');
+ $pdf->Ln(0);
+ $pdf->Cell(240, 8, 'Book: ' . $data2->book . ', Author: ' . $data2->author . '.', '0', '1', 'C');
+ $pdf->Ln(0);
+ }
+
+ $tempDir = $path . '/pdf/temp_prcode/';
+ $data = $this->connection->select('textbook_companion_qr_code', 'q')
+ ->fields('q')
+ ->condition('proposal_id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ $DBString = $data ? $data->qr_code : '';
+ if ($DBString == '' || $DBString == 'null') {
+ $UniqueString = $this->generateRandomString();
+ $this->connection->insert('textbook_companion_qr_code')
+ ->fields([
+ 'proposal_id' => $proposal_id,
+ 'qr_code' => $UniqueString,
+ ])
+ ->execute();
+ }
+ else {
+ $UniqueString = $DBString;
+ }
+
+ $codeContents = 'http://dwsim.fossee.in/textbook-companion/certificates/verify/' . $UniqueString;
+ $fileName = 'generated_qrcode.png';
+ $pngAbsoluteFilePath = $tempDir . $fileName;
+ \QRcode::png($codeContents, $pngAbsoluteFilePath);
+ $pdf->Cell(240, 4, '', '0', '1', 'C');
+ $pdf->SetX(95);
+ $pdf->write(0, 'The work done is available at ');
+ $pdf->SetFont('', 'U');
+ $pdf->SetTextColor(139, 69, 19);
+ $pdf->write(0, 'http://dwsim.fossee.in/', 'http://dwsim.fossee.in/');
+ $pdf->SetFont('', '');
+ $pdf->SetTextColor(0, 0, 0);
+ $pdf->write(0, '.', '.');
+ $pdf->Ln(5);
+ $pdf->SetX(198);
+ $pdf->SetFont('', '');
+ $pdf->SetTextColor(0, 0, 0);
+ $pdf->SetY(-85);
+ $pdf->SetX(200);
+ $pdf->SetTextColor(0, 0, 0);
+ $pdf->SetFont('', '');
+ $sign = $path . '/pdf/images/sign.png';
+ $pdf->Image($sign, $pdf->GetX() - 20, $pdf->GetY(), 75, 0);
+ $pdf->SetX(29);
+ $pdf->SetFont('Arial', 'B', 10);
+ $pdf->SetY(-58);
+ $pdf->SetX(28);
+ $pdf->Cell(0, 2, $UniqueString, 0, 0, 'C');
+ $pdf->SetX(29);
+ $pdf->SetY(-50);
+ $image4 = $path . '/pdf/images/verify_content.png';
+ $pdf->SetY(-50);
+ $pdf->SetX(80);
+ $image3 = $path . '/pdf/images/mhrd.png';
+ $image2 = $path . '/pdf/images/fossee.png';
+ $pdf->Image($image2, $pdf->GetX() - 15, $pdf->GetY() + 7, 40, 0);
+ $pdf->Image($pngAbsoluteFilePath, $pdf->GetX() + 50, $pdf->GetY() - 5, 30, 0);
+ $pdf->Image($image3, $pdf->GetX() + 110, $pdf->GetY() + 3, 40, 0);
+ $pdf->Image($image4, $pdf->GetX() - 15, $pdf->GetY() + 28, 150, 0);
+ $pdf->SetFont('Arial', 'I', 8);
+ $pdf->SetTextColor(0, 0, 0);
+ $filename = str_replace(' ', '-', $data3->full_name) . '-DWSIM-Textbook-Certificate.pdf';
+ $file = $path . '/pdf/temp_certificate/' . $proposal_id . '_' . $filename;
+ $pdf->Output($file, 'F');
+
+ header('Content-Type: application/octet-stream');
+ header('Content-Disposition: attachment; filename=' . $filename);
+ header('Content-Type: application/download');
+ header('Content-Description: File Transfer');
+ header('Content-Length: ' . filesize($file));
+ flush();
+ $fp = fopen($file, 'r');
+ while (!feof($fp)) {
+ echo fread($fp, 65536);
+ flush();
+ }
+ fclose($fp);
+ unlink($file);
+
+ return [];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/PaperSubmissionForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/PaperSubmissionForm.php
new file mode 100644
index 0000000..efb8e6d
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/PaperSubmissionForm.php
@@ -0,0 +1,333 @@
+database = $database;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->mailService = $mail_service;
+ $this->routeProvider = $route_provider;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('entity_type.manager'),
+ $container->get('textbook_companion.mail_service'),
+ $container->get('router.route_provider')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'paper_submission_form';
+ }
+
+ /**
+ * Resolves proposal ID from query, route, or path.
+ */
+ protected function resolveProposalId($proposal_id = NULL) {
+ if (empty($proposal_id)) {
+ $proposal_id = \Drupal::request()->query->get('proposal_id')
+ ?? \Drupal::routeMatch()->getParameter('proposal_id');
+ }
+
+ if (empty($proposal_id)) {
+ $parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last = end($parts);
+ if (is_numeric($last)) {
+ $proposal_id = (int) $last;
+ }
+ }
+
+ return $proposal_id;
+ }
+
+ /**
+ * Returns manage-proposals URL or front if route is missing.
+ */
+ protected function getManageProposalsUrl(): Url {
+ try {
+ $this->routeProvider->getRouteByName('textbook_companion._proposal_all');
+ return Url::fromRoute('textbook_companion._proposal_all');
+ }
+ catch (RouteNotFoundException $e) {
+ return Url::fromRoute('');
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $proposal_id = NULL) {
+ $proposal_id = $this->resolveProposalId($proposal_id);
+
+ if (empty($proposal_id)) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse($this->getManageProposalsUrl()->toString())
+ );
+ }
+
+ $query = $this->database->select('textbook_companion_paper', 'p');
+ $query->fields('p');
+ $query->condition('proposal_id', $proposal_id);
+ $data = $query->execute()->fetchObject();
+
+ $form1 = 0;
+ $form2 = 0;
+ $form3 = 0;
+ $form4 = 0;
+
+ if ($data) {
+ $form1 = $data->internship_form;
+ $form2 = $data->copyright_form;
+ $form3 = $data->undertaking_form;
+ $form4 = $data->reciept_form;
+ }
+ else {
+ $this->database->insert('textbook_companion_paper')
+ ->fields(['proposal_id' => $proposal_id])
+ ->execute();
+ }
+
+ $form['proposal_id'] = [
+ '#type' => 'hidden',
+ '#default_value' => $proposal_id,
+ ];
+ $form['internshipform'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Recieved Internship Application'),
+ '#description' => $this->t('Check if the Internship Application has been recieved.'),
+ '#default_value' => $form1,
+ ];
+ $form['copyrighttransferform'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Recieved Copyright Transfer Form'),
+ '#description' => $this->t('Check if the Copyright Transfer Form has been recieved.'),
+ '#default_value' => $form2,
+ ];
+ $form['undertakingform'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Recieved Undertaking Form'),
+ '#description' => $this->t('Check if the Undertaking Form has been recieved.'),
+ '#default_value' => $form3,
+ ];
+ $form['recieptform'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Recieved Reciept Form'),
+ '#description' => $this->t('Check if the Reciept Form has been recieved.'),
+ '#default_value' => $form4,
+ ];
+ $form['submit'] = [
+ '#type' => 'submit',
+ '#value' => $this->t('Send Email'),
+ ];
+ $form['cancel'] = [
+ '#type' => 'markup',
+ '#markup' => Link::fromTextAndUrl($this->t('Cancel'), $this->getManageProposalsUrl())->toString(),
+ ];
+
+ return $form;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $proposal_id = $form_state->getValue('proposal_id');
+
+ $this->database->update('textbook_companion_paper')
+ ->fields([
+ 'internship_form' => $form_state->getValue('internshipform'),
+ 'copyright_form' => $form_state->getValue('copyrighttransferform'),
+ 'undertaking_form' => $form_state->getValue('undertakingform'),
+ 'reciept_form' => $form_state->getValue('recieptform'),
+ ])
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
+ $proposal_data = $this->database->select('textbook_companion_proposal', 'p')
+ ->fields('p')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirectUrl($this->getManageProposalsUrl());
+ return;
+ }
+
+ $book_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ $email_to = $book_user ? $book_user->getEmail() : '';
+
+ $empty_book_params = [
+ 'book_title' => '',
+ 'chapter_number' => '',
+ 'chapter_title' => '',
+ 'example_no' => '',
+ ];
+
+ if ($form_state->getValue('internshipform') == 1) {
+ $params = [
+ 'internshipform' => array_merge($empty_book_params, [
+ 'proposal_id' => $proposal_id,
+ 'user_id' => $proposal_data->uid,
+ ]),
+ ];
+ if (!$this->mailService->sendMail('textbook_companion', 'internshipform', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Internship Form for Book proposal has been recieved. User has been notified .'));
+ }
+ else {
+ if (!$this->mailService->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ (string) $this->t('[Textbook Companion] Internship Form not received'),
+ (string) $this->t('Dear user,
+
+Your Internship Form for the Book proposal has not been received.
+
+Regards,
+DWSIM TBC Team,
+FOSSEE.')
+ )) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Internship Form for Book proposal has not been recieved. User has been notified .'));
+ }
+
+ if ($form_state->getValue('copyrighttransferform') == 1) {
+ $params = [
+ 'copyrighttransferform' => array_merge($empty_book_params, [
+ 'proposal_id' => $proposal_id,
+ 'user_id' => $proposal_data->uid,
+ ]),
+ ];
+ if (!$this->mailService->sendMail('textbook_companion', 'copyrighttransferform', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Copyright Form for Book proposal has been recieved. User has been notified .'));
+ }
+ else {
+ if (!$this->mailService->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ (string) $this->t('[Textbook Companion] Copyright Transfer Form not received'),
+ (string) $this->t('Dear user,
+
+Your Copyright Transfer Form for the Book proposal has not been received.
+
+Regards,
+DWSIM TBC Team,
+FOSSEE.')
+ )) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Copyright Transfer Form for Book proposal has not been recieved. User has been notified .'));
+ }
+
+ if ($form_state->getValue('undertakingform') == 1) {
+ $params = [
+ 'undertakingform' => array_merge($empty_book_params, [
+ 'proposal_id' => $proposal_id,
+ 'user_id' => $proposal_data->uid,
+ ]),
+ ];
+ if (!$this->mailService->sendMail('textbook_companion', 'undertakingform', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Undertaking Form for Book proposal has been recieved. User has been notified .'));
+ }
+ else {
+ if (!$this->mailService->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ (string) $this->t('[Textbook Companion] Undertaking Form not received'),
+ (string) $this->t('Dear user,
+
+Your Undertaking Form for the Book proposal has not been received.
+
+Regards,
+DWSIM TBC Team,
+FOSSEE.')
+ )) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $this->messenger()->addStatus($this->t('Undertaking Form for Book proposal has not been recieved. User has been notified .'));
+ }
+
+ $this->messenger()->addStatus($this->t('Proposal Updated'));
+ $form_state->setRedirectUrl($this->getManageProposalsUrl());
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/ProposalApprovalForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/ProposalApprovalForm.php
index 951a285..c937417 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/ProposalApprovalForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/ProposalApprovalForm.php
@@ -9,10 +9,95 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\textbook_companion\Services\MailService;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Url;
+use Drupal\Core\Link;
+use Drupal\Core\Form\EnforcedResponseException;
class ProposalApprovalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountProxyInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\textbook_companion\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * Constructs a new ProposalApprovalForm object.
+ */
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ RequestStack $request_stack,
+ MailService $mail_service
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->requestStack = $request_stack;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('request_stack'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,179 +105,185 @@ public function getFormId() {
return 'proposal_approval_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $proposal_id = arg(3);
- /*$result = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 and id = %d", $proposal_id);*/
- $query = db_select('textbook_companion_proposal');
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state, $proposal_id = NULL) {
+ if (empty($proposal_id)) {
+ $proposal_id = \Drupal::routeMatch()->getParameter('proposal_id')
+ ?? \Drupal::routeMatch()->getParameter('id')
+ ?? \Drupal::request()->attributes->get('proposal_id')
+ ?? \Drupal::request()->attributes->get('id');
+ }
+
+ if (empty($proposal_id)) {
+ // Fallback for path parsing if routing wildcard is not matched.
+ $path_args = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last_arg = end($path_args);
+ if (is_numeric($last_arg)) {
+ $proposal_id = (int) $last_arg;
+ }
+ }
+
+ if (empty($proposal_id)) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromUri('internal:/textbook-companion/manage-proposal')->toString()));
+ }
+
+ $query = $this->database->select('textbook_companion_proposal');
$query->fields('textbook_companion_proposal');
$query->condition('proposal_status', 0);
$query->condition('id', $proposal_id);
$result = $query->execute();
- if ($result) {
- if ($row = $result->fetchObject()) {
- /* everything ok */
- } //$row = $result->fetchObject()
- else {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
- return;
- }
- } //$result
- else {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
- return;
+ $row = $result->fetchObject();
+
+ if (!$row) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromUri('internal:/textbook-companion/manage-proposal')->toString()));
}
+
+ $proposal_user = $this->entityTypeManager->getStorage('user')->load($row->uid);
+
$form['full_name'] = [
'#type' => 'item',
- '#markup' => l($row->full_name, 'user/' . $row->uid),
- '#title' => t('Contributor Name'),
+ '#markup' => $proposal_user
+ ? Link::fromTextAndUrl($row->full_name, Url::fromRoute('entity.user.canonical', ['user' => $row->uid]))->toString()
+ : $row->full_name,
+ '#title' => $this->t('Contributor Name'),
];
$form['email'] = [
'#type' => 'item',
- '#markup' => user_load($row->uid)->mail,
- '#title' => t('Email'),
+ '#markup' => $proposal_user ? $proposal_user->getEmail() : $this->t('Unknown'),
+ '#title' => $this->t('Email'),
];
$form['mobile'] = [
'#type' => 'item',
'#markup' => $row->mobile,
- '#title' => t('Mobile'),
+ '#title' => $this->t('Mobile'),
];
$form['how_project'] = [
'#type' => 'item',
'#markup' => $row->how_project,
- '#title' => t('How did you come to know about this project'),
+ '#title' => $this->t('How did you come to know about this project'),
];
$form['course'] = [
'#type' => 'item',
'#markup' => $row->course,
- '#title' => t('Course'),
+ '#title' => $this->t('Course'),
];
$form['branch'] = [
'#type' => 'item',
'#markup' => $row->branch,
- '#title' => t('Department/Branch'),
+ '#title' => $this->t('Department/Branch'),
];
$form['university'] = [
'#type' => 'item',
'#markup' => $row->university,
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
];
$form['city'] = [
'#type' => 'item',
'#markup' => $row->city,
- '#title' => t('City/Village'),
+ '#title' => $this->t('City/Village'),
];
$form['pincode'] = [
'#type' => 'item',
'#markup' => $row->pincode,
- '#title' => t('Pincode'),
+ '#title' => $this->t('Pincode'),
];
$form['state'] = [
'#type' => 'item',
'#markup' => $row->state,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
];
$form['faculty'] = [
'#type' => 'hidden',
- '#markup' => $row->faculty,
- '#title' => t('College Teacher/Professor'),
+ '#value' => $row->faculty,
];
$form['reviewer'] = [
'#type' => 'hidden',
- '#markup' => $row->reviewer,
- '#title' => t('Reviewer'),
+ '#value' => $row->reviewer,
];
if ($row->proposed_completion_date != 0) {
$proposed_completion_date = date('d-m-Y', $row->proposed_completion_date);
- } //$row->proposed_completion_date != 0
+ }
else {
$proposed_completion_date = "-----";
}
$form['proposed_completion_date'] = [
'#type' => 'item',
'#markup' => $proposed_completion_date,
- '#title' => t('Proposed Date of Completion'),
+ '#title' => $this->t('Proposed Date of Completion'),
];
if ($row->completion_date != 0) {
$actual_completion_date = date('d-m-Y', $row->completion_date);
- } //$row->completion_date != 0
+ }
else {
$actual_completion_date = "-----";
}
$form['completion_date'] = [
'#type' => 'item',
'#markup' => $actual_completion_date,
- '#title' => t('Actual Date of Completion'),
+ '#title' => $this->t('Actual Date of Completion'),
];
$form['operating_system'] = [
'#type' => 'item',
'#markup' => $row->operating_system,
- '#title' => t('Operating System'),
+ '#title' => $this->t('Operating System'),
];
$form['version'] = [
'#type' => 'item',
'#markup' => $row->dwsim_version,
- '#title' => t('dwsim Version'),
+ '#title' => $this->t('dwsim Version'),
];
$form['reference'] = [
'#type' => 'item',
'#markup' => $row->reference,
- '#title' => t('References'),
+ '#title' => $this->t('References'),
];
$form['reason'] = [
'#type' => 'item',
'#markup' => $row->reason,
- '#title' => t('Reasons'),
+ '#title' => $this->t('Reasons'),
];
+
/* get book preference */
$preference_rows = [];
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id);*/
- $query = db_select('textbook_companion_preference');
+ $query = $this->database->select('textbook_companion_preference');
$query->fields('textbook_companion_preference');
$query->condition('proposal_id', $proposal_id);
$query->orderBy('pref_number', 'ASC');
$preference_q = $query->execute();
while ($preference_data = $preference_q->fetchObject()) {
$preference_rows[$preference_data->id] = $preference_data->book . ' (Written by ' . $preference_data->author . ')';
- } //$preference_data = $preference_q->fetchObject()
- if ($row->proposal_type == 1) {
- $form['book_preference'] = [
- '#type' => 'radios',
- '#options' => $preference_rows,
- '#title' => t('Book Preferences'),
- '#required' => TRUE,
- ];
- } //$row->proposal_type == 1
- else {
- $form['book_preference'] = [
- '#type' => 'radios',
- '#title' => t('Book Preferences'),
- '#options' => $preference_rows,
- '#required' => TRUE,
- ];
}
+
+ $form['book_preference'] = [
+ '#type' => 'radios',
+ '#options' => $preference_rows,
+ '#title' => $this->t('Book Preferences'),
+ '#required' => !$form_state->getValue('disapprove'),
+ ];
+
if ($row->samplefilepath != "Not available") {
$form['samplecode'] = [
'#type' => 'markup',
- '#markup' => l('Download Sample Code', 'textbook-companion/download/samplecode/' . $proposal_id) . " ",
+ '#markup' => Link::fromTextAndUrl($this->t('Download Sample Code'), Url::fromUri('internal:/textbook-companion/download/samplecode/' . $proposal_id))->toString() . " ",
];
- } //$row->samplefilepath != "Not available"
+ }
$form['disapprove'] = [
'#type' => 'checkbox',
- '#title' => t('Disapprove all the above book preferences'),
+ '#title' => $this->t('Disapprove all the above book preferences'),
];
$form['message'] = [
'#type' => 'textarea',
- '#title' => t('Reason for disapproval'),
+ '#title' => $this->t('Reason for disapproval'),
'#states' => [
'visible' => [
':input[name="disapprove"]' => [
'checked' => TRUE
- ]
- ],
+ ]
+ ],
'required' => [':input[name="disapprove"]' => ['checked' => TRUE]],
],
];
@@ -202,164 +293,107 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
$form['cancel'] = [
'#type' => 'markup',
- '#value' => l(t('Cancel'), 'textbook-companion/manage-proposal'),
+ '#markup' => Link::fromTextAndUrl($this->t('Cancel'), Url::fromUri('internal:/textbook-companion/manage-proposal'))->toString(),
];
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if ($form_state->getValue(['disapprove'])) {
- if (strlen(trim($form_state->getValue(['message']))) <= 30) {
- $form_state->setErrorByName('message', t('Please mention the reason for disapproval in minimum 30 characters.'));
- } //strlen(trim($form_state['values']['message'])) <= 30
- } //$form_state['values']['disapprove']
- return;
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if ($form_state->getValue('disapprove')) {
+ if (strlen(trim($form_state->getValue('message'))) <= 30) {
+ $form_state->setErrorByName('message', $this->t('Please mention the reason for disapproval in minimum 30 characters.'));
+ }
+ }
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $proposal_id = $form_state->getValue(['proposal_id']);
- /*$result = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 and id = %d", $proposal_id);*/
- $query = db_select('textbook_companion_proposal');
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $proposal_id = $form_state->getValue('proposal_id');
+
+ $query = $this->database->select('textbook_companion_proposal');
$query->fields('textbook_companion_proposal');
$query->condition('proposal_status', 0);
$query->condition('id', $proposal_id);
$result = $query->execute();
- if ($result) {
- if ($row = $result->fetchObject()) {
- /* everything ok */
- } //$row = $result->fetchObject()
- else {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
- return;
- }
- } //$result
- else {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
+ $row = $result->fetchObject();
+
+ if (!$row) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirectUrl(Url::fromUri('internal:/textbook-companion/manage-proposal'));
return;
}
+
/* disapprove */
- if ($form_state->getValue(['disapprove'])) {
- /*db_query("UPDATE {textbook_companion_proposal} SET approver_uid = %d, approval_date = %d, proposal_status = 2, message = '%s' WHERE id = %d", $user->uid, time(), $form_state['values']['message'], $proposal_id);*/
- $query = db_update('textbook_companion_proposal');
+ if ($form_state->getValue('disapprove')) {
+ $query = $this->database->update('textbook_companion_proposal');
$query->fields([
- 'approver_uid' => $user->uid,
+ 'approver_uid' => $this->currentUser->id(),
'approval_date' => time(),
'proposal_status' => 2,
'completion_date' => '0',
- 'message' => $form_state->getValue(['message']),
+ 'message' => $form_state->getValue('message'),
]);
$query->condition('id', $proposal_id);
- $num_updated = $query->execute();
- /*db_query("UPDATE {textbook_companion_preference} SET approval_status = 2 WHERE proposal_id = %d", $proposal_id);*/
- $query = db_update('textbook_companion_preference');
+ $query->execute();
+
+ $query = $this->database->update('textbook_companion_preference');
$query->fields(['approval_status' => 2]);
$query->condition('proposal_id', $proposal_id);
- $num_updated = $query->execute();
- /* unlock all the aicte books */
- /*$query = "
- UPDATE textbook_companion_aicte
- SET status = 0, uid = 0, proposal_id = 0, preference_id = 0
- WHERE proposal_id = {$proposal_id}
- ";
- db_query($query);*/
- /*$query = db_update('textbook_companion_aicte');
- $query->fields(array(
- 'status' => 0,
- 'uid' => 0,
- 'proposal_id' => 0,
- 'preference_id' => 0,
- ));
- $query->condition('proposal_id', $proposal_id);
- $num_updated = $query->execute();*/
+ $query->execute();
+
/* sending email */
- $book_user = user_load($row->uid);
- $email_to = $book_user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $param['proposal_disapproved']['proposal_id'] = $proposal_id;
- $param['proposal_disapproved']['user_id'] = $row->uid;
- $param['proposal_disapproved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'proposal_disapproved', $email_to, language_default(), $param, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ $book_user = $this->entityTypeManager->getStorage('user')->load($row->uid);
+ if ($book_user) {
+ $email_to = $book_user->getEmail();
+ $params['proposal_disapproved']['proposal_id'] = $proposal_id;
+ $params['proposal_disapproved']['user_id'] = $row->uid;
+ if (!$this->mailService->sendMail('textbook_companion', 'proposal_disapproved', $email_to, $params)) {
+ $this->messenger->addError($this->t('Error sending email message.'));
+ }
}
- drupal_set_message('Book proposal dis-approved. User has been notified of the dis-approval.', 'error');
- drupal_goto('textbook-companion/manage-proposal');
+ $this->messenger->addError($this->t('Book proposal dis-approved. User has been notified of the dis-approval.'));
+ $form_state->setRedirectUrl(Url::fromUri('internal:/textbook-companion/manage-proposal'));
return;
- } //$form_state['values']['disapprove']
- /* get book preference and set the status */
- $preference_id = $form_state->getValue(['book_preference']);
- /*db_query("UPDATE {textbook_companion_proposal} SET approver_uid = %d, approval_date = %d, proposal_status = 1 WHERE id = %d", $user->uid, time(), $proposal_id);*/
- $query = db_update('textbook_companion_proposal');
+ }
+
+ /* get book preference and set the status */
+ $preference_id = $form_state->getValue('book_preference');
+
+ $query = $this->database->update('textbook_companion_proposal');
$query->fields([
- 'approver_uid' => $user->uid,
+ 'approver_uid' => $this->currentUser->id(),
'approval_date' => time(),
'proposal_status' => 1,
]);
$query->condition('id', $proposal_id);
- $num_updated = $query->execute();
- /*db_query("UPDATE {textbook_companion_preference} SET approval_status = 1 WHERE id = %d", $preference_id);*/
- $query = db_update('textbook_companion_preference');
+ $query->execute();
+
+ $query = $this->database->update('textbook_companion_preference');
$query->fields(['approval_status' => 1]);
$query->condition('id', $preference_id);
- $num_updated = $query->execute();
- /* unlock aicte books except the one which was approved out of 3 nos */
- /* $query = "
- UPDATE textbook_companion_aicte
- SET status = 0, uid = 0, proposal_id = 0, preference_id = 0
- WHERE proposal_id = {$proposal_id} AND preference_id != {$preference_id}
- ";
- db_query($query);*/
- /*$query = db_update('textbook_companion_aicte');
- $query->fields(array(
- 'status' => 0,
- 'uid' => 0,
- 'proposal_id' => 0,
- 'preference_id' => 0,
- ));
- $query->condition('proposal_id', '$proposal_id');
- $query->condition('preference_id', '$preference_id', '<>');
- $num_updated = $query->execute();*/
+ $query->execute();
+
/* sending email */
- $book_user = user_load($row->uid);
- $email_to = $book_user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $param['proposal_approved']['proposal_id'] = $proposal_id;
- $param['proposal_approved']['user_id'] = $row->uid;
- $param['proposal_approved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'proposal_approved', $email_to, language_default(), $param, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ $book_user = $this->entityTypeManager->getStorage('user')->load($row->uid);
+ if ($book_user) {
+ $email_to = $book_user->getEmail();
+ $params['proposal_approved']['proposal_id'] = $proposal_id;
+ $params['proposal_approved']['user_id'] = $row->uid;
+ if (!$this->mailService->sendMail('textbook_companion', 'proposal_approved', $email_to, $params)) {
+ $this->messenger->addError($this->t('Error sending email message.'));
+ }
}
- drupal_set_message('Book proposal approved. User has been notified of the approval', 'status');
- drupal_goto('textbook-companion/manage-proposal');
- return;
+ $this->messenger->addStatus($this->t('Book proposal approved. User has been notified of the approval.'));
+ $form_state->setRedirectUrl(Url::fromUri('internal:/textbook-companion/manage-proposal'));
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/ProposalEditForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/ProposalEditForm.php
index e15a69f..b55da24 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/ProposalEditForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/ProposalEditForm.php
@@ -9,69 +9,92 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedResponseException;
class ProposalEditForm extends FormBase {
- /**
- * {@inheritdoc}
- */
+ protected $database;
+ protected $currentUser;
+ protected $entityTypeManager;
+
+ public function __construct(Connection $database, AccountProxyInterface $current_user, EntityTypeManagerInterface $entity_type_manager) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager')
+ );
+ }
+
public function getFormId() {
return 'proposal_edit_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state, $nonaicte_book = NULL) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $proposal_id = arg(3);
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
+ /**
+ * Helper to load a preference by proposal_id and pref_number.
+ */
+ protected function loadPreference($proposal_id, $pref_number) {
+ return $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')
+ ->condition('proposal_id', $proposal_id)
+ ->condition('pref_number', $pref_number)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+ }
+
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $proposal_id = \Drupal::request()->query->get('proposal_id')
+ ?? \Drupal::routeMatch()->getParameter('proposal_id');
+
+ if (empty($proposal_id)) {
+ $parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last = end($parts);
+ if (is_numeric($last)) {
+ $proposal_id = (int) $last;
+ }
+ }
+
+ if (empty($proposal_id)) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse(Url::fromRoute('textbook_companion._proposal_all')->toString())
+ );
+ }
+
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->fields('p');
$query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- $proposal_data = $proposal_q->fetchObject();
- if (!$proposal_data) {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
- return;
- } //!$proposal_data
- } //$proposal_q
- else {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
- return;
+ $proposal_data = $query->execute()->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger()->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse(Url::fromRoute('textbook_companion._proposal_all')->toString())
+ );
}
- $user_data = user_load($proposal_data->uid);
- /* $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 1);
- $preference1_data = db_fetch_object($preference1_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('pref_number', 1);
- $query->range(0, 1);
- $preference1_q = $query->execute();
- $preference1_data = $preference1_q->fetchObject();
- /********************************************************************/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('pref_number', 2);
- $query->range(0, 1);
- $preference2_q = $query->execute();
- $preference2_data = $preference2_q->fetchObject();
- /**************************************************************************/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('pref_number', 3);
- $query->range(0, 1);
- $preference3_q = $query->execute();
- $preference3_data = $preference3_q->fetchObject();
- /*************************************************************************/
+
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+
+ $preference1_data = $this->loadPreference($proposal_id, 1);
+ $preference2_data = $this->loadPreference($proposal_id, 2);
+ $preference3_data = $this->loadPreference($proposal_id, 3);
+
$form['full_name'] = [
'#type' => 'textfield',
- '#title' => t('Full Name'),
+ '#title' => $this->t('Full Name'),
'#size' => 30,
'#maxlength' => 50,
'#required' => TRUE,
@@ -79,14 +102,14 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['email_id'] = [
'#type' => 'textfield',
- '#title' => t('Email'),
+ '#title' => $this->t('Email'),
'#size' => 30,
- '#value' => $user_data->mail,
+ '#value' => $user_data ? $user_data->getEmail() : '',
'#disabled' => TRUE,
];
$form['mobile'] = [
'#type' => 'textfield',
- '#title' => t('Mobile No.'),
+ '#title' => $this->t('Mobile No.'),
'#size' => 30,
'#maxlength' => 15,
'#required' => TRUE,
@@ -94,7 +117,7 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['how_project'] = [
'#type' => 'select',
- '#title' => t('How did you come to know about this project'),
+ '#title' => $this->t('How did you come to know about this project'),
'#options' => [
'DWSIM Website' => 'DWSIM Website',
'Friend' => 'Friend',
@@ -108,553 +131,259 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['course'] = [
'#type' => 'textfield',
- '#title' => t('Course'),
+ '#title' => $this->t('Course'),
'#size' => 30,
'#maxlength' => 50,
'#required' => TRUE,
'#default_value' => $proposal_data->course,
];
+
+ $dept_options = function_exists('_list_of_departments') ? _list_of_departments() : [];
$form['branch'] = [
'#type' => 'select',
- '#title' => t('Department/Branch'),
- '#options' => _list_of_departments(),
+ '#title' => $this->t('Department/Branch'),
+ '#options' => $dept_options,
'#required' => TRUE,
'#default_value' => $proposal_data->branch,
];
$form['university'] = [
'#type' => 'textfield',
- '#title' => t('University/ Institute'),
+ '#title' => $this->t('University/ Institute'),
'#size' => 80,
'#maxlength' => 200,
'#required' => TRUE,
- '#attributes' => [
- 'placeholder' => 'Insert full name of your institute/ university.... '
- ],
+ '#attributes' => ['placeholder' => 'Insert full name of your institute/ university....'],
'#default_value' => $proposal_data->university,
];
$form['country'] = [
'#type' => 'select',
- '#title' => t('Country'),
- '#options' => [
- 'India' => 'India',
- 'Others' => 'Others',
- ],
+ '#title' => $this->t('Country'),
+ '#options' => ['India' => 'India', 'Others' => 'Others'],
'#required' => TRUE,
- '#tree' => TRUE,
- '#validated' => TRUE,
'#default_value' => $proposal_data->country,
];
$form['other_country'] = [
'#type' => 'textfield',
- '#title' => t('Other than India'),
+ '#title' => $this->t('Other than India'),
'#size' => 100,
- '#attributes' => [
- 'placeholder' => t('Enter your country name')
- ],
'#default_value' => $proposal_data->country,
- '#states' => [
- 'visible' => [
- ':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
- ],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'Others']]],
];
$form['other_state'] = [
'#type' => 'textfield',
- '#title' => t('State other than India'),
+ '#title' => $this->t('State other than India'),
'#size' => 100,
'#default_value' => $proposal_data->state,
- '#attributes' => [
- 'placeholder' => t('Enter your state/region name')
- ],
- '#states' => [
- 'visible' => [
- ':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
- ],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'Others']]],
];
$form['other_city'] = [
'#type' => 'textfield',
- '#title' => t('City other than India'),
+ '#title' => $this->t('City other than India'),
'#size' => 100,
'#default_value' => $proposal_data->city,
- '#attributes' => [
- 'placeholder' => t('Enter your city name')
- ],
- '#states' => [
- 'visible' => [
- ':input[name="country"]' => [
- 'value' => 'Others'
- ]
- ]
- ],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'Others']]],
];
+
+ $state_options = function_exists('_list_of_states') ? _list_of_states() : [];
$form['all_state'] = [
'#type' => 'select',
- '#title' => t('State'),
- '#selected' => [
- '' => '-select-'
- ],
- '#options' => _list_of_states(),
+ '#title' => $this->t('State'),
+ '#options' => $state_options,
'#default_value' => $proposal_data->state,
- '#validated' => TRUE,
- '#states' => [
- 'visible' => [
- ':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
- ],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'India']]],
];
+
+ $city_options = function_exists('_list_of_cities') ? _list_of_cities() : [];
$form['city'] = [
'#type' => 'select',
- '#title' => t('City'),
+ '#title' => $this->t('City'),
+ '#options' => $city_options,
'#default_value' => $proposal_data->city,
- '#options' => _list_of_cities(),
- '#states' => [
- 'visible' => [
- ':input[name="country"]' => [
- 'value' => 'India'
- ]
- ]
- ],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'India']]],
];
$form['pincode'] = [
'#type' => 'textfield',
- '#title' => t('Pincode'),
+ '#title' => $this->t('Pincode'),
'#size' => 30,
'#maxlength' => 6,
- '#required' => FALSE,
'#default_value' => $proposal_data->pincode,
- '#attributes' => [
- 'placeholder' => 'Enter pincode....'
- ],
- ];
- /***************************************************************************/
- $form['hr'] = [
- '#type' => 'item',
- '#markup' => ' ',
- ];
- $form['faculty'] = [
- '#type' => 'hidden',
- '#title' => t('College Teacher/Professor'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#default_value' => $proposal_data->faculty,
- ];
- $form['reviewer'] = [
- '#type' => 'hidden',
- '#title' => t('Reviewer'),
- '#size' => 30,
- '#maxlength' => 100,
- '#default_value' => $proposal_data->reviewer,
];
+ $form['hr'] = ['#type' => 'item', '#markup' => ' '];
+ $form['faculty'] = ['#type' => 'hidden', '#value' => $proposal_data->faculty];
+ $form['reviewer'] = ['#type' => 'hidden', '#value' => $proposal_data->reviewer];
$form['completion_date'] = [
'#type' => 'textfield',
- '#title' => t('Expected Date of Completion'),
- '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'),
+ '#title' => $this->t('Expected Date of Completion'),
+ '#description' => $this->t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'),
'#size' => 10,
'#maxlength' => 10,
- '#default_value' => date('d-m-Y', $proposal_data->completion_date),
+ '#default_value' => $proposal_data->completion_date ? date('d-m-Y', $proposal_data->completion_date) : '',
];
$form['version'] = [
'#type' => 'textfield',
- '#title' => t('DWSIM Version'),
+ '#title' => $this->t('DWSIM Version'),
'#size' => 10,
'#maxlength' => 20,
'#default_value' => $proposal_data->dwsim_version,
];
$form['operating_system'] = [
'#type' => 'textfield',
- '#title' => t('Operating System'),
+ '#title' => $this->t('Operating System'),
'#size' => 30,
'#maxlength' => 50,
'#default_value' => $proposal_data->operating_system,
];
+
+ // Preference 1 (always shown).
$form['preference1'] = [
'#type' => 'fieldset',
- '#title' => t('Book Preference 1'),
+ '#title' => $this->t('Book Preference 1'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
];
- $form['preference1']['book1'] = [
- '#type' => 'textfield',
- '#title' => t('Title of the book'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#default_value' => $preference1_data->book,
- ];
- $form['preference1']['author1'] = [
- '#type' => 'textfield',
- '#title' => t('Author Name'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#default_value' => $preference1_data->author,
- ];
- $form['preference1']['isbn1'] = [
- '#type' => 'textfield',
- '#title' => t('ISBN No'),
- '#size' => 30,
- '#maxlength' => 25,
- '#required' => TRUE,
- '#default_value' => $preference1_data->isbn,
- ];
- $form['preference1']['publisher1'] = [
- '#type' => 'textfield',
- '#title' => t('Publisher & Place'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE,
- '#default_value' => $preference1_data->publisher,
- ];
- $form['preference1']['edition1'] = [
- '#type' => 'textfield',
- '#title' => t('Edition'),
- '#size' => 4,
- '#maxlength' => 2,
- '#required' => TRUE,
- '#default_value' => $preference1_data->edition,
- ];
- $form['preference1']['year1'] = [
- '#type' => 'textfield',
- '#title' => t('Year of pulication'),
- '#size' => 4,
- '#maxlength' => 4,
- '#required' => TRUE,
- '#default_value' => $preference1_data->year,
- ];
- if ($preference2_data) {
- $form['preference2'] = [
- '#type' => 'fieldset',
- '#title' => t('Book Preference 2'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- ];
- $form['preference2']['book2'] = [
- '#type' => 'textfield',
- '#title' => t('Title of the book'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#default_value' => $preference2_data->book,
- ];
- $form['preference2']['author2'] = [
- '#type' => 'textfield',
- '#title' => t('Author Name'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#default_value' => $preference2_data->author,
- ];
- $form['preference2']['isbn2'] = [
- '#type' => 'textfield',
- '#title' => t('ISBN No'),
- '#size' => 30,
- '#maxlength' => 25,
- '#required' => TRUE,
- '#default_value' => $preference2_data->isbn,
- ];
- $form['preference2']['publisher2'] = [
- '#type' => 'textfield',
- '#title' => t('Publisher & Place'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE,
- '#default_value' => $preference2_data->publisher,
- ];
- $form['preference2']['edition2'] = [
+ foreach (['book1' => 'book', 'author1' => 'author', 'isbn1' => 'isbn', 'publisher1' => 'publisher', 'edition1' => 'edition', 'year1' => 'year'] as $field => $col) {
+ $form['preference1'][$field] = [
'#type' => 'textfield',
- '#title' => t('Edition'),
- '#size' => 4,
- '#maxlength' => 2,
+ '#title' => $this->t(ucfirst(str_replace('1', '', $field))),
'#required' => TRUE,
- '#default_value' => $preference2_data->edition,
+ '#default_value' => $preference1_data ? $preference1_data->$col : '',
+ '#size' => in_array($field, ['edition1', 'year1']) ? 4 : 30,
+ '#maxlength' => in_array($field, ['edition1']) ? 2 : (in_array($field, ['year1']) ? 4 : 100),
];
- $form['preference2']['year2'] = [
- '#type' => 'textfield',
- '#title' => t('Year of pulication'),
- '#size' => 4,
- '#maxlength' => 4,
- '#required' => TRUE,
- '#default_value' => $preference2_data->year,
- ];
- } //$preference2_data
+ }
+
+ if ($preference2_data) {
+ $form['preference2'] = ['#type' => 'fieldset', '#title' => $this->t('Book Preference 2'), '#collapsible' => TRUE, '#collapsed' => FALSE];
+ foreach (['book2' => 'book', 'author2' => 'author', 'isbn2' => 'isbn', 'publisher2' => 'publisher', 'edition2' => 'edition', 'year2' => 'year'] as $field => $col) {
+ $form['preference2'][$field] = [
+ '#type' => 'textfield',
+ '#title' => $this->t(ucfirst(str_replace('2', '', $field))),
+ '#required' => TRUE,
+ '#default_value' => $preference2_data->$col,
+ '#size' => in_array($field, ['edition2', 'year2']) ? 4 : 30,
+ '#maxlength' => in_array($field, ['edition2']) ? 2 : (in_array($field, ['year2']) ? 4 : 100),
+ ];
+ }
+ }
+
if ($preference3_data) {
- $form['preference3'] = [
- '#type' => 'fieldset',
- '#title' => t('Book Preference 3'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- ];
- $form['preference3']['book3'] = [
- '#type' => 'textfield',
- '#title' => t('Title of the book'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#default_value' => $preference3_data->book,
- ];
- $form['preference3']['author3'] = [
- '#type' => 'textfield',
- '#title' => t('Author Name'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#default_value' => $preference3_data->author,
- ];
- $form['preference3']['isbn3'] = [
- '#type' => 'textfield',
- '#title' => t('ISBN No'),
- '#size' => 30,
- '#maxlength' => 25,
- '#required' => TRUE,
- '#default_value' => $preference3_data->isbn,
- ];
- $form['preference3']['publisher3'] = [
- '#type' => 'textfield',
- '#title' => t('Publisher & Place'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE,
- '#default_value' => $preference3_data->publisher,
- ];
- $form['preference3']['edition3'] = [
- '#type' => 'textfield',
- '#title' => t('Edition'),
- '#size' => 4,
- '#maxlength' => 2,
- '#required' => TRUE,
- '#default_value' => $preference3_data->edition,
- ];
- $form['preference3']['year3'] = [
- '#type' => 'textfield',
- '#title' => t('Year of pulication'),
- '#size' => 4,
- '#maxlength' => 4,
- '#required' => TRUE,
- '#default_value' => $preference3_data->year,
- ];
- } //$preference3_data
- /* hidden fields */
- $form['hidden_preference_id1'] = [
- '#type' => 'hidden',
- '#value' => $preference1_data->id,
- ];
- /* $form['hidden_preference_id2'] = array(
- '#type' => 'hidden',
- '#value' => $preference2_data->id
- );
- $form['hidden_preference_id3'] = array(
- '#type' => 'hidden',
- '#value' => $preference3_data->id
- );*/
- $form['hidden_proposal_id'] = [
- '#type' => 'hidden',
- '#value' => $proposal_id,
- ];
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => t('Submit'),
- ];
+ $form['preference3'] = ['#type' => 'fieldset', '#title' => $this->t('Book Preference 3'), '#collapsible' => TRUE, '#collapsed' => FALSE];
+ foreach (['book3' => 'book', 'author3' => 'author', 'isbn3' => 'isbn', 'publisher3' => 'publisher', 'edition3' => 'edition', 'year3' => 'year'] as $field => $col) {
+ $form['preference3'][$field] = [
+ '#type' => 'textfield',
+ '#title' => $this->t(ucfirst(str_replace('3', '', $field))),
+ '#required' => TRUE,
+ '#default_value' => $preference3_data->$col,
+ '#size' => in_array($field, ['edition3', 'year3']) ? 4 : 30,
+ '#maxlength' => in_array($field, ['edition3']) ? 2 : (in_array($field, ['year3']) ? 4 : 100),
+ ];
+ }
+ }
+
+ $form['hidden_preference_id1'] = ['#type' => 'hidden', '#value' => $preference1_data ? $preference1_data->id : 0];
+ $form['hidden_proposal_id'] = ['#type' => 'hidden', '#value' => $proposal_id];
+ $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Submit')];
$form['cancel'] = [
- '#type' => 'item',
- '#markup' => l(t('Cancel'), 'textbook-companion/manage-proposal'),
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute('textbook_companion._proposal_all'),
+ '#attributes' => ['class' => ['button']],
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if ($form_state->getValue(['book1']) && $form_state->getValue(['author1'])) {
- $bk1 = trim($form_state->getValue(['book1']));
- $auth1 = trim($form_state->getValue(['author1']));
- if (_dir_name($bk1, $auth1, $form_state->getValue([
- 'hidden_preference_id1'
- ])) != NULL) {
- $form_state->setValue(['dir_name1'], _dir_name($bk1, $auth1, $form_state->getValue([
- 'hidden_preference_id1'
- ])));
- } //_dir_name($bk1, $auth1, $form_state['values']['hidden_preference_id1']) != NULL
- } //$form_state['values']['book1'] && $form_state['values']['author1']
- /*if ($form_state['values']['book2'] && $form_state['values']['author2'])
- {
- $bk2 = trim($form_state['values']['book2']);
- $auth2 = trim($form_state['values']['author2']);
-
- if (_dir_name($bk2, $auth2, $form_state['values']['hidden_preference_id2']) != NULL)
- {
- $form_state['values']['dir_name2'] = _dir_name($bk2, $auth2, $form_state['values']['hidden_preference_id2']);
- }
- }
- if ($form_state['values']['book3'] && $form_state['values']['author3'])
- {
- $bk3 = trim($form_state['values']['book3']);
- $auth3 = trim($form_state['values']['author3']);
-
- if (_dir_name($bk3, $auth3, $form_state['values']['hidden_preference_id3']) != NULL)
- {
- $form_state['values']['dir_name3'] = _dir_name($bk3, $auth3, $form_state['values']['hidden_preference_id3']);
- }
- }
- /* mobile */
- if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state->getValue(['mobile']))) {
- $form_state->setErrorByName('mobile', t('Invalid mobile number'));
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if ($form_state->getValue('book1') && $form_state->getValue('author1')) {
+ if (function_exists('_dir_name')) {
+ $dir = _dir_name(trim($form_state->getValue('book1')), trim($form_state->getValue('author1')), $form_state->getValue('hidden_preference_id1'));
+ if ($dir !== NULL) {
+ $form_state->setValue('dir_name1', $dir);
+ }
+ }
+ }
+ if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state->getValue('mobile'))) {
+ $form_state->setErrorByName('mobile', $this->t('Invalid mobile number'));
}
- /* date of completion */
- if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state->getValue([
- 'completion_date'
- ]))) {
- $form_state->setErrorByName('completion_date', t('Invalid expected date of completion'));
+ if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state->getValue('completion_date'))) {
+ $form_state->setErrorByName('completion_date', $this->t('Invalid expected date of completion'));
}
- list($d, $m, $y) = explode('-', $form_state->getValue(['completion_date']));
- $d = (int) $d;
- $m = (int) $m;
- $y = (int) $y;
- if (!checkdate($m, $d, $y)) {
- $form_state->setErrorByName('completion_date', t('Invalid expected date of completion'));
+ else {
+ [$d, $m, $y] = explode('-', $form_state->getValue('completion_date'));
+ if (!checkdate((int) $m, (int) $d, (int) $y)) {
+ $form_state->setErrorByName('completion_date', $this->t('Invalid expected date of completion'));
+ }
}
- //if (mktime(0, 0, 0, $m, $d, $y) <= time())
- //form_set_error('completion_date', t('Expected date of completion should be in future'));
- /* edition */
- if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state->getValue(['edition1']))) {
- $form_state->setErrorByName('edition1', t('Invalid edition for Book Preference 1'));
+ if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state->getValue('edition1'))) {
+ $form_state->setErrorByName('edition1', $this->t('Invalid edition for Book Preference 1'));
}
- /* year of publication */
- if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state->getValue(['year1']))) {
- $form_state->setErrorByName('year1', t('Invalid year of pulication for Book Preference 1'));
+ if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state->getValue('year1'))) {
+ $form_state->setErrorByName('year1', $this->t('Invalid year of publication for Book Preference 1'));
}
- /* year of publication */
- $cur_year = date('Y');
- if ((int) $form_state->getValue(['year1']) > $cur_year) {
- $form_state->setErrorByName('year1', t('Year of pulication should be not in the future for Book Preference 1'));
+ elseif ((int) $form_state->getValue('year1') > (int) date('Y')) {
+ $form_state->setErrorByName('year1', $this->t('Year of publication should not be in the future for Book Preference 1'));
}
- /* isbn */
- if (!preg_match('/^[0-9\-xX]+$/', $form_state->getValue(['isbn1']))) {
- $form_state->setErrorByName('isbn1', t('Invalid ISBN for Book Preference 1'));
+ if (!preg_match('/^[0-9\-xX]+$/', $form_state->getValue('isbn1'))) {
+ $form_state->setErrorByName('isbn1', $this->t('Invalid ISBN for Book Preference 1'));
}
- if ($form_state->getValue(['version']) == 'olderversion') {
- if ($form_state->getValue(['older']) == '') {
- $form_state->setErrorByName('older', t('Please provide valid version'));
- } //$form_state['values']['older'] == ''
- } //$form_state['values']['version'] == 'olderversion'
- return;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- /* completion date to timestamp */
- list($d, $m, $y) = explode('-', $form_state->getValue(['completion_date']));
- $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y);
- $proposal_id = $form_state->getValue(['hidden_proposal_id']);
- if ($form_state->getValue(['version']) == 'olderversion') {
- $form_state->setValue(['version'], $form_state->getValue(['older']));
- } //$form_state['values']['version'] == 'olderversion'
- if ($form_state->getValue(['country']) == 'other') {
- $form_state->setValue(['country'], $form_state->getValue(['other_country']));
- $form_state->setValue(['all_state'], $form_state->getValue(['other_state']));
- } //$form_state['values']['country'] == 'other'
- $query = db_update('textbook_companion_proposal');
- $query->fields([
- 'full_name' => $form_state->getValue(['full_name']),
- 'mobile' => $form_state->getValue(['mobile']),
- 'how_project' => $form_state->getValue(['how_project']),
- 'course' => $form_state->getValue(['course']),
- 'branch' => $form_state->getValue(['branch']),
- 'university' => $form_state->getValue(['university']),
- 'city' => $form_state->getValue(['city']),
- 'pincode' => $form_state->getValue(['pincode']),
- 'state' => $form_state->getValue(['all_state']),
- 'country' => $form_state->getValue(['country']),
- 'faculty' => $form_state->getValue(['faculty']),
- 'reviewer' => $form_state->getValue(['reviewer']),
- 'completion_date' => $completion_date_timestamp,
- 'operating_system' => $form_state->getValue(['operating_system']),
- 'dwsim_version' => $form_state->getValue(['version']),
- ]);
- $query->condition('id', $proposal_id);
- $num_updated = $query->execute();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('pref_number', 1);
- $query->range(0, 1);
- $preference1_q = $query->execute();
- $preference1_data = $preference1_q->fetchObject();
- $preference1_id = $preference1_data->id;
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ [$d, $m, $y] = explode('-', $form_state->getValue('completion_date'));
+ $completion_ts = mktime(0, 0, 0, $m, $d, $y);
+ $proposal_id = $form_state->getValue('hidden_proposal_id');
+
+ if ($form_state->getValue('country') === 'other') {
+ $form_state->setValue('country', $form_state->getValue('other_country'));
+ $form_state->setValue('all_state', $form_state->getValue('other_state'));
+ }
+
+ $this->database->update('textbook_companion_proposal')
+ ->fields([
+ 'full_name' => $form_state->getValue('full_name'),
+ 'mobile' => $form_state->getValue('mobile'),
+ 'how_project' => $form_state->getValue('how_project'),
+ 'course' => $form_state->getValue('course'),
+ 'branch' => $form_state->getValue('branch'),
+ 'university' => $form_state->getValue('university'),
+ 'city' => $form_state->getValue('city'),
+ 'pincode' => $form_state->getValue('pincode'),
+ 'state' => $form_state->getValue('all_state'),
+ 'country' => $form_state->getValue('country'),
+ 'faculty' => $form_state->getValue('faculty'),
+ 'reviewer' => $form_state->getValue('reviewer'),
+ 'completion_date' => $completion_ts,
+ 'operating_system' => $form_state->getValue('operating_system'),
+ 'dwsim_version' => $form_state->getValue('version'),
+ ])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ $preference1_data = $this->loadPreference($proposal_id, 1);
if ($preference1_data) {
- del_book_pdf($preference1_data->id);
- RenameDir($preference1_id, $form_state->getValue(['dir_name1']));
- $query = db_update('textbook_companion_preference');
- $query->fields([
- 'book' => $form_state->getValue(['book1']),
- 'author' => $form_state->getValue(['author1']),
- 'isbn' => $form_state->getValue(['isbn1']),
- 'publisher' => $form_state->getValue(['publisher1']),
- 'edition' => $form_state->getValue(['edition1']),
- 'year' => $form_state->getValue(['year1']),
- 'directory_name' => $form_state->getValue(['dir_name1']),
- ]);
- $query->condition('id', $preference1_id);
- $num_updated = $query->execute();
- } //$preference1_data
- /**************************************************************/
- /**$query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('pref_number', 2);
- $query->range(0, 1);
- $preference2_q = $query->execute();
- $preference2_data = $preference2_q->fetchObject();
- $preference2_id = $preference2_data->id;
- if ($preference2_data)
- {
- del_book_pdf($preference2_data->id);
- RenameDir($preference2_id, $form_state['values']['dir_name2']);
- $query = db_update('textbook_companion_preference');
- $query->fields(array(
- 'book' => $form_state['values']['book2'],
- 'author' => $form_state['values']['author2'],
- 'isbn' => $form_state['values']['isbn2'],
- 'publisher' => $form_state['values']['publisher2'],
- 'edition' => $form_state['values']['edition2'],
- 'year' => $form_state['values']['year2'],
- 'directory_name' => $form_state['values']['dir_name2']
- ));
- $query->condition('id', $preference2_id);
- $num_updated = $query->execute();
- }
- /*****************************************************************/
- /**$query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('pref_number', 3);
- $query->range(0, 1);
- $preference3_q = $query->execute();
- $preference3_data = $preference3_q->fetchObject();
- $preference3_id = $preference3_data->id;
- if ($preference3_data)
- {
- del_book_pdf($preference3_data->id);
- RenameDir($preference3_id, $form_state['values']['dir_name3']);
- $query = db_update('textbook_companion_preference');
- $query->fields(array(
- 'book' => $form_state['values']['book3'],
- 'author' => $form_state['values']['author3'],
- 'isbn' => $form_state['values']['isbn3'],
- 'publisher' => $form_state['values']['publisher3'],
- 'edition' => $form_state['values']['edition3'],
- 'year' => $form_state['values']['year3'],
- 'directory_name' => $form_state['values']['dir_name3']
- ));
- $query->condition('id', $preference3_id);
- $num_updated = $query->execute();
- }**/
- drupal_set_message(t('Proposal Updated'), 'status');
+ $preference1_id = $preference1_data->id;
+ if (function_exists('del_book_pdf')) {
+ del_book_pdf($preference1_id);
+ }
+ if (function_exists('RenameDir') && $form_state->getValue('dir_name1')) {
+ RenameDir($preference1_id, $form_state->getValue('dir_name1'));
+ }
+ $this->database->update('textbook_companion_preference')
+ ->fields([
+ 'book' => $form_state->getValue('book1'),
+ 'author' => $form_state->getValue('author1'),
+ 'isbn' => $form_state->getValue('isbn1'),
+ 'publisher' => $form_state->getValue('publisher1'),
+ 'edition' => $form_state->getValue('edition1'),
+ 'year' => $form_state->getValue('year1'),
+ 'directory_name' => $form_state->getValue('dir_name1'),
+ ])
+ ->condition('id', $preference1_id)
+ ->execute();
+ }
+
+ $this->messenger()->addStatus($this->t('Proposal Updated'));
+ $form_state->setRedirect('textbook_companion._proposal_all');
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/ProposalStatusForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/ProposalStatusForm.php
index 2fa36fb..7c96f14 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/ProposalStatusForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/ProposalStatusForm.php
@@ -9,325 +9,335 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\textbook_companion\Services\MailService;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedResponseException;
class ProposalStatusForm extends FormBase {
- /**
- * {@inheritdoc}
- */
+ protected $database;
+ protected $messenger;
+ protected $currentUser;
+ protected $entityTypeManager;
+ protected $mailService;
+
+ public function __construct(
+ Connection $database,
+ MessengerInterface $messenger,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ MailService $mail_service
+ ) {
+ $this->database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->mailService = $mail_service;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
public function getFormId() {
return 'proposal_status_form';
}
- public function buildForm(array $from, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $proposal_id = arg(3);
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ // Extract proposal_id from query parameter.
+ $proposal_id = \Drupal::request()->query->get('proposal_id')
+ ?? \Drupal::routeMatch()->getParameter('proposal_id');
+
+ if (empty($proposal_id)) {
+ $path_parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last = end($path_parts);
+ if (is_numeric($last)) {
+ $proposal_id = (int) $last;
+ }
+ }
+
+ if (empty($proposal_id)) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse(Url::fromRoute('textbook_companion._proposal_all')->toString())
+ );
+ }
+
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->fields('p');
$query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if (!$proposal_data = $proposal_q->fetchObject()) {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
- return;
- } //!$proposal_data = $proposal_q->fetchObject()
+ $proposal_data = $query->execute()->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ throw new EnforcedResponseException(
+ new RedirectResponse(Url::fromRoute('textbook_companion._proposal_all')->toString())
+ );
+ }
+
+ // Load user for email.
+ $proposal_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ $user_email = $proposal_user ? $proposal_user->getEmail() : $this->t('Unknown');
+
$form['full_name'] = [
'#type' => 'item',
'#markup' => $proposal_data->full_name,
- '#title' => t('Contributor Name'),
+ '#title' => $this->t('Contributor Name'),
];
$form['email'] = [
'#type' => 'item',
- '#markup' => user_load($proposal_data->uid)->mail,
- '#title' => t('Email'),
+ '#markup' => $user_email,
+ '#title' => $this->t('Email'),
];
$form['mobile'] = [
'#type' => 'item',
'#markup' => $proposal_data->mobile,
- '#title' => t('Mobile'),
+ '#title' => $this->t('Mobile'),
];
$form['how_project'] = [
'#type' => 'item',
'#markup' => $proposal_data->how_project,
- '#title' => t('How did you come to know about this project'),
+ '#title' => $this->t('How did you come to know about this project'),
];
$form['course'] = [
'#type' => 'item',
'#markup' => $proposal_data->course,
- '#title' => t('Course'),
+ '#title' => $this->t('Course'),
];
$form['branch'] = [
'#type' => 'item',
'#markup' => $proposal_data->branch,
- '#title' => t('Department/Branch'),
+ '#title' => $this->t('Department/Branch'),
];
$form['university'] = [
'#type' => 'item',
'#markup' => $proposal_data->university,
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
];
$form['city'] = [
'#type' => 'item',
'#markup' => $proposal_data->city,
- '#title' => t('City/Village'),
+ '#title' => $this->t('City/Village'),
];
$form['pincode'] = [
'#type' => 'item',
'#markup' => $proposal_data->pincode,
- '#title' => t('Pincode'),
+ '#title' => $this->t('Pincode'),
];
$form['state'] = [
'#type' => 'item',
'#markup' => $proposal_data->state,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
];
$form['faculty'] = [
'#type' => 'hidden',
- '#markup' => $proposal_data->faculty,
- '#title' => t('College Teacher/Professor'),
+ '#value' => $proposal_data->faculty,
];
$form['reviewer'] = [
'#type' => 'hidden',
- '#markup' => $proposal_data->reviewer,
- '#title' => t('Reviewer'),
+ '#value' => $proposal_data->reviewer,
];
+ $completion_ts = $proposal_data->completion_date;
$form['completion_date'] = [
'#type' => 'item',
- '#markup' => date('d-m-Y', $proposal_data->completion_date),
- '#title' => t('Expected Date of Completion'),
+ '#markup' => $completion_ts ? date('d-m-Y', $completion_ts) : '-----',
+ '#title' => $this->t('Expected Date of Completion'),
];
$form['operating_system'] = [
'#type' => 'item',
'#markup' => $proposal_data->operating_system,
- '#title' => t('Operating System'),
+ '#title' => $this->t('Operating System'),
];
$form['version'] = [
'#type' => 'item',
'#markup' => $proposal_data->dwsim_version,
- '#title' => t('DWSIM Version'),
+ '#title' => $this->t('DWSIM Version'),
];
+
if ($proposal_data->proposal_type == 1) {
$form['reason'] = [
- '#type' => 'hidden',
+ '#type' => 'item',
'#markup' => $proposal_data->reason,
- '#title' => t('Reason'),
+ '#title' => $this->t('Reason'),
];
$form['reference'] = [
- '#type' => 'hidden',
+ '#type' => 'item',
'#markup' => $proposal_data->reference,
- '#title' => t('References'),
+ '#title' => $this->t('References'),
];
- } //$proposal_data->proposal_type == 1
- /* get book preference */
+ }
+
+ // Book preferences list.
$preference_html = '';
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('pref_number', 'ASC');
- $preference_q = $query->execute();
- while ($preference_data = $preference_q->fetchObject()) {
+ $pref_query = $this->database->select('textbook_companion_preference', 'pref');
+ $pref_query->fields('pref');
+ $pref_query->condition('proposal_id', $proposal_id);
+ $pref_query->orderBy('pref_number', 'ASC');
+ $pref_result = $pref_query->execute();
+ while ($preference_data = $pref_result->fetchObject()) {
if ($preference_data->approval_status == 1) {
- $preference_html .= '' . $preference_data->book . ' (Written by ' . $preference_data->author . ') - Approved Book ';
+ $preference_html .= '' . $preference_data->book . ' (Written by ' . $preference_data->author . ') - Approved Book ';
}
else {
$preference_html .= '' . $preference_data->book . ' (Written by ' . $preference_data->author . ') ';
}
- } //$preference_data = $preference_q->fetchObject()
+ }
$preference_html .= ' ';
$form['book_preference'] = [
'#type' => 'item',
'#markup' => $preference_html,
- '#title' => t('Book Preferences'),
+ '#title' => $this->t('Book Preferences'),
+ ];
+
+ // Proposal status label.
+ $statuses = [
+ 0 => $this->t('Pending'),
+ 1 => $this->t('Approved'),
+ 2 => $this->t('Dis-approved'),
+ 3 => $this->t('Completed'),
+ 4 => $this->t('External'),
+ 5 => $this->t('Submitted all codes'),
];
- $proposal_status = '';
- switch ($proposal_data->proposal_status) {
- case 0:
- $proposal_status = t('Pending');
- break;
- case 1:
- $proposal_status = t('Approved');
- break;
- case 2:
- $proposal_status = t('Dis-approved');
- break;
- case 3:
- $proposal_status = t('Completed');
- break;
- case 4:
- $proposal_status = t('External');
- break;
- case 5:
- $proposal_status = t('Submitted all codes');
- break;
- default:
- $proposal_status = t('Unkown');
- break;
- } //$proposal_data->proposal_status
+ $proposal_status = $statuses[$proposal_data->proposal_status] ?? $this->t('Unknown');
$form['proposal_status'] = [
'#type' => 'item',
'#markup' => $proposal_status,
- '#title' => t('Proposal Status'),
+ '#title' => $this->t('Proposal Status'),
];
+
if ($proposal_data->proposal_status == 2) {
$form['message'] = [
'#type' => 'item',
'#markup' => $proposal_data->message,
- '#title' => t('Reason for disapproval'),
+ '#title' => $this->t('Reason for disapproval'),
];
- } //$proposal_data->proposal_status == 2
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $proposal_id);
- $query->orderBy('pref_number', 'ASC');
- $preference_q_status = $query->execute()->fetchObject();
- if ($preference_q_status->submited_all_examples_code == 1) {
- $form['submit_all_code'] = [
- '#type' => 'checkbox',
- '#title' => t('Enable Code Submission for user '),
- '#description' => t('Check if user has not submitted all the book examples.'),
- ];
- $form['completed'] = [
- '#type' => 'hidden',
- '#value' => 0,
- ];
- } //$preference_q_status->submited_all_examples_code == 1
- else {
- if ($preference_q_status->submited_all_examples_code == 2) {
- if (($proposal_data->proposal_status == 1 || $proposal_data->proposal_status == 4) || $proposal_data->proposal_status == 5) {
+ }
+
+ // Re-query first preference for submission status.
+ $pref_status_query = $this->database->select('textbook_companion_preference', 'pref');
+ $pref_status_query->fields('pref');
+ $pref_status_query->condition('proposal_id', $proposal_id);
+ $pref_status_query->orderBy('pref_number', 'ASC');
+ $preference_q_status = $pref_status_query->execute()->fetchObject();
+
+ if ($preference_q_status) {
+ if ($preference_q_status->submited_all_examples_code == 1) {
+ $form['submit_all_code'] = [
+ '#type' => 'checkbox',
+ '#title' => $this->t('Enable Code Submission for user '),
+ '#description' => $this->t('Check if user has not submitted all the book examples.'),
+ ];
+ $form['completed'] = ['#type' => 'hidden', '#value' => 0];
+ }
+ elseif ($preference_q_status->submited_all_examples_code == 2) {
+ if (in_array($proposal_data->proposal_status, [1, 4, 5])) {
$form['completed'] = [
'#type' => 'checkbox',
- '#title' => t('Completed '),
- '#description' => t('Check if user has completed all the book examples.'),
+ '#title' => $this->t('Completed '),
+ '#description' => $this->t('Check if user has completed all the book examples.'),
];
- $form['submit_all_code'] = [
- '#type' => 'hidden',
- '#value' => 0,
- ];
- } //($proposal_data->proposal_status == 1 || $proposal_data->proposal_status == 4) || $proposal_data->proposal_status == 5
+ $form['submit_all_code'] = ['#type' => 'hidden', '#value' => 0];
+ }
}
- } //$preference_q_status->submited_all_examples_code == 2
+ }
+
if ($proposal_data->proposal_status == 0) {
+ $approve_url = Url::fromRoute('textbook_companion.proposal_approval_form', [], [
+ 'query' => ['proposal_id' => $proposal_id],
+ ]);
$form['approve'] = [
'#type' => 'item',
- '#markup' => l('Click here', 'textbook-companion/manage-proposal/approve/' . $proposal_id),
- '#title' => t('Approve'),
- ];
- $form['completed'] = [
- '#type' => 'hidden',
- '#value' => 0,
+ '#markup' => Link::fromTextAndUrl($this->t('Click here'), $approve_url)->toString(),
+ '#title' => $this->t('Approve'),
];
- $form['submit_all_code'] = [
- '#type' => 'hidden',
- '#value' => 0,
- ];
- } //$proposal_data->proposal_status == 0
- $form['proposal_id'] = [
- '#type' => 'hidden',
- '#value' => $proposal_id,
- ];
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => t('Submit'),
- ];
+ $form['completed'] = ['#type' => 'hidden', '#value' => 0];
+ $form['submit_all_code'] = ['#type' => 'hidden', '#value' => 0];
+ }
+
+ $form['proposal_id'] = ['#type' => 'hidden', '#value' => $proposal_id];
+ $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Submit')];
$form['cancel'] = [
- '#type' => 'item',
- '#markup' => l(t('Cancel'), 'textbook-companion/manage-proposal/all'),
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute('textbook_companion._proposal_all'),
+ '#attributes' => ['class' => ['button']],
];
+
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- $proposal_id = $form_state->getValue(['proposal_id']);
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $proposal_id = $form_state->getValue('proposal_id');
+
+ $query = $this->database->select('textbook_companion_proposal', 'p');
+ $query->fields('p');
$query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if (!$proposal_data = $proposal_q->fetchObject()) {
- drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error');
- drupal_goto('textbook-companion/manage-proposal');
+ $proposal_data = $query->execute()->fetchObject();
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirect('textbook_companion._proposal_all');
return;
- } //!$proposal_data = $proposal_q->fetchObject()
- if ($form_state->getValue(['submit_all_code']) == 1) {
- /*db_query("UPDATE {textbook_companion_proposal} SET proposal_status = 3 WHERE id = %d", $proposal_id);*/
- $query = db_update('textbook_companion_preference');
- $query->fields(['submited_all_examples_code' => 0]);
- $query->condition('proposal_id', $proposal_id);
- $num_updated = $query->execute();
- /* sending email */
- $book_user = user_load($proposal_data->uid);
- $email_to = $book_user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_bcc_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $book_user = user_load($proposal_data->uid);
- $params['all_code_submitted_status_changed']['proposal_id'] = $proposal_id;
- $params['all_code_submitted_status_changed']['user_id'] = $proposal_data->uid;
- $params['all_code_submitted_status_changed']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'all_code_submitted_status_changed', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ }
+
+ $proposal_user = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+
+ if ($form_state->getValue('submit_all_code') == 1) {
+ $this->database->update('textbook_companion_preference')
+ ->fields(['submited_all_examples_code' => 0])
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
+
+ if ($proposal_user) {
+ $params['all_code_submitted_status_changed']['proposal_id'] = $proposal_id;
+ $params['all_code_submitted_status_changed']['user_id'] = $proposal_data->uid;
+ if (!$this->mailService->sendMail('textbook_companion', 'all_code_submitted_status_changed', $proposal_user->getEmail(), $params)) {
+ $this->messenger->addError($this->t('Error sending email message.'));
+ }
}
- drupal_set_message('User has been notified of that code submission interface is now available .', 'status');
- drupal_goto('textbook-companion/manage-proposal');
- return;
- } //$form_state['values']['submit_all_code'] == 1
- else {
- if ($form_state->getValue(['completed']) == 1) {
- /* set the book status to completed */
- /*db_query("UPDATE {textbook_companion_proposal} SET proposal_status = 3 WHERE id = %d", $proposal_id);*/
- $query = db_update('textbook_companion_proposal');
- $query->fields([
- 'proposal_status' => 3,
- 'completion_date' => time(),
- ]);
- $query->condition('id', $proposal_id);
- $num_updated = $query->execute();
+ $this->messenger->addStatus($this->t('User has been notified that code submission interface is now available.'));
+ }
+ elseif ($form_state->getValue('completed') == 1) {
+ $this->database->update('textbook_companion_proposal')
+ ->fields(['proposal_status' => 3, 'completion_date' => time()])
+ ->condition('id', $proposal_id)
+ ->execute();
+
+ if (function_exists('CreateReadmeFileTextbookCompanion')) {
CreateReadmeFileTextbookCompanion($proposal_id);
- /* sending email */
- $book_user = user_load($proposal_data->uid);
- $email_to = $book_user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $param['proposal_completed']['proposal_id'] = $proposal_id;
- $param['proposal_completed']['user_id'] = $proposal_data->uid;
- $param['proposal_completed']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'proposal_completed', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ }
+
+ if ($proposal_user) {
+ $params['proposal_completed']['proposal_id'] = $proposal_id;
+ $params['proposal_completed']['user_id'] = $proposal_data->uid;
+ if (!$this->mailService->sendMail('textbook_companion', 'proposal_completed', $proposal_user->getEmail(), $params)) {
+ $this->messenger->addError($this->t('Error sending email message.'));
}
- drupal_set_message('Congratulations! Book proposal has been marked as completed. User has been notified of the completion.', 'status');
- } //$form_state['values']['completed'] == 1
- else {
- drupal_set_message('Please select any one action.', 'error');
- drupal_goto('textbook-companion/manage-proposal/status/' . $proposal_id);
- return;
}
+ $this->messenger->addStatus($this->t('Congratulations! Book proposal has been marked as completed. User has been notified of the completion.'));
}
- drupal_goto('textbook-companion/manage-proposal');
- return;
+ else {
+ $this->messenger->addError($this->t('Please select any one action.'));
+ $form_state->setRedirect('textbook_companion.proposal_status_form', [], [
+ 'query' => ['proposal_id' => $proposal_id],
+ ]);
+ return;
+ }
+
+ $form_state->setRedirect('textbook_companion._proposal_all');
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionBrowseCollegeForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionBrowseCollegeForm.php
index 8000f07..208eddc 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionBrowseCollegeForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionBrowseCollegeForm.php
@@ -9,10 +9,28 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class TextbookCompanionBrowseCollegeForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $database;
+
+ public function __construct(Connection $database) {
+ $this->database = $database;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -20,48 +38,68 @@ public function getFormId() {
return 'textbook_companion_browse_college_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $form = [];
- ahah_helper_register($form, $form_state);
- if ($form_state->getStorage()) {
- $usage_default_value = '0';
- }
- else {
- $usage_default_value = $form_state->getStorage();
- }
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $usage_default_value = $form_state->getValue('college') ?? '0';
+
$form['college_info'] = [
'#type' => 'fieldset',
'#prefix' => '',
'#suffix' => '
',
'#tree' => TRUE,
];
+
+ // Build college options from module function if available.
+ $college_options = ['0' => $this->t('- Select -')];
+ if (function_exists('_list_of_colleges')) {
+ $college_options = _list_of_colleges();
+ }
+
$form['college_info']['college'] = [
'#type' => 'select',
- '#title' => t('College Name'),
- '#options' => _list_of_colleges(),
+ '#title' => $this->t('College Name'),
+ '#options' => $college_options,
'#default_value' => $usage_default_value,
- '#ahah' => [
- 'event' => 'change',
- 'path' => ahah_helper_path([
- 'college_info'
- ]),
+ '#ajax' => [
+ 'callback' => '::ajaxCollegeChanged',
'wrapper' => 'college-info-wrapper',
+ 'event' => 'change',
],
];
+
if ($usage_default_value != '0') {
+ $books = '';
+ if (function_exists('_list_books_by_college')) {
+ $books = _list_books_by_college($usage_default_value);
+ }
$form['college_info']['book_details'] = [
'#type' => 'item',
- '#value' => _list_books_by_college($usage_default_value),
+ '#markup' => $books,
];
}
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ /**
+ * AJAX callback for college select change.
+ */
+ public function ajaxCollegeChanged(array &$form, FormStateInterface $form_state) {
+ return $form['college_info'];
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionProposalForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionProposalForm.php
new file mode 100644
index 0000000..26b6ab1
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionProposalForm.php
@@ -0,0 +1,494 @@
+database = $database;
+ $this->currentUser = $current_user;
+ $this->configFactory = $config_factory;
+ $this->mailService = $mail_service;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user'),
+ $container->get('config.factory'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
+ public function getFormId() {
+ return 'book_proposal_form';
+ }
+
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $form['#attributes'] = ['enctype' => 'multipart/form-data'];
+
+ $form['imp_notice'] = [
+ '#type' => 'item',
+ '#markup' => 'Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion ',
+ ];
+ $form['full_name'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Full Name'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE,
+ ];
+ $form['email_id'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Email'),
+ '#size' => 30,
+ '#default_value' => $this->currentUser->getEmail(),
+ '#disabled' => TRUE,
+ ];
+ $form['mobile'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Mobile No.'),
+ '#size' => 30,
+ '#maxlength' => 15,
+ '#required' => TRUE,
+ ];
+ $form['gender'] = [
+ '#type' => 'radios',
+ '#title' => $this->t('Gender'),
+ '#options' => ['M' => 'Male', 'F' => 'Female'],
+ '#required' => TRUE,
+ ];
+ $form['how_project'] = [
+ '#type' => 'select',
+ '#title' => $this->t('How did you come to know about this project'),
+ '#options' => [
+ 'DWSIM Website' => 'DWSIM Website',
+ 'Friend' => 'Friend',
+ 'Professor/Teacher' => 'Professor/Teacher',
+ 'Mailing List' => 'Mailing List',
+ 'Poster in my/other college' => 'Poster in my/other college',
+ 'Others' => 'Others',
+ ],
+ '#required' => TRUE,
+ ];
+ $form['course'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Course'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE,
+ ];
+ $form['branch'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Department/Branch'),
+ '#options' => function_exists('_list_of_departments') ? _list_of_departments() : [],
+ '#required' => TRUE,
+ ];
+ $form['university'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('University/ Institute'),
+ '#size' => 80,
+ '#maxlength' => 200,
+ '#required' => TRUE,
+ '#attributes' => ['placeholder' => 'Insert full name of your institute/ university.... '],
+ ];
+ $form['country'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Country'),
+ '#options' => ['India' => 'India', 'Others' => 'Others'],
+ '#required' => TRUE,
+ ];
+ $form['other_country'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Other than India'),
+ '#size' => 100,
+ '#attributes' => ['placeholder' => $this->t('Enter your country name')],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'Others']]],
+ ];
+ $form['other_state'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('State other than India'),
+ '#size' => 100,
+ '#attributes' => ['placeholder' => $this->t('Enter your state/region name')],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'Others']]],
+ ];
+ $form['other_city'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('City other than India'),
+ '#size' => 100,
+ '#attributes' => ['placeholder' => $this->t('Enter your city name')],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'Others']]],
+ ];
+ $form['all_state'] = [
+ '#type' => 'select',
+ '#title' => $this->t('State'),
+ '#options' => function_exists('_list_of_states') ? _list_of_states() : [],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'India']]],
+ ];
+ $form['city'] = [
+ '#type' => 'select',
+ '#title' => $this->t('City'),
+ '#options' => function_exists('_list_of_cities') ? _list_of_cities() : [],
+ '#states' => ['visible' => [':input[name="country"]' => ['value' => 'India']]],
+ ];
+ $form['pincode'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Pincode'),
+ '#size' => 30,
+ '#maxlength' => 6,
+ '#attributes' => ['placeholder' => 'Enter pincode....'],
+ ];
+ $form['hr'] = ['#type' => 'item', '#markup' => ' '];
+ $form['faculty'] = ['#type' => 'hidden', '#value' => 'None'];
+ $form['faculty_email'] = ['#type' => 'hidden', '#value' => 'None@email.com'];
+ $form['reviewer'] = ['#type' => 'hidden', '#value' => 'None'];
+ $form['version'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Version'),
+ '#options' => function_exists('_list_of_software_version') ? _list_of_software_version() : [],
+ '#required' => TRUE,
+ ];
+ $form['older'] = [
+ '#type' => 'textfield',
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#description' => $this->t('Specify the Older version used'),
+ '#states' => ['visible' => [':input[name="version"]' => ['value' => 'olderversion']]],
+ ];
+ $form['completion_date'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Expected Date of Completion'),
+ '#description' => $this->t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'),
+ '#size' => 10,
+ '#maxlength' => 10,
+ ];
+ $form['operating_system'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Operating System'),
+ '#required' => TRUE,
+ '#size' => 30,
+ '#maxlength' => 50,
+ ];
+ $form['reason'] = [
+ '#type' => 'checkboxes',
+ '#title' => $this->t('Reasons'),
+ '#options' => [
+ 'Used in more than one University' => $this->t('Used in more than one University'),
+ 'The book has multiple editions' => $this->t('The book has multiple editions'),
+ 'Extremely useful' => $this->t('Extremely useful'),
+ 'Other reason' => $this->t('Any other reason state below'),
+ ],
+ '#required' => TRUE,
+ ];
+ $form['other_reason'] = [
+ '#type' => 'textarea',
+ '#states' => ['visible' => [':input[name="reason[Other reason]"]' => ['checked' => TRUE]]],
+ ];
+ $form['proposal_type'] = ['#type' => 'hidden', '#default_value' => '1'];
+ $form['reference'] = [
+ '#type' => 'textarea',
+ '#title' => $this->t('Reference'),
+ '#required' => TRUE,
+ '#attributes' => ['placeholder' => 'Links of the syllabus must be provided....'],
+ ];
+ $form['form_type'] = ['#type' => 'hidden', '#value' => 1];
+
+ $form['preference1'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Book Preference'),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE,
+ ];
+ $form['preference1']['book1'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Title of the book'),
+ '#size' => 30,
+ '#maxlength' => 100,
+ '#required' => TRUE,
+ ];
+ $form['preference1']['author1'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Author Name'),
+ '#size' => 30,
+ '#maxlength' => 100,
+ '#required' => TRUE,
+ ];
+ $form['preference1']['isbn1'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('ISBN No'),
+ '#size' => 30,
+ '#maxlength' => 25,
+ '#required' => TRUE,
+ ];
+ $form['preference1']['publisher1'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Publisher & Place'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE,
+ ];
+ $form['preference1']['edition1'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Edition'),
+ '#size' => 4,
+ '#maxlength' => 2,
+ '#required' => TRUE,
+ ];
+ $form['preference1']['year1'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Year of publication'),
+ '#size' => 4,
+ '#maxlength' => 4,
+ '#required' => TRUE,
+ ];
+
+ $ext = $this->configFactory->get('textbook_companion.settings')->get('textbook_companion_source_extensions');
+ if (!$ext && function_exists('tc_variable_get')) {
+ $ext = tc_variable_get('textbook_companion_source_extensions', '');
+ }
+ $form['samplefile'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Sample Source Files'),
+ ];
+ $form['samplefile']['samplefile1'] = [
+ '#type' => 'file',
+ '#title' => $this->t('Upload sample source file'),
+ '#size' => 48,
+ '#description' => $this->t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . 'Allowed file extensions : ' . $ext . ' ',
+ ];
+ $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Submit')];
+ $form['dir_name'] = ['#type' => 'hidden', '#value' => 'None'];
+
+ return $form;
+ }
+
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state->getValue('mobile'))) {
+ $form_state->setErrorByName('mobile', $this->t('Invalid mobile number'));
+ }
+ if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state->getValue('completion_date'))) {
+ $form_state->setErrorByName('completion_date', $this->t('Invalid expected date of completion'));
+ }
+ $date_parts = explode('-', (string) $form_state->getValue('completion_date'));
+ if (count($date_parts) === 3) {
+ list($d, $m, $y) = $date_parts;
+ $d = (int) $d;
+ $m = (int) $m;
+ $y = (int) $y;
+ if (!checkdate($m, $d, $y)) {
+ $form_state->setErrorByName('completion_date', $this->t('Invalid expected date of completion'));
+ }
+ if (mktime(0, 0, 0, $m, $d, $y) <= time()) {
+ $form_state->setErrorByName('completion_date', $this->t('Expected date of completion should be in future'));
+ }
+ }
+
+ $cur_year = date('Y');
+ if (!preg_match('/^[A-Za-z]/', $form_state->getValue('book1'))) {
+ $form_state->setErrorByName('book1', $this->t('Invalid book name for Book Preference 1'));
+ }
+ if (!preg_match('/^[0-9\-xX]+$/', $form_state->getValue('isbn1'))) {
+ $form_state->setErrorByName('isbn1', $this->t('Invalid ISBN for Book Preference 1'));
+ }
+ if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state->getValue('edition1'))) {
+ $form_state->setErrorByName('edition1', $this->t('Invalid edition for Book Preference 1'));
+ }
+ if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state->getValue('year1'))) {
+ $form_state->setErrorByName('year1', $this->t('Invalid year of publication for Book Preference 1'));
+ }
+ if ((int) $form_state->getValue('year1') > $cur_year) {
+ $form_state->setErrorByName('year1', $this->t('Year of publication should not be in the future for Book Preference 1'));
+ }
+
+ $bk1 = trim((string) $form_state->getValue('book1'));
+ $auth1 = trim((string) $form_state->getValue('author1'));
+ if ($bk1 && $auth1 && function_exists('_dir_name')) {
+ $dir = _dir_name($bk1, $auth1, NULL, $form_state);
+ if ($dir != NULL) {
+ $form_state->setValue('dir_name1', $dir);
+ }
+ }
+
+ if ($form_state->getValue('version') == 'olderversion' && $form_state->getValue('older') == '') {
+ $form_state->setErrorByName('older', $this->t('Please provide valid version'));
+ }
+
+ $files = $this->getRequest()->files->get('files', []);
+ $sample = is_array($files) ? ($files['samplefile1'] ?? NULL) : NULL;
+ if (!$sample || (is_object($sample) && !$sample->getClientOriginalName())) {
+ // Fall back to $_FILES for legacy upload field name.
+ if (empty($_FILES['files']['name']['samplefile1'])) {
+ $form_state->setErrorByName('samplefile1', $this->t('Please upload sample code main or source file.'));
+ }
+ }
+ if (!empty($_FILES['files']['name'])) {
+ foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
+ if ($file_name) {
+ $allowed_extensions_str = function_exists('tc_variable_get')
+ ? tc_variable_get('textbook_companion_source_extensions', '')
+ : (string) $this->configFactory->get('textbook_companion.settings')->get('textbook_companion_source_extensions');
+ $allowed_extensions = array_filter(array_map('trim', explode(',', $allowed_extensions_str)));
+ $fnames = explode('.', strtolower($file_name));
+ $temp_extension = end($fnames);
+ if ($allowed_extensions && !in_array($temp_extension, $allowed_extensions)) {
+ $form_state->setErrorByName($file_form_name, $this->t('Only files with @ext extensions can be uploaded.', ['@ext' => $allowed_extensions_str]));
+ }
+ if ($_FILES['files']['size'][$file_form_name] <= 0) {
+ $form_state->setErrorByName($file_form_name, $this->t('File size cannot be zero.'));
+ }
+ if (function_exists('textbook_companion_check_valid_filename') && !textbook_companion_check_valid_filename($file_name)) {
+ $form_state->setErrorByName($file_form_name, $this->t('Invalid file name specified. Only alphabets and numbers are allowed as a valid filename.'));
+ }
+ }
+ }
+ }
+ }
+
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $uid = $this->currentUser->id();
+ if (!$uid) {
+ $this->messenger()->addError($this->t('It is mandatory to login on this website to access the proposal form'));
+ return;
+ }
+
+ $root_path = function_exists('textbook_companion_samplecode_path')
+ ? textbook_companion_samplecode_path()
+ : '';
+
+ $date_parts = explode('-', (string) $form_state->getValue('completion_date'));
+ $completion_date_timestamp = time();
+ if (count($date_parts) === 3) {
+ list($d, $m, $y) = $date_parts;
+ $completion_date_timestamp = mktime(0, 0, 0, (int) $m, (int) $d, (int) $y);
+ }
+
+ $dwsim_version = $form_state->getValue('version');
+ if ($dwsim_version == 'olderversion') {
+ $dwsim_version = $form_state->getValue('older');
+ }
+
+ $country = $form_state->getValue('country');
+ $state = $form_state->getValue('all_state');
+ // Preserve legacy comparison exactly.
+ if ($country == 'other') {
+ $country = trim((string) $form_state->getValue('other_country'));
+ $state = trim((string) $form_state->getValue('other_state'));
+ }
+
+ $reason_vals = $form_state->getValue('reason') ?: [];
+ $selected = array_filter(is_array($reason_vals) ? $reason_vals : []);
+ $my_reason = implode(', ', array_keys($selected));
+ $other_reason = $form_state->getValue('other_reason');
+ if ($other_reason) {
+ $my_reason .= '- ' . $other_reason;
+ }
+
+ $fields = [
+ 'uid' => $uid,
+ 'approver_uid' => 0,
+ 'full_name' => trim(ucwords(strtolower($form_state->getValue('full_name')))),
+ 'mobile' => trim($form_state->getValue('mobile')),
+ 'gender' => $form_state->getValue('gender'),
+ 'how_project' => $form_state->getValue('how_project'),
+ 'course' => trim($form_state->getValue('course')),
+ 'branch' => $form_state->getValue('branch'),
+ 'university' => trim($form_state->getValue('university')),
+ 'city' => trim((string) $form_state->getValue('city')),
+ 'pincode' => $form_state->getValue('pincode'),
+ 'state' => trim((string) $state),
+ 'country' => $country,
+ 'faculty' => ucwords(strtolower($form_state->getValue('faculty') ?: 'None')),
+ 'reviewer' => 'DWSIM TBC Team',
+ 'reference' => trim($form_state->getValue('reference')),
+ 'completion_date' => $completion_date_timestamp,
+ 'creation_date' => time(),
+ 'approval_date' => 0,
+ 'proposal_status' => 0,
+ 'dwsim_version' => trim($dwsim_version),
+ 'operating_system' => trim($form_state->getValue('operating_system')),
+ 'teacher_email' => $form_state->getValue('faculty_email'),
+ 'reason' => $my_reason,
+ 'samplefilepath' => '',
+ 'proposal_type' => 0,
+ 'proposed_completion_date' => $completion_date_timestamp,
+ ];
+
+ $result = $this->database->insert('textbook_companion_proposal')->fields($fields)->execute();
+
+ // Preference row required by approval/upload pipeline (same fields as nonaicte path).
+ if ($form_state->getValue('book1')) {
+ $pref_fields = [
+ 'proposal_id' => $result,
+ 'pref_number' => 1,
+ 'book' => ucwords(strtolower($form_state->getValue('book1'))),
+ 'author' => ucwords(strtolower($form_state->getValue('author1'))),
+ 'isbn' => $form_state->getValue('isbn1'),
+ 'publisher' => ucwords(strtolower($form_state->getValue('publisher1'))),
+ 'edition' => $form_state->getValue('edition1'),
+ 'year' => $form_state->getValue('year1'),
+ 'category' => 0,
+ 'approval_status' => 0,
+ 'directory_name' => $form_state->getValue('dir_name1') ?: '',
+ 'nonaicte_book' => 0,
+ ];
+ $this->database->insert('textbook_companion_preference')->fields($pref_fields)->execute();
+ }
+
+ $dest_path = $result . '/';
+ if ($root_path && !is_dir($root_path . $dest_path)) {
+ mkdir($root_path . $dest_path);
+ }
+ if (!empty($_FILES['files']['name'])) {
+ foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
+ if ($file_name && $root_path) {
+ $dest_file = $root_path . $dest_path . $file_name;
+ if (file_exists($dest_file)) {
+ unlink($dest_file);
+ }
+ if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $dest_file)) {
+ $this->database->update('textbook_companion_proposal')
+ ->fields(['samplefilepath' => $dest_path . $file_name])
+ ->condition('id', $result)
+ ->execute();
+ }
+ }
+ }
+ }
+
+ $params = [];
+ $params['proposal_received']['proposal_id'] = $result;
+ $params['proposal_received']['user_id'] = $uid;
+ $this->mailService->sendMail('textbook_companion', 'proposal_received', $this->currentUser->getEmail(), $params);
+
+ $this->messenger()->addStatus($this->t('We have received your book proposal. We will get back to you soon.'));
+ $form_state->setRedirectUrl(Url::fromRoute(''));
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionRunForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionRunForm.php
index b987463..8921e14 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionRunForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionRunForm.php
@@ -1,17 +1,60 @@
database = $database;
+ $this->requestStack = $request_stack;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('request_stack')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -19,450 +62,304 @@ public function getFormId() {
return 'textbook_companion_run_form';
}
-
- public function buildForm(array $form, FormStateInterface $form_state) {
- $url_book_pref_id = \Drupal::request()->attributes->get('book_pref_id') ?? 0;
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $url_book_pref_id = $this->requestStack->getCurrentRequest()->attributes->get('book_pref_id') ?? 0;
$category_default_value = 0;
if ($url_book_pref_id) {
- $query = \Drupal::database()->select('textbook_companion_preference', 't');
- $query->fields('t', ['category']);
- $query->condition('id', $url_book_pref_id);
- $result = $query->execute()->fetchObject();
+ $result = $this->database->select('textbook_companion_preference', 't')
+ ->fields('t', ['category'])
+ ->condition('id', $url_book_pref_id)
+ ->execute()->fetchObject();
$category_default_value = $result ? $result->category : 0;
}
// Values from form_state (AJAX) or route attribute defaults.
- $selected_book = (int) ($form_state->getValue('book') ?: $url_book_pref_id);
- // $selected_chapter = (int) $form_state->getValue('chapter');
- //$selected_example = (int) $form_state->getValue('example');
+ $selected_book = (int) ($form_state->getValue('book') ?: $url_book_pref_id);
+ $selected_chapter = (int) $form_state->getValue('chapter');
+ $selected_example = (int) ($form_state->getValue('examples') ?? 0);
-
- // var_dump($url_book_pref_id);die;
- // var_dump($selected_book);die;
- // BOOK select (top-level)
+ // Book select (top-level).
$form['book'] = [
- '#type' => 'select',
- '#title' => $this->t('Title of the book'),
- '#options' => $this->_list_of_books($category_default_value),
+ '#type' => 'select',
+ '#title' => $this->t('Title of the book'),
+ '#options' => $this->_list_of_books($category_default_value),
'#default_value' => $selected_book,
- '#ajax' => [
+ '#ajax' => [
'callback' => '::ajax_book_changed_callback',
- 'wrapper' => 'textbook-book-wrapper',
- 'event' => 'change',
+ 'wrapper' => 'textbook-book-wrapper',
+ 'event' => 'change',
],
];
- // BOOK WRAPPER (contains book info, chapter select & chapter download)
+ // Book wrapper (contains book info, chapter select & chapter download).
$form['book_wrapper'] = [
- '#type' => 'container',
+ '#type' => 'container',
'#attributes' => ['id' => 'textbook-book-wrapper'],
];
if ($selected_book) {
- // Book info markup
$form['book_wrapper']['book_info'] = [
- '#type' => 'markup',
+ '#type' => 'markup',
'#markup' => $this->_html_book_info($selected_book),
];
- // Download Book link
$form['book_wrapper']['download_book'] = [
- '#type' => 'markup',
+ '#type' => 'markup',
'#markup' => Link::fromTextAndUrl(
$this->t('Download Book'),
Url::fromRoute('textbook_companion.download_book', ['book_id' => $selected_book])
)->toString(),
];
-$selected_chapter = (int) $form_state->getValue('chapter');
- // Chapter select
+ // Chapter select.
$form['book_wrapper']['chapter'] = [
- '#type' => 'select',
- '#title' => $this->t('Title of the chapter'),
- '#options' => $this->_list_of_chapters($selected_book),
+ '#type' => 'select',
+ '#title' => $this->t('Title of the chapter'),
+ '#options' => $this->_list_of_chapters($selected_book),
'#default_value' => $selected_chapter,
- '#ajax' => [
+ '#ajax' => [
'callback' => '::ajax_chapter_changed_callback',
- 'wrapper' => 'chapter-download-wrapper',
- 'event' => 'change',
+ 'wrapper' => 'chapter-download-wrapper',
+ 'event' => 'change',
],
];
- // Chapter-download wrapper (inside book_wrapper)
+ // Chapter-download wrapper (inside book_wrapper).
$form['chapter_download'] = [
- '#type' => 'container',
+ '#type' => 'container',
'#attributes' => ['id' => 'chapter-download-wrapper'],
];
if ($selected_chapter) {
$form['chapter_download']['link'] = [
- '#type' => 'markup',
+ '#type' => 'markup',
'#markup' => Link::fromTextAndUrl(
$this->t('Download Chapter'),
Url::fromRoute('textbook_companion.download_chapter', ['chapter_id' => $selected_chapter])
)->toString(),
];
}
-
}
- // var_dump($selected_chapter);die;
-
- $selected_example = (int)$form_state->getValue('examples') ?? 0;
-
- // var_dump($selected_example);die;
-
- // if ($selected_chapter) {
-
- // Example dropdown
- $form['chapter_download']['examples'] = [
- '#type' => 'select',
- '#title' => $this->t('Name of the example'),
- '#options' => $this->_list_of_examples($selected_chapter, $selected_example),
- '#default_value' => $selected_example,
- '#ajax' => [
- 'callback' => '::ajax_example_changed_callback',
- 'wrapper' => 'download-example-link-wrapper',
- 'event' => 'change',
- ],
- ];
-
-
- // Download example + files wrapper
- $form['download_example_wrapper'] = [
- '#type' => 'container',
- '#attributes' => ['id' => 'download-example-link-wrapper'],
- ];
-
- // if ($selected_example) {
-if (!empty($selected_example)) {
- // Download link
- $form['download_example_wrapper']['download_example'] = [
- '#type' => 'markup',
- '#markup' => Link::fromTextAndUrl(
- $this->t('Download Example (OpenFOAM code)'),
- Url::fromRoute('textbook_companion.download_example', ['example_id' => $selected_example])
- )->toString(),
+ // Example dropdown.
+ $form['chapter_download']['examples'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Name of the example'),
+ '#options' => $this->_list_of_examples($selected_chapter, $selected_example),
+ '#default_value' => $selected_example,
+ '#ajax' => [
+ 'callback' => '::ajax_example_changed_callback',
+ 'wrapper' => 'download-example-link-wrapper',
+ 'event' => 'change',
+ ],
];
-
-
-// $query = \Drupal::database()->select('textbook_companion_example_files', 'f');
-// $query->fields('f');
-// $query->condition('example_id', $selected_example);
-// $result = $query->execute()->fetchAll();
-
-// \Drupal::logger('tbc_debug')->notice('Example ID: @id, Found @count files', [
-// '@id' => $selected_example,
-// '@count' => count($result),
-// ]);
-// ✅ Example files table rendering
-// if (!empty($selected_example)) {
-// $query = \Drupal::database()->select('textbook_companion_example_files', 'f');
-// $query->fields('f');
-// $query->condition('example_id', $selected_example);
-// $files = $query->execute()->fetchAll();
-
-// // If there are results
-// if (!empty($files)) {
-// $rows = [];
-// foreach ($files as $file) {
-// switch ($file->filetype) {
-// case 'S': $type = 'Source or Main file'; break;
-// case 'R': $type = 'Result file'; break;
-// case 'X': $type = 'xcos file'; break;
-// default: $type = 'Unknown'; break;
-// }
-
-// $example_files_rows[] = [
-// Link::fromTextAndUrl(
-// $file->filename,
-// Url::fromUserInput('/textbook-companion/download/file/' . $files->id)
-// )->toString(),
-// $type,
-
-// ];
-
-
-// }
-
-// // ✅ Wrap table in container
-// $form['download_example_wrapper']['example_files'] = [
-// '#type' => 'fieldset',
-// '#title' => $this->t('List of Example Files'),
-// '#attributes' => ['id' => 'ajax-download-example-files-replace'],
-// 'table' => [
-// '#type' => 'table',
-// '#header' => [$this->t('Filename'), $this->t('Type')],
-// '#rows' => $rows,
-// '#attributes' =>[
-// 'style' => 'width: 100%;',
-// ],
-
-// '#empty' => $this->t('No files found for this example.'),
-// ],
-// ];
-// }
-// }
-
-
-
-if (!empty($selected_example)) {
- $query = \Drupal::database()->select('textbook_companion_example_files', 'f');
- $query->fields('f');
- $query->condition('example_id', $selected_example);
- $files = $query->execute()->fetchAll();
-
- if (!empty($files)) {
- $rows = [];
-
- foreach ($files as $file) {
- // Map file type to label
- switch ($file->filetype) {
- case 'S': $type = 'Source or Main file'; break;
- case 'R': $type = 'Result file'; break;
- case 'X': $type = 'xcos file'; break;
- default: $type = 'Unknown'; break;
- }
-
- // Ensure you have correct ID field name in your table
- $file_id = $file->id ?? $file->example_file_id ?? NULL;
- // Create link to download file
- $link = Link::fromTextAndUrl(
- $file->filename,
- Url::fromUserInput('/textbook-companion/download/file/' . $file_id)
- )->toRenderable();
+ // Download example + files wrapper.
+ $form['download_example_wrapper'] = [
+ '#type' => 'container',
+ '#attributes' => ['id' => 'download-example-link-wrapper'],
+ ];
- // Add row to the table
- $rows[] = [
- 'filename' => ['data' => $link],
- 'type' => ['data' => ['#markup' => $type]],
+ if (!empty($selected_example)) {
+ $form['download_example_wrapper']['download_example'] = [
+ '#type' => 'markup',
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Download Example (OpenFOAM code)'),
+ Url::fromRoute('textbook_companion.download_example', ['example_id' => $selected_example])
+ )->toString(),
];
+
+ // Example files table.
+ $files = $this->database->select('textbook_companion_example_files', 'f')
+ ->fields('f')
+ ->condition('example_id', $selected_example)
+ ->execute()->fetchAll();
+
+ if (!empty($files)) {
+ $rows = [];
+ foreach ($files as $file) {
+ switch ($file->filetype) {
+ case 'S': $type = 'Source or Main file'; break;
+ case 'R': $type = 'Result file'; break;
+ case 'X': $type = 'xcos file'; break;
+ default: $type = 'Unknown'; break;
+ }
+ $file_id = $file->id ?? NULL;
+ $link = Link::fromTextAndUrl(
+ $file->filename,
+ Url::fromUserInput('/textbook-companion/download/file/' . $file_id)
+ )->toRenderable();
+ $rows[] = [
+ 'filename' => ['data' => $link],
+ 'type' => ['data' => ['#markup' => $type]],
+ ];
+ }
+
+ $form['download_example_wrapper']['example_files'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('List of Example Files'),
+ '#attributes' => ['id' => 'ajax-download-example-files-replace'],
+ 'table' => [
+ '#type' => 'table',
+ '#header' => [$this->t('Filename'), $this->t('Type')],
+ '#rows' => $rows,
+ '#empty' => $this->t('No files found for this example.'),
+ '#attributes' => ['style' => 'width: 100%;'],
+ ],
+ ];
+ }
}
- // Wrap table in container
- $form['download_example_wrapper']['example_files'] = [
- '#type' => 'fieldset',
- '#title' => $this->t('List of Example Files'),
- '#attributes' => ['id' => 'ajax-download-example-files-replace'],
- 'table' => [
- '#type' => 'table',
- '#header' => [$this->t('Filename'), $this->t('Type')],
- '#rows' => $rows,
- '#empty' => $this->t('No files found for this example.'),
- '#attributes' => ['style' => 'width: 100%;'],
- ],
- ];
+ return $form;
}
-}
-
-
- } return $form;
- }
// ---------------------------
// AJAX CALLBACKS
// ---------------------------
+ /**
+ * Returns the book wrapper after book change.
+ */
public function ajax_book_changed_callback(array &$form, FormStateInterface $form_state) {
return $form['book_wrapper'];
}
+ /**
+ * Returns the chapter download wrapper after chapter change.
+ */
public function ajax_chapter_changed_callback(array &$form, FormStateInterface $form_state) {
return $form['chapter_download'];
}
-public function ajax_example_changed_callback(array &$form, FormStateInterface $form_state) {
- // $selected_example = (int) $form_state->getValue('examples') ?? 0;
- // $selected_chapter = (int) $form_state->getValue('chapter') ?? 0;
- $form_state->setRebuild(TRUE);
-
-// // Rebuild the examples select field with the correct options
- // $form['examples']['#options'] = $this->_list_of_examples($selected_chapter, $selected_example);
-// // Return the updated download example wrapper
-
- return $form['download_example_wrapper'];
- // return $form['download_example_wrapper'];
-}
+ /**
+ * Returns the download example wrapper after example change.
+ */
+ public function ajax_example_changed_callback(array &$form, FormStateInterface $form_state) {
+ $form_state->setRebuild(TRUE);
+ return $form['download_example_wrapper'];
+ }
- // ---------------------------
- // HELPER FUNCTIONS
+ // ---------------------------
+ // HELPER METHODS
// ---------------------------
+ /**
+ * Returns list of books for a given category.
+ */
public function _list_of_books($category_default_value = 0) {
$book_titles = [0 => $this->t('Please select ...')];
- $connection = \Drupal::database();
- $subquery = $connection->select('textbook_companion_proposal', 'tcp');
+ $subquery = $this->database->select('textbook_companion_proposal', 'tcp');
$subquery->fields('tcp', ['id']);
$subquery->condition('proposal_status', 3);
- $query = $connection->select('textbook_companion_preference', 'tcp');
+ $query = $this->database->select('textbook_companion_preference', 'tcp');
$query->fields('tcp', ['id', 'book', 'author']);
$query->condition('category', $category_default_value);
$query->condition('approval_status', 1);
$query->condition('proposal_id', $subquery, 'IN');
$query->orderBy('book', 'ASC');
- $results = $query->execute()->fetchAll();
- foreach ($results as $book) {
+ foreach ($query->execute()->fetchAll() as $book) {
$book_titles[$book->id] = $book->book . ' (Written by ' . $book->author . ')';
}
return $book_titles;
}
-
- // public function ajax_example_files_callback($example_id) {
- // if (!$example_id) {
- // return ['#markup' => ''];
- // }
-
- // $connection = \Drupal::database();
- // // Assuming the table name is 'textbook_companion_example_file'
- // $query = $connection->select('textbook_companion_example_file', 'tcef');
- // $query->fields('tcef', ['id', 'filename', 'filetype']);
- // $query->condition('example_id', $example_id);
- // $query->orderBy('filename', 'ASC');
- // $results = $query->execute()->fetchAll();
-
- // if (empty($results)) {
- // return ['#markup' => ''];
- // }
-
- // $header = [
- // 'filename' => $this->t('Filename'),
- // 'filetype' => $this->t('Type'),
- // ];
-
- // $rows = [];
- // foreach ($results as $file) {
- // $example_file_type = $this->t('Unknown');
- // switch ($file->filetype) {
- // case 'S':
- // $example_file_type = $this->t('Source or Main file');
- // break;
- // case 'R':
- // $example_file_type = $this->t('Result file');
- // break;
- // case 'X':
- // $example_file_type = $this->t('xcos file');
- // break;
- // }
-
- // // Create the linked filename. Adjust the route name if necessary.
- // $link = Link::fromTextAndUrl(
- // $file->filename,
- // Url::fromRoute('textbook_companion.download_file', ['file_id' => $file->id])
- // )->toString();
-
- // $rows[] = [
- // // Ensure rows are simple arrays or use the 'data' structure
- // // as necessary for your specific Drupal theme.
- // // Using a simple array for row data is often sufficient.
- // ['#markup' => $link],
- // ['#markup' => $example_file_type],
- // ];
- // }
-
- // return [
- // '#type' => 'table',
- // // ✅ REMOVED: Remove the '#caption' element to match the image.
- // '#header' => $header,
- // '#rows' => $rows,
- // // ✅ UPDATED: Add a custom class for styling the table header.
- // '#attributes' => ['class' => ['textbook-companion-files', 'textbook-companion-example-file-list']],
- // '#empty' => $this->t('No files found for this example.'),
- // ];
- // }
+ /**
+ * Returns book info HTML block for a given preference ID.
+ */
public function _html_book_info($preference_id) {
- $connection = \Drupal::database();
-
- $query = $connection->select('textbook_companion_proposal', 'proposal');
+ $query = $this->database->select('textbook_companion_proposal', 'proposal');
$query->leftJoin('textbook_companion_preference', 'preference', 'proposal.id = preference.proposal_id');
- $query->addField('preference', 'book', 'preference_book');
- $query->addField('preference', 'author', 'preference_author');
- $query->addField('preference', 'isbn', 'preference_isbn');
+ $query->addField('preference', 'book', 'preference_book');
+ $query->addField('preference', 'author', 'preference_author');
+ $query->addField('preference', 'isbn', 'preference_isbn');
$query->addField('preference', 'publisher', 'preference_publisher');
- $query->addField('preference', 'edition', 'preference_edition');
- $query->addField('preference', 'year', 'preference_year');
- $query->addField('proposal', 'full_name', 'proposal_full_name');
- $query->addField('proposal', 'faculty', 'proposal_faculty');
- $query->addField('proposal', 'reviewer', 'proposal_reviewer');
- $query->addField('proposal', 'course', 'proposal_course');
- $query->addField('proposal', 'branch', 'proposal_branch');
- $query->addField('proposal', 'university', 'proposal_university');
+ $query->addField('preference', 'edition', 'preference_edition');
+ $query->addField('preference', 'year', 'preference_year');
+ $query->addField('proposal', 'full_name', 'proposal_full_name');
+ $query->addField('proposal', 'faculty', 'proposal_faculty');
+ $query->addField('proposal', 'reviewer', 'proposal_reviewer');
+ $query->addField('proposal', 'course', 'proposal_course');
+ $query->addField('proposal', 'branch', 'proposal_branch');
+ $query->addField('proposal', 'university','proposal_university');
$query->condition('preference.id', $preference_id);
- $book_details = $query->execute()->fetchObject();
- if (!$book_details) {
+ $d = $query->execute()->fetchObject();
+ if (!$d) {
return '';
}
- $html_data = '';
- $html_data .= '';
- $html_data .= 'About the Book ';
- $html_data .= 'Author: ' . $book_details->preference_author . ' ';
- $html_data .= 'Title: ' . $book_details->preference_book . ' ';
- $html_data .= 'Publisher: ' . $book_details->preference_publisher . ' ';
- $html_data .= 'Year: ' . $book_details->preference_year . ' ';
- $html_data .= 'Edition: ' . $book_details->preference_edition . ' ';
- $html_data .= ' ';
- $html_data .= 'About the Contributor ';
- $html_data .= 'Name: ' . $book_details->proposal_full_name . ' ';
- $html_data .= 'Faculty: ' . $book_details->proposal_faculty . ' ';
- $html_data .= 'Reviewer: ' . $book_details->proposal_reviewer . ' ';
- $html_data .= 'Course: ' . $book_details->proposal_course . ', ' . $book_details->proposal_branch . ', ' . $book_details->proposal_university . ' ';
- $html_data .= '
';
-
- return $html_data;
+ $html = '';
+ $html .= 'About the Book ';
+ $html .= 'Author: ' . $d->preference_author . ' ';
+ $html .= 'Title: ' . $d->preference_book . ' ';
+ $html .= 'Publisher: ' . $d->preference_publisher . ' ';
+ $html .= 'Year: ' . $d->preference_year . ' ';
+ $html .= 'Edition: ' . $d->preference_edition . ' ';
+ $html .= ' ';
+ $html .= 'About the Contributor ';
+ $html .= 'Name: ' . $d->proposal_full_name . ' ';
+ $html .= 'Faculty: ' . $d->proposal_faculty . ' ';
+ $html .= 'Reviewer: ' . $d->proposal_reviewer . ' ';
+ $html .= 'Course: ' . $d->proposal_course . ', ' . $d->proposal_branch . ', ' . $d->proposal_university . ' ';
+ $html .= '
';
+
+ return $html;
}
+ /**
+ * Returns list of chapters for a given preference ID.
+ */
public function _list_of_chapters($preference_id = 0) {
$book_chapters = [0 => $this->t('Please select...')];
- if (!$preference_id) return $book_chapters;
+ if (!$preference_id) {
+ return $book_chapters;
+ }
- $connection = \Drupal::database();
- $query = $connection->select('textbook_companion_chapter', 'tcc');
+ $query = $this->database->select('textbook_companion_chapter', 'tcc');
$query->fields('tcc', ['id', 'name', 'number']);
$query->condition('preference_id', $preference_id);
$query->orderBy('number', 'ASC');
- $results = $query->execute()->fetchAll();
- foreach ($results as $chapter) {
+ foreach ($query->execute()->fetchAll() as $chapter) {
$book_chapters[$chapter->id] = $chapter->number . '. ' . $chapter->name;
}
return $book_chapters;
}
+ /**
+ * Returns list of approved examples for a given chapter ID.
+ */
public function _list_of_examples($chapter_id = 0, $selected_example = 0) {
- $examples = [0 => $this->t('Please select...')];
- if (!$chapter_id) {
- return $examples;
- }
+ $examples = [0 => $this->t('Please select...')];
+ if (!$chapter_id) {
+ return $examples;
+ }
- $connection = \Drupal::database();
- $query = $connection->select('textbook_companion_example', 'tce');
- $query->fields('tce', ['id', 'number', 'caption']);
- $query->condition('chapter_id', $chapter_id);
- $query->condition('approval_status', 1);
- $results = $query->execute()->fetchAll();
+ $query = $this->database->select('textbook_companion_example', 'tce');
+ $query->fields('tce', ['id', 'number', 'caption']);
+ $query->condition('chapter_id', $chapter_id);
+ $query->condition('approval_status', 1);
- foreach ($results as $example) {
- $examples[$example->id] = $example->number . '. ' . $example->caption;
- }
+ foreach ($query->execute()->fetchAll() as $example) {
+ $examples[$example->id] = $example->number . '. ' . $example->caption;
+ }
- // If the selected example is not in the list, add it manually
- // if ($selected_example && !isset($examples[$selected_example])) {
- // $examples[$selected_example] = $selected_example . ' (Selected)';
- // }
+ return $examples;
+ }
- return $examples;
-}
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ }
-
- public function submitForm(array &$form, FormStateInterface $form_state) {
- }
}
\ No newline at end of file
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSearchForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSearchForm.php
index 948bde6..a044633 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSearchForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSearchForm.php
@@ -9,114 +9,118 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class TextbookCompanionSearchForm extends FormBase {
- /**
- * {@inheritdoc}
- */
+ protected $database;
+
+ public function __construct(Connection $database) {
+ $this->database = $database;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static($container->get('database'));
+ }
+
public function getFormId() {
return 'textbook_companion_search_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $form['#redirect'] = FALSE;
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $request = \Drupal::request();
+ $search_term = $request->query->get('search') ?? '';
+ $by_title = $request->query->get('by_title') ?? 1;
+ $by_author = $request->query->get('by_author') ?? 1;
+
$form['search'] = [
'#type' => 'textfield',
- '#title' => t('Search'),
+ '#title' => $this->t('Search'),
'#size' => 48,
+ '#default_value' => $search_term,
];
$form['search_by_title'] = [
'#type' => 'checkbox',
- '#default_value' => TRUE,
- '#title' => t('Search by Title of the Book'),
+ '#default_value' => $by_title,
+ '#title' => $this->t('Search by Title of the Book'),
];
$form['search_by_author'] = [
'#type' => 'checkbox',
- '#default_value' => TRUE,
- '#title' => t('Search by Author of the Book'),
- ];
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => t('Search'),
+ '#default_value' => $by_author,
+ '#title' => $this->t('Search by Author of the Book'),
];
+ $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Search')];
$form['cancel'] = [
- '#type' => 'item',
- '#markup' => l(t('Cancel'), ''),
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute(''),
+ '#attributes' => ['class' => ['button']],
];
- if ($_POST) {
- $output = '';
- $search_rows = [];
- $search_query = '';
- if ($_POST['search_by_title'] && $_POST['search_by_author']) {
- /*$search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND (book LIKE '%%%s%%' OR author LIKE '%%%s%%')", $_POST['search'], $_POST['search']);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('approval_status', 1);
- $or = db_or();
- $or->condition('book', '%%' . $_POST['search'] . '%%', 'LIKE');
- $or->condition('author', '%%' . $_POST['search'] . '%%', 'LIKE');
+
+ if (!empty($search_term)) {
+ $query = $this->database->select('textbook_companion_preference', 'pref');
+ $query->fields('pref', ['id', 'book', 'author']);
+ $query->condition('approval_status', 1);
+
+ if ($by_title && $by_author) {
+ $or = $query->orConditionGroup()
+ ->condition('book', '%' . $this->database->escapeLike($search_term) . '%', 'LIKE')
+ ->condition('author', '%' . $this->database->escapeLike($search_term) . '%', 'LIKE');
$query->condition($or);
- $search_q = $query->execute();
+ }
+ elseif ($by_title) {
+ $query->condition('book', '%' . $this->database->escapeLike($search_term) . '%', 'LIKE');
+ }
+ elseif ($by_author) {
+ $query->condition('author', '%' . $this->database->escapeLike($search_term) . '%', 'LIKE');
}
else {
- if ($_POST['search_by_title']) {
- /*$search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND book LIKE '%%%s%%'", $_POST['search']);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('approval_status', 1);
- $query->condition('book', '%%' . $_POST['search'] . '%%', 'LIKE');
- $search_q = $query->execute();
- }
- else {
- if ($_POST['search_by_author']) {
- /*$search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND author LIKE '%%%s%%'", $_POST['search']);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('approval_status', 1);
- $query->condition('author', '%%' . $_POST['search'] . '%%', 'LIKE');
- $search_q = $query->execute();
- }
- else {
- drupal_set_message('Please select whether to search by Title and/or Author of the Book.', 'error');
- }
- }
+ $this->messenger()->addError($this->t('Please select whether to search by Title and/or Author.'));
}
- while ($search_data = $search_q->fetchObject()) {
+
+ $search_rows = [];
+ foreach ($query->execute() as $search_data) {
+ $run_url = Url::fromRoute('textbook_companion.run_form', ['book_pref_id' => $search_data->id]);
$search_rows[] = [
- l($search_data->book, 'textbook_run/' . $search_data->id),
+ Link::fromTextAndUrl($search_data->book, $run_url)->toString(),
$search_data->author,
];
}
+
if ($search_rows) {
- $search_header = [
- 'Title of the Book',
- 'Author Name',
- ];
- $output .= theme('table', [
- 'headers' => $search_header,
- 'rows' => $search_rows,
- ]);
$form['search_results'] = [
'#type' => 'item',
- '#title' => t('Search results for "') . $_POST['search'] . '"',
- '#markup' => $output,
+ '#title' => $this->t('Search results for "@term"', ['@term' => $search_term]),
+ 'table' => [
+ '#type' => 'table',
+ '#header' => [$this->t('Title of the Book'), $this->t('Author Name')],
+ '#rows' => $search_rows,
+ ],
];
}
else {
$form['search_results'] = [
'#type' => 'item',
- '#title' => t('Search results for "') . $_POST['search'] . '"',
- '#markup' => 'No results found',
+ '#title' => $this->t('Search results for "@term"', ['@term' => $search_term]),
+ '#markup' => $this->t('No results found'),
];
}
}
+
return $form;
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $form_state->setRedirect('textbook_companion.search_form', [], [
+ 'query' => [
+ 'search' => $form_state->getValue('search'),
+ 'by_title' => $form_state->getValue('search_by_title') ? 1 : 0,
+ 'by_author' => $form_state->getValue('search_by_author') ? 1 : 0,
+ ],
+ ]);
+ }
}
-}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSettingsForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSettingsForm.php
index db2ba5d..87beb6b 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSettingsForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/TextbookCompanionSettingsForm.php
@@ -7,11 +7,17 @@
namespace Drupal\textbook_companion\Form;
-use Drupal\Core\Form\FormBase;
+use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
-class TextbookCompanionSettingsForm extends FormBase {
+class TextbookCompanionSettingsForm extends ConfigFormBase {
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function getEditableConfigNames() {
+ return ['textbook_companion.settings'];
+ }
/**
* {@inheritdoc}
@@ -20,75 +26,102 @@ public function getFormId() {
return 'textbook_companion_settings_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $config = $this->config('textbook_companion.settings');
+
$form['bcc_emails'] = [
'#type' => 'textfield',
- '#title' => t('(Bcc) Notification emails'),
- '#description' => t('Specify emails id for Bcc option of mail system with comma separated'),
+ '#title' => $this->t('(Bcc) Notification emails'),
+ '#description' => $this->t('Specify emails id for Bcc option of mail system with comma separated'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
- '#default_value' => variable_get('textbook_companion_bcc_emails', ''),
+ '#default_value' => $config->get('textbook_companion_bcc_emails') ?? \Drupal::state()->get('textbook_companion_bcc_emails', ''),
];
$form['cc_emails'] = [
'#type' => 'textfield',
- '#title' => t('(Cc) Notification emails'),
- '#description' => t('Specify emails id for Cc option of mail system with comma separated'),
+ '#title' => $this->t('(Cc) Notification emails'),
+ '#description' => $this->t('Specify emails id for Cc option of mail system with comma separated'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
- '#default_value' => variable_get('textbook_companion_cc_emails', ''),
+ '#default_value' => $config->get('textbook_companion_cc_emails') ?? \Drupal::state()->get('textbook_companion_cc_emails', ''),
];
$form['from_email'] = [
'#type' => 'textfield',
- '#title' => t('Outgoing from email address'),
- '#description' => t('Email address to be display in the from field of all outgoing messages'),
+ '#title' => $this->t('Outgoing from email address'),
+ '#description' => $this->t('Email address to be display in the from field of all outgoing messages'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
- '#default_value' => variable_get('textbook_companion_from_email', ''),
+ '#default_value' => $config->get('textbook_companion_from_email') ?? \Drupal::state()->get('textbook_companion_from_email', ''),
];
$form['extensions']['source'] = [
'#type' => 'textfield',
- '#title' => t('Allowed source file extensions'),
- '#description' => t('A comma separated list WITHOUT SPACE of source file extensions that are permitted to be uploaded on the server'),
+ '#title' => $this->t('Allowed source file extensions'),
+ '#description' => $this->t('A comma separated list WITHOUT SPACE of source file extensions that are permitted to be uploaded on the server'),
'#size' => 50,
'#maxlength' => 255,
'#required' => TRUE,
- '#default_value' => variable_get('textbook_companion_source_extensions', ''),
+ '#default_value' => $config->get('textbook_companion_source_extensions') ?? \Drupal::state()->get('textbook_companion_source_extensions', ''),
];
$options = [
- '1' => t('1'),
- '2' => t('2'),
- '3' => t('3'),
+ '1' => $this->t('1'),
+ '2' => $this->t('2'),
+ '3' => $this->t('3'),
];
$form['book_preference_options'] = [
'#type' => 'radios',
- '#title' => t('Book Preferences'),
+ '#title' => $this->t('Book Preferences'),
'#options' => $options,
'#required' => TRUE,
- '#description' => t('Set number book preference to be allowed'),
- '#default_value' => variable_get('textbook_companion_book_preferences', ''),
- ];
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => t('Submit'),
+ '#description' => $this->t('Set number book preference to be allowed'),
+ '#default_value' => $config->get('textbook_companion_book_preferences') ?? \Drupal::state()->get('textbook_companion_book_preferences', ''),
];
- return $form;
+
+ return parent::buildForm($form, $form_state);
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- return;
+ /**
+ * {@inheritdoc}
+ */
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ parent::validateForm($form, $form_state);
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- variable_set('textbook_companion_bcc_emails', $form_state->getValue(['bcc_emails']));
- variable_set('textbook_companion_cc_emails', $form_state->getValue(['cc_emails']));
- variable_set('textbook_companion_from_email', $form_state->getValue(['from_email']));
- variable_set('textbook_companion_source_extensions', $form_state->getValue(['source']));
- variable_set('textbook_companion_book_preferences', $form_state->getValue(['book_preference_options']));
- drupal_set_message(t('Settings updated'), 'status');
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $bcc_emails = $form_state->getValue('bcc_emails');
+ $cc_emails = $form_state->getValue('cc_emails');
+ $from_email = $form_state->getValue('from_email');
+ $source_extensions = $form_state->getValue('source');
+ $book_preferences = $form_state->getValue('book_preference_options');
+
+ // Save to Configuration.
+ $this->config('textbook_companion.settings')
+ ->set('textbook_companion_bcc_emails', $bcc_emails)
+ ->set('textbook_companion_emails', $bcc_emails)
+ ->set('textbook_companion_cc_emails', $cc_emails)
+ ->set('textbook_companion_from_email', $from_email)
+ ->set('textbook_companion_source_extensions', $source_extensions)
+ ->set('textbook_companion_book_preferences', $book_preferences)
+ ->save();
+
+ // Synchronize to State API for backward compatibility.
+ \Drupal::state()->set('textbook_companion_bcc_emails', $bcc_emails);
+ \Drupal::state()->set('textbook_companion_emails', $bcc_emails);
+ \Drupal::state()->set('textbook_companion_cc_emails', $cc_emails);
+ \Drupal::state()->set('textbook_companion_from_email', $from_email);
+ \Drupal::state()->set('textbook_companion_source_extensions', $source_extensions);
+ \Drupal::state()->set('textbook_companion_book_preferences', $book_preferences);
+
+ $this->messenger()->addMessage($this->t('Settings updated'), 'status');
+ parent::submitForm($form, $form_state);
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesAdminEditForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesAdminEditForm.php
index 7b7ca4e..9ffeaf3 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesAdminEditForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesAdminEditForm.php
@@ -9,417 +9,299 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\textbook_companion\Services\MailService;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedResponseException;
class UploadExamplesAdminEditForm extends FormBase {
- /**
- * {@inheritdoc}
- */
+ protected $database;
+ protected $currentUser;
+ protected $entityTypeManager;
+ protected $configFactory;
+ protected $mailService;
+
+ public function __construct(
+ Connection $database,
+ AccountProxyInterface $current_user,
+ EntityTypeManagerInterface $entity_type_manager,
+ ConfigFactoryInterface $config_factory,
+ MailService $mail_service
+ ) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->configFactory = $config_factory;
+ $this->mailService = $mail_service;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('config.factory'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
public function getFormId() {
return 'upload_examples_admin_edit_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- $example_id = arg(3);
- /* get example details */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $example_id);
- $query->range(0, 1);
- $example_q = $query->execute();
- $example_data = $example_q->fetchObject();
- if (!$example_q) {
- drupal_set_message(t("Invalid example selected."), 'error');
- drupal_goto('');
- return;
- } //!$example_q
- /* get examples files */
- $source_file = "";
- $source_id = 0;
- $result1_file = "";
- $result1_id = 0;
- $result2_file = "";
- $result2_id = 0;
- $xcos1_file = "";
- $xcos1_id = 0;
- $xcos2_file = "";
- $xcos2_id = 0;
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id);*/
- $query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_id);
- $example_files_q = $query->execute();
- while ($example_files_data = $example_files_q->fetchObject()) {
- if ($example_files_data->filetype == "S") {
- $source_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id);
- $source_file_id = $example_files_data->id;
- } //$example_files_data->filetype == "S"
- if ($example_files_data->filetype == "R") {
- if (strlen($result1_file) == 0) {
- $result1_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id);
- $result1_file_id = $example_files_data->id;
- } //strlen($result1_file) == 0
- else {
- $result2_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id);
- $result2_file_id = $example_files_data->id;
- }
- } //$example_files_data->filetype == "R"
- if ($example_files_data->filetype == "X") {
- if (strlen($xcos1_file) <= 0) {
- $xcos1_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id);
- $xcos1_file_id = $example_files_data->id;
- } //strlen($xcos1_file) <= 0
- else {
- $xcos2_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id);
- $xcos2_file_id = $example_files_data->id;
- }
- } //$example_files_data->filetype == "X"
- } //$example_files_data = $example_files_q->fetchObject()
- /* get chapter details */
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
+ /**
+ * Resolve example_id from route, query, or path.
+ */
+ protected function resolveExampleId() {
+ $example_id = \Drupal::routeMatch()->getParameter('example_id');
+ if (!$example_id) {
+ $example_id = \Drupal::request()->query->get('example_id');
+ }
+ if (!$example_id) {
+ $parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last = end($parts);
+ if (is_numeric($last)) {
+ $example_id = (int) $last;
+ }
+ }
+ return $example_id;
+ }
+
+ /**
+ * Load a file download link for an example file.
+ */
+ protected function fileDownloadLink($filename, $file_id) {
+ return Link::fromTextAndUrl(
+ $filename,
+ Url::fromRoute('textbook_companion.download_example_file', ['example_file_id' => $file_id])
+ )->toString();
+ }
+
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $example_id = $this->resolveExampleId();
+
+ if (!$example_id) {
+ $this->messenger()->addError($this->t('Invalid example selected.'));
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromRoute('')->toString()));
+ }
+
+ $example_data = $this->database->select('textbook_companion_example', 'e')
+ ->fields('e')->condition('id', $example_id)->range(0, 1)
+ ->execute()->fetchObject();
+
+ if (!$example_data) {
+ $this->messenger()->addError($this->t('Invalid example selected.'));
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromRoute('')->toString()));
+ }
+
+ // Load example files.
+ $source_file = ''; $source_file_id = 0;
+ $result1_file = ''; $result1_file_id = 0;
+ $result2_file = ''; $result2_file_id = 0;
+ $xcos1_file = ''; $xcos1_file_id = 0;
+ $xcos2_file = ''; $xcos2_file_id = 0;
+
+ $files_q = $this->database->select('textbook_companion_example_files', 'f')
+ ->fields('f')->condition('example_id', $example_id)->execute();
+ while ($f = $files_q->fetchObject()) {
+ if ($f->filetype === 'S') {
+ $source_file = $this->fileDownloadLink($f->filename, $f->id);
+ $source_file_id = $f->id;
+ }
+ elseif ($f->filetype === 'R') {
+ if (!$result1_file) { $result1_file = $this->fileDownloadLink($f->filename, $f->id); $result1_file_id = $f->id; }
+ else { $result2_file = $this->fileDownloadLink($f->filename, $f->id); $result2_file_id = $f->id; }
+ }
+ elseif ($f->filetype === 'X') {
+ if (!$xcos1_file) { $xcos1_file = $this->fileDownloadLink($f->filename, $f->id); $xcos1_file_id = $f->id; }
+ else { $xcos2_file = $this->fileDownloadLink($f->filename, $f->id); $xcos2_file_id = $f->id; }
+ }
+ }
+
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'c')
+ ->fields('c')->condition('id', $example_data->chapter_id)->execute()->fetchObject();
if (!$chapter_data) {
- drupal_set_message(t("Invalid chapter selected."), 'error');
- drupal_goto('');
- return;
- } //!$chapter_data
- /* get preference details */
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
+ $this->messenger()->addError($this->t('Invalid chapter selected.'));
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromRoute('')->toString()));
+ }
+
+ $preference_data = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('id', $chapter_data->preference_id)->execute()->fetchObject();
if (!$preference_data) {
- drupal_set_message(t("Invalid book selected."), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
- /* get proposal details */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $preference_data->proposal_id);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
+ $this->messenger()->addError($this->t('Invalid book selected.'));
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromRoute('')->toString()));
+ }
+
+ $proposal_data = $this->database->select('textbook_companion_proposal', 'pr')
+ ->fields('pr')->condition('id', $preference_data->proposal_id)->execute()->fetchObject();
if (!$proposal_data) {
- drupal_set_message(t("Invalid proposal selected."), 'error');
- drupal_goto('');
- return;
- } //!$proposal_data
- $user_data = user_load($proposal_data->uid);
- $form['#redirect'] = 'code_approval/bulk';
- $form['#attributes'] = ['enctype' => "multipart/form-data"];
- $form['book_details']['book'] = [
- '#type' => 'item',
- '#markup' => $preference_data->book,
- '#title' => t('Title of the Book'),
- ];
- $form['contributor_name'] = [
- '#type' => 'item',
- '#markup' => $proposal_data->full_name,
- '#title' => t('Contributor Name'),
- ];
- $form['number'] = [
- '#type' => 'item',
- '#title' => t('Chapter No'),
- '#markup' => $chapter_data->number,
- ];
- $form['name'] = [
- '#type' => 'item',
- '#title' => t('Title of the Chapter'),
- '#markup' => $chapter_data->name,
- ];
- $form['example_number'] = [
- '#type' => 'item',
- '#title' => t('Example No'),
- '#markup' => $example_data->number,
- ];
+ $this->messenger()->addError($this->t('Invalid proposal selected.'));
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromRoute('')->toString()));
+ }
+
+ $config = $this->configFactory->get('textbook_companion.settings');
+ $source_extensions = $config->get('textbook_companion_source_extensions') ?? '';
+
+ $form['#attributes'] = ['enctype' => 'multipart/form-data'];
+ $form['book_details']['book'] = ['#type' => 'item', '#markup' => $preference_data->book, '#title' => $this->t('Title of the Book')];
+ $form['contributor_name'] = ['#type' => 'item', '#markup' => $proposal_data->full_name, '#title' => $this->t('Contributor Name')];
+ $form['number'] = ['#type' => 'item', '#title' => $this->t('Chapter No'), '#markup' => $chapter_data->number];
+ $form['name'] = ['#type' => 'item', '#title' => $this->t('Title of the Chapter'), '#markup' => $chapter_data->name];
+ $form['example_number'] = ['#type' => 'item', '#title' => $this->t('Example No'), '#markup' => $example_data->number];
$form['example_caption'] = [
- '#type' => 'textfield',
- '#title' => t('Caption'),
- '#size' => 40,
- '#maxlength' => 255,
- '#required' => TRUE,
+ '#type' => 'textfield', '#title' => $this->t('Caption'),
+ '#size' => 40, '#maxlength' => 255, '#required' => TRUE,
'#default_value' => $example_data->caption,
];
$form['example_warning'] = [
'#type' => 'item',
- '#title' => t('You should upload all the files (main or source files, result files, executable file if any)'),
- '#prefix' => '',
- '#suffix' => '
',
- ];
- $form['sourcefile'] = [
- '#type' => 'fieldset',
- '#title' => t('Main or Source Files'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE,
+ '#title' => $this->t('You should upload all the files (main or source files, result files, executable file if any)'),
+ '#prefix' => '', '#suffix' => '
',
];
+ $form['sourcefile'] = ['#type' => 'fieldset', '#title' => $this->t('Main or Source Files'), '#collapsible' => FALSE, '#collapsed' => FALSE];
if ($source_file) {
- $form['sourcefile']['cur_source'] = [
- '#type' => 'item',
- '#title' => t('Existing Main or Source File'),
- '#markup' => $source_file,
- ];
- $form['sourcefile']['cur_source_checkbox'] = [
- '#type' => 'checkbox',
- '#title' => t('Delete Existing Main or Source File'),
- '#description' => 'Check to delete the existing Main or Source file.',
- ];
+ $form['sourcefile']['cur_source'] = ['#type' => 'item', '#title' => $this->t('Existing Main or Source File'), '#markup' => $source_file];
+ $form['sourcefile']['cur_source_checkbox'] = ['#type' => 'checkbox', '#title' => $this->t('Delete Existing Main or Source File'), '#description' => 'Check to delete the existing Main or Source file.'];
$form['sourcefile']['sourcefile1'] = [
- '#type' => 'file',
- '#title' => t('Upload New Main or Source File'),
- '#size' => 48,
- '#description' => t("Upload new Main or Source file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. ") . t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''),
- ];
- $form['sourcefile']['cur_source_file_id'] = [
- '#type' => 'hidden',
- '#default_value' => $source_file_id,
+ '#type' => 'file', '#title' => $this->t('Upload New Main or Source File'), '#size' => 48,
+ '#description' => $this->t('Upload new Main or Source file above if you want to replace the existing file. Leave blank to keep existing. ') . $this->t('Allowed file extensions: ') . $source_extensions,
];
- } //$source_file
+ $form['sourcefile']['cur_source_file_id'] = ['#type' => 'hidden', '#value' => $source_file_id];
+ }
else {
$form['sourcefile']['sourcefile1'] = [
- '#type' => 'file',
- '#title' => t('Upload New Main or Source File'),
- '#size' => 48,
- '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''),
+ '#type' => 'file', '#title' => $this->t('Upload New Main or Source File'), '#size' => 48,
+ '#description' => $this->t('Allowed file extensions: ') . $source_extensions,
];
}
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => t('Submit'),
- ];
+
+ $form['example_id_hidden'] = ['#type' => 'hidden', '#value' => $example_id];
+ $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Submit')];
$form['cancel'] = [
- '#type' => 'markup',
- '#value' => l(t('Cancel'), 'textbook-companion/code'),
+ '#type' => 'link', '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute('textbook_companion.bulk_approval_form'),
+ '#attributes' => ['class' => ['button']],
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if (!check_name($form_state->getValue(['example_caption']))) {
- $form_state->setErrorByName('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.'));
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (function_exists('check_name')) {
+ if (!check_name($form_state->getValue('example_caption'))) {
+ $form_state->setErrorByName('example_caption', $this->t('Example Caption can contain only alphabets, numbers and spaces.'));
+ }
}
+ $config = $this->configFactory->get('textbook_companion.settings');
if (isset($_FILES['files'])) {
- /* check for valid filename extensions */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- if ($file_name) {
- /* checking file type */
- if (strstr($file_form_name, 'source')) {
- $file_type = 'S';
- }
- else {
- if (strstr($file_form_name, 'result')) {
- $file_type = 'R';
- }
- else {
- if (strstr($file_form_name, 'xcos')) {
- $file_type = 'X';
- }
- else {
- $file_type = 'U';
- }
- }
- }
- $allowed_extensions_str = '';
- switch ($file_type) {
- case 'S':
- $allowed_extensions_str = variable_get('textbook_companion_source_extensions', '');
- break;
- case 'R':
- $allowed_extensions_str = variable_get('textbook_companion_result_extensions', '');
- break;
- case 'X':
- $allowed_extensions_str = variable_get('textbook_companion_xcos_extensions', '');
- break;
- } //$file_type
- $allowed_extensions = explode(',', $allowed_extensions_str);
- $temp_ext = explode('.', strtolower($_FILES['files']['name'][$file_form_name]));
- $temp_extension = end($temp_ext);
- if (!in_array($temp_extension, $allowed_extensions)) {
- $form_state->setErrorByName($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.'));
- }
- if ($_FILES['files']['size'][$file_form_name] <= 0) {
- $form_state->setErrorByName($file_form_name, t('File size cannot be zero.'));
- }
- /* check if valid file name */
- if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) {
- $form_state->setErrorByName($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.'));
- }
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- } //isset($_FILES['files'])
+ foreach ($_FILES['files']['name'] as $field_name => $file_name) {
+ if (!$file_name) continue;
+ $file_type = strstr($field_name, 'source') ? 'S' : (strstr($field_name, 'result') ? 'R' : (strstr($field_name, 'xcos') ? 'X' : 'U'));
+ $ext_map = ['S' => 'textbook_companion_source_extensions', 'R' => 'textbook_companion_result_extensions', 'X' => 'textbook_companion_xcos_extensions'];
+ $allowed_str = isset($ext_map[$file_type]) ? ($config->get($ext_map[$file_type]) ?? '') : '';
+ $allowed = explode(',', $allowed_str);
+ $parts = explode('.', strtolower($file_name));
+ if (!in_array(end($parts), $allowed)) {
+ $form_state->setErrorByName($field_name, $this->t('Only files with @ext extensions can be uploaded.', ['@ext' => $allowed_str]));
+ }
+ if ($_FILES['files']['size'][$field_name] <= 0) {
+ $form_state->setErrorByName($field_name, $this->t('File size cannot be zero.'));
+ }
+ if (function_exists('textbook_companion_check_valid_filename') && !textbook_companion_check_valid_filename($file_name)) {
+ $form_state->setErrorByName($field_name, $this->t('Invalid file name. Only alphabets, numbers and underscore are allowed.'));
+ }
+ }
+ }
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- $example_id = arg(3);
- /* get example details */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $example_id);
- $query->range(0, 1);
- $example_q = $query->execute();
- $example_data = $example_q->fetchObject();
- if (!$example_q) {
- drupal_set_message(t("Invalid example selected."), 'error');
- drupal_goto('');
- return;
- } //!$example_q
- /* get chapter details */
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $chapter_q = $query->execute();
- $chapter_data = $chapter_q->fetchObject();
- if (!$chapter_data) {
- drupal_set_message(t("Invalid chapter selected."), 'error');
- drupal_goto('');
- return;
- } //!$chapter_data
- /* get preference details */
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if (!$preference_data) {
- drupal_set_message(t("Invalid book selected."), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
- /* get proposal details */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $preference_data->proposal_id);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- if (!$proposal_data) {
- drupal_set_message(t("Invalid proposal selected."), 'error');
- drupal_goto('');
- return;
- } //!$proposal_data
- $user_data = user_load($proposal_data->uid);
- /* creating directories */
- $root_path = textbook_companion_path();
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $example_id = $form_state->getValue('example_id_hidden');
+
+ $example_data = $this->database->select('textbook_companion_example', 'e')
+ ->fields('e')->condition('id', $example_id)->range(0, 1)->execute()->fetchObject();
+ if (!$example_data) { $this->messenger()->addError($this->t('Invalid example selected.')); return; }
+
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'c')
+ ->fields('c')->condition('id', $example_data->chapter_id)->execute()->fetchObject();
+ if (!$chapter_data) { $this->messenger()->addError($this->t('Invalid chapter selected.')); return; }
+
+ $preference_data = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('id', $chapter_data->preference_id)->execute()->fetchObject();
+ if (!$preference_data) { $this->messenger()->addError($this->t('Invalid book selected.')); return; }
+
+ $proposal_data = $this->database->select('textbook_companion_proposal', 'pr')
+ ->fields('pr')->condition('id', $preference_data->proposal_id)->execute()->fetchObject();
+ if (!$proposal_data) { $this->messenger()->addError($this->t('Invalid proposal selected.')); return; }
+
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+
+ $root_path = function_exists('textbook_companion_path') ? textbook_companion_path() : '';
$dest_path = $preference_data->directory_name . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path);
- }
+ if ($root_path && !is_dir($root_path . $dest_path)) { mkdir($root_path . $dest_path); }
$dest_path .= 'CH' . $chapter_data->number . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path);
- }
+ if ($root_path && !is_dir($root_path . $dest_path)) { mkdir($root_path . $dest_path); }
$dest_path .= 'EX' . $example_data->number . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path);
- }
- $filepath = 'CH' . $chapter_data->number . '/' . 'EX' . $example_data->number . '/';
- /* updating example caption */
- /*db_query("UPDATE {textbook_companion_example} SET caption = '%s' WHERE id = %d", $form_state['values']['example_caption'], $example_id);*/
- $query = db_update('textbook_companion_example');
- $query->fields(['caption' => $form_state->getValue(['example_caption'])]);
- $query->condition('id', $example_id);
- $num_updated = $query->execute();
- /* handle source file */
- if (!$form_state->getValue(['cur_source_file_id'])) {
- $form_state->setValue(['cur_source_file_id'], 0);
- } //empty($form_state['values']['cur_source_file_id'])
- $cur_file_id = $form_state->getValue(['cur_source_file_id']);
+ if ($root_path && !is_dir($root_path . $dest_path)) { mkdir($root_path . $dest_path); }
+ $filepath = 'CH' . $chapter_data->number . '/EX' . $example_data->number . '/';
+
+ $this->database->update('textbook_companion_example')
+ ->fields(['caption' => $form_state->getValue('example_caption')])
+ ->condition('id', $example_id)->execute();
+
+ $cur_file_id = (int) $form_state->getValue('cur_source_file_id');
if ($cur_file_id > 0) {
- /*$file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id);
- $file_data = db_fetch_object($file_q);*/
- $query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('id', $cur_file_id);
- $query->condition('example_id', $example_data->id);
- $result = $query->execute();
- $file_data = $result->fetchObject();
- if (!$file_data) {
- drupal_set_message("Error deleting example source file. File not present in database.", 'error');
- return;
- } //!$file_data
- if (($form_state->getValue(['cur_source_checkbox']) == 1) && (!$_FILES['files']['name']['sourcefile1'])) {
- if (!delete_file($cur_file_id)) {
- drupal_set_message("Error deleting example source file.", 'error');
- return;
- } //!delete_file($cur_file_id)
- } //($form_state['values']['cur_source_checkbox'] == 1) && (!$_FILES['files']['name']['sourcefile1'])
- } //$cur_file_id > 0
- if ($_FILES['files']['name']['sourcefile1']) {
- if ($cur_file_id > 0) {
- if (!delete_file($cur_file_id)) {
- drupal_set_message("Error removing previous example source file.", 'error');
- return;
- } //!delete_file($cur_file_id)
- } //$cur_file_id > 0
- if (file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) {
- drupal_set_message(t("Error uploading source file. File !filename already exists.", [
- '!filename' => $_FILES['files']['name']['sourcefile1']
- ]), 'error');
- return;
- } //file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])
- /* uploading file */
- if (move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) {
- /* for uploaded files making an entry in the database */
- /*db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp)
- VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)",
- $example_data->id,
- $_FILES['files']['name']['sourcefile1'],
- $dest_path . $_FILES['files']['name']['sourcefile1'],
- $_FILES['files']['type']['sourcefile1'],
- $_FILES['files']['size']['sourcefile1'],
- 'S',
- time()
- );*/
- $query = "INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp)
- VALUES (:example_id, :filename, :filepath, :filemime, :filesize, :filetype, :timestamp)";
- $args = [
- ":example_id" => $example_data->id,
- ":filename" => $_FILES['files']['name']['sourcefile1'],
- ":filepath" => $filepath . $_FILES['files']['name']['sourcefile1'],
- ":filemime" => 'application/dwxml',
- ":filesize" => $_FILES['files']['size']['sourcefile1'],
- ":filetype" => 'S',
- ":timestamp" => time(),
- ];
- $result = db_query($query, $args, [
- 'return' => Database::RETURN_INSERT_ID
- ]);
- drupal_set_message($_FILES['files']['name']['sourcefile1'] . ' uploaded successfully.', 'status');
- } //move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])
+ $file_data = $this->database->select('textbook_companion_example_files', 'f')
+ ->fields('f')->condition('id', $cur_file_id)->condition('example_id', $example_data->id)->execute()->fetchObject();
+ if (!$file_data) { $this->messenger()->addError($this->t('Error deleting example source file. File not found in database.')); return; }
+ if ($form_state->getValue('cur_source_checkbox') == 1 && empty($_FILES['files']['name']['sourcefile1'])) {
+ if (function_exists('delete_file') && !delete_file($cur_file_id)) {
+ $this->messenger()->addError($this->t('Error deleting example source file.')); return;
+ }
+ }
+ }
+
+ if (!empty($_FILES['files']['name']['sourcefile1'])) {
+ if ($cur_file_id > 0 && function_exists('delete_file') && !delete_file($cur_file_id)) {
+ $this->messenger()->addError($this->t('Error removing previous example source file.')); return;
+ }
+ $upload_filename = $_FILES['files']['name']['sourcefile1'];
+ if ($root_path && file_exists($root_path . $dest_path . $upload_filename)) {
+ $this->messenger()->addError($this->t('Error: file @file already exists.', ['@file' => $upload_filename])); return;
+ }
+ if (!$root_path || move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $upload_filename)) {
+ $this->database->insert('textbook_companion_example_files')->fields([
+ 'example_id' => $example_data->id,
+ 'filename' => $upload_filename,
+ 'filepath' => $filepath . $upload_filename,
+ 'filemime' => 'application/dwxml',
+ 'filesize' => $_FILES['files']['size']['sourcefile1'],
+ 'filetype' => 'S',
+ 'timestamp' => time(),
+ ])->execute();
+ $this->messenger()->addStatus($this->t('@file uploaded successfully.', ['@file' => $upload_filename]));
+ }
else {
- drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['sourcefile1'], 'error');
+ $this->messenger()->addError($this->t('Error uploading file: @path', ['@path' => $dest_path . $upload_filename]));
}
- } //$_FILES['files']['name']['sourcefile1']
- /* sending email */
- $email_to = $user_data->mail;
- $params['example_updated_admin']['example_id'] = $example_id;
- $params['example_updated_admin']['user_id'] = $proposal_data->uid;
- if (!drupal_mail('textbook_companion', 'example_updated_admin', $email_to, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
}
- drupal_set_message(t("Example successfully udpated."), 'status');
+
+ if ($user_data) {
+ $params['example_updated_admin']['example_id'] = $example_id;
+ $params['example_updated_admin']['user_id'] = $proposal_data->uid;
+ if (!$this->mailService->sendMail('textbook_companion', 'example_updated_admin', $user_data->getEmail(), $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ }
+
+ $this->messenger()->addStatus($this->t('Example successfully updated.'));
+ $form_state->setRedirect('textbook_companion.bulk_approval_form');
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesEditForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesEditForm.php
index 88bd19d..f81fa7a 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesEditForm.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesEditForm.php
@@ -9,481 +9,281 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\textbook_companion\Services\MailService;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Drupal\Core\Form\EnforcedResponseException;
class UploadExamplesEditForm extends FormBase {
- /**
- * {@inheritdoc}
- */
+ protected $database;
+ protected $currentUser;
+ protected $configFactory;
+ protected $mailService;
+
+ public function __construct(
+ Connection $database,
+ AccountProxyInterface $current_user,
+ ConfigFactoryInterface $config_factory,
+ MailService $mail_service
+ ) {
+ $this->database = $database;
+ $this->currentUser = $current_user;
+ $this->configFactory = $config_factory;
+ $this->mailService = $mail_service;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user'),
+ $container->get('config.factory'),
+ $container->get('textbook_companion.mail_service')
+ );
+ }
+
public function getFormId() {
return 'upload_examples_edit_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- $example_id = arg(3);
- /* get example details */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $example_id);
- $query->range(0, 1);
- $example_q = $query->execute();
- $example_data = $example_q->fetchObject();
- if (!$example_q) {
- drupal_set_message(t("Invalid example selected."), 'error');
- drupal_goto('');
- return;
- } //!$example_q
+ /**
+ * Resolve example_id from route, query, or path.
+ */
+ protected function resolveExampleId() {
+ $example_id = \Drupal::routeMatch()->getParameter('example_id');
+ if (!$example_id) $example_id = \Drupal::request()->query->get('example_id');
+ if (!$example_id) {
+ $parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $last = end($parts);
+ if (is_numeric($last)) $example_id = (int) $last;
+ }
+ return $example_id;
+ }
+
+ protected function redirectFront(FormStateInterface $form_state = NULL) {
+ $url = Url::fromRoute('textbook_companion.list_chapters')->toString();
+ throw new EnforcedResponseException(new RedirectResponse($url));
+ }
+
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $uid = $this->currentUser->id();
+ $example_id = $this->resolveExampleId();
+
+ if (!$example_id) {
+ $this->messenger()->addError($this->t('Invalid example selected.'));
+ $this->redirectFront();
+ }
+
+ $example_data = $this->database->select('textbook_companion_example', 'e')
+ ->fields('e')->condition('id', $example_id)->range(0, 1)->execute()->fetchObject();
+ if (!$example_data) {
+ $this->messenger()->addError($this->t('Invalid example selected.'));
+ $this->redirectFront();
+ }
if ($example_data->approval_status != 0) {
- drupal_set_message(t("You cannot edit an example after it has been approved or dis-approved. Please contact site administrator if you want to edit this example."), 'error');
- drupal_goto('');
- return;
- } //$example_data->approval_status != 0
- /* get examples files */
- $source_file = "";
- $source_id = 0;
- $result1_file = "";
- $result1_id = 0;
- $result2_file = "";
- $result2_id = 0;
- $xcos1_file = "";
- $xcos1_id = 0;
- $xcos2_file = "";
- $xcos2_id = 0;
- /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id);*/
- $query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_id);
- $example_files_q = $query->execute();
- while ($example_files_data = $example_files_q->fetchObject()) {
- if ($example_files_data->filetype == "S") {
- $source_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id);
- $source_file_id = $example_files_data->id;
- //var_dump($source_file);die;
- } //$example_files_data->filetype == "S"
- } //$example_files_data = $example_files_q->fetchObject()
- /* get chapter details */
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- if (!$chapter_data) {
- drupal_set_message(t("Invalid chapter selected."), 'error');
- drupal_goto('');
- return;
- } //!$chapter_data
- /* get preference details */
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if (!$preference_data) {
- drupal_set_message(t("Invalid book selected."), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
+ $this->messenger()->addError($this->t('You cannot edit an example after it has been approved or dis-approved.'));
+ $this->redirectFront();
+ }
+
+ $source_file = ''; $source_file_id = 0;
+ $files_q = $this->database->select('textbook_companion_example_files', 'f')
+ ->fields('f')->condition('example_id', $example_id)->execute();
+ while ($f = $files_q->fetchObject()) {
+ if ($f->filetype === 'S') {
+ $source_file = Link::fromTextAndUrl(
+ $f->filename,
+ Url::fromRoute('textbook_companion.download_example_file', ['example_file_id' => $f->id])
+ )->toString();
+ $source_file_id = $f->id;
+ }
+ }
+
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'c')
+ ->fields('c')->condition('id', $example_data->chapter_id)->execute()->fetchObject();
+ if (!$chapter_data) { $this->messenger()->addError($this->t('Invalid chapter selected.')); $this->redirectFront(); }
+
+ $preference_data = $this->database->select('textbook_companion_preference', 'p')
+ ->fields('p')->condition('id', $chapter_data->preference_id)->execute()->fetchObject();
+ if (!$preference_data) { $this->messenger()->addError($this->t('Invalid book selected.')); $this->redirectFront(); }
if ($preference_data->approval_status != 1) {
- drupal_set_message(t("Cannot edit example. Either the book proposal has not been approved or it has been rejected."), 'error');
- drupal_goto('');
- return;
- } //$preference_data->approval_status != 1
- /* get proposal details */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $preference_data->proposal_id);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- if (!$proposal_data) {
- drupal_set_message(t("Invalid proposal selected."), 'error');
- drupal_goto('');
- return;
- } //!$proposal_data
- if ($proposal_data->uid != $user->uid) {
- drupal_set_message(t("You do not have permissions to edit this example."), 'error');
- drupal_goto('');
- return;
- } //$proposal_data->uid != $user->uid
- $user_data = user_load($proposal_data->uid);
- $form['#redirect'] = 'textbook-companion/code';
- $form['#attributes'] = ['enctype' => "multipart/form-data"];
- $form['book_details']['book'] = [
- '#type' => 'item',
- '#markup' => $preference_data->book,
- '#title' => t('Title of the Book'),
- ];
- $form['contributor_name'] = [
- '#type' => 'item',
- '#markup' => $proposal_data->full_name,
- '#title' => t('Contributor Name'),
- ];
- $form['number'] = [
- '#type' => 'item',
- '#title' => t('Chapter No'),
- '#markup' => $chapter_data->number,
- ];
- $form['name'] = [
- '#type' => 'item',
- '#title' => t('Title of the Chapter'),
- '#markup' => $chapter_data->name,
- ];
- $form['example_number'] = [
- '#type' => 'item',
- '#title' => t('Example No'),
- '#markup' => $example_data->number,
- ];
+ $this->messenger()->addError($this->t('Cannot edit example. Book proposal has not been approved or was rejected.'));
+ $this->redirectFront();
+ }
+
+ $proposal_data = $this->database->select('textbook_companion_proposal', 'pr')
+ ->fields('pr')->condition('id', $preference_data->proposal_id)->execute()->fetchObject();
+ if (!$proposal_data) { $this->messenger()->addError($this->t('Invalid proposal selected.')); $this->redirectFront(); }
+ if ($proposal_data->uid != $uid) {
+ $this->messenger()->addError($this->t('You do not have permissions to edit this example.'));
+ $this->redirectFront();
+ }
+
+ $config = $this->configFactory->get('textbook_companion.settings');
+ $source_extensions = $config->get('textbook_companion_source_extensions') ?? '';
+
+ $form['#attributes'] = ['enctype' => 'multipart/form-data'];
+ $form['book_details']['book'] = ['#type' => 'item', '#markup' => $preference_data->book, '#title' => $this->t('Title of the Book')];
+ $form['contributor_name'] = ['#type' => 'item', '#markup' => $proposal_data->full_name, '#title' => $this->t('Contributor Name')];
+ $form['number'] = ['#type' => 'item', '#title' => $this->t('Chapter No'), '#markup' => $chapter_data->number];
+ $form['name'] = ['#type' => 'item', '#title' => $this->t('Title of the Chapter'), '#markup' => $chapter_data->name];
+ $form['example_number'] = ['#type' => 'item', '#title' => $this->t('Example No'), '#markup' => $example_data->number];
$form['example_caption'] = [
- '#type' => 'textfield',
- '#title' => t('Caption'),
- '#size' => 40,
- '#maxlength' => 255,
- '#required' => TRUE,
+ '#type' => 'textfield', '#title' => $this->t('Caption'),
+ '#size' => 40, '#maxlength' => 255, '#required' => TRUE,
'#default_value' => $example_data->caption,
];
$form['example_warning'] = [
'#type' => 'item',
- '#title' => t('You should upload all the files (main or source files, result files, executable file if any)'),
- '#prefix' => '',
- '#suffix' => '
',
- ];
- $form['sourcefile'] = [
- '#type' => 'fieldset',
- '#title' => t('Main or Source Files'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE,
+ '#title' => $this->t('You should upload all the files (main or source files, result files, executable file if any)'),
+ '#prefix' => '', '#suffix' => '
',
];
+ $form['sourcefile'] = ['#type' => 'fieldset', '#title' => $this->t('Main or Source Files'), '#collapsible' => FALSE, '#collapsed' => FALSE];
if ($source_file) {
- $form['sourcefile']['cur_source'] = [
- '#type' => 'item',
- '#title' => t('Existing Main or Source File'),
- '#markup' => $source_file,
- ];
- $form['sourcefile']['cur_source_checkbox'] = [
- '#type' => 'checkbox',
- '#title' => t('Delete Existing Main or Source File'),
- '#description' => 'Check to delete the existing Main or Source file.',
- ];
+ $form['sourcefile']['cur_source'] = ['#type' => 'item', '#title' => $this->t('Existing Main or Source File'), '#markup' => $source_file];
+ $form['sourcefile']['cur_source_checkbox'] = ['#type' => 'checkbox', '#title' => $this->t('Delete Existing Main or Source File'), '#description' => 'Check to delete the existing Main or Source file.'];
$form['sourcefile']['sourcefile1'] = [
- '#type' => 'file',
- '#title' => t('Upload New Main or Source File'),
- '#size' => 48,
- '#description' => t("Upload new Main or Source file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. ") . t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''),
+ '#type' => 'file', '#title' => $this->t('Upload New Main or Source File'), '#size' => 48,
+ '#description' => $this->t('Upload new Main or Source file if you want to replace the existing file. ') . $this->t('Allowed file extensions: ') . $source_extensions,
];
- $form['sourcefile']['cur_source_file_id'] = [
- '#type' => 'hidden',
- '#value' => $source_file_id,
- ];
- } //$source_file
+ $form['sourcefile']['cur_source_file_id'] = ['#type' => 'hidden', '#value' => $source_file_id];
+ }
else {
$form['sourcefile']['sourcefile1'] = [
- '#type' => 'file',
- '#title' => t('Upload New Main or Source File'),
- '#size' => 48,
- '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''),
+ '#type' => 'file', '#title' => $this->t('Upload New Main or Source File'), '#size' => 48,
+ '#description' => $this->t('Allowed file extensions: ') . $source_extensions,
];
}
- $form['submit'] = [
- '#type' => 'submit',
- '#value' => t('Submit'),
- ];
+
+ $form['example_id_hidden'] = ['#type' => 'hidden', '#value' => $example_id];
+ $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Submit')];
$form['cancel'] = [
- '#type' => 'item',
- '#markup' => l(t('Cancel'), 'textbook-companion/code'),
+ '#type' => 'link', '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute('textbook_companion.list_chapters'),
+ '#attributes' => ['class' => ['button']],
];
+
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if (!check_name($form_state->getValue(['example_caption']))) {
- $form_state->setErrorByName('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.'));
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (function_exists('check_name') && !check_name($form_state->getValue('example_caption'))) {
+ $form_state->setErrorByName('example_caption', $this->t('Example Caption can contain only alphabets, numbers and spaces.'));
}
+ $config = $this->configFactory->get('textbook_companion.settings');
if (isset($_FILES['files'])) {
- /* check for valid filename extensions */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
- if ($file_name) {
- /* checking file type */
- if (strstr($file_form_name, 'source')) {
- $file_type = 'S';
- }
- else {
- if (strstr($file_form_name, 'result')) {
- $file_type = 'R';
- }
- else {
- if (strstr($file_form_name, 'xcos')) {
- $file_type = 'X';
- }
- else {
- $file_type = 'U';
- }
- }
- }
- $allowed_extensions_str = '';
- switch ($file_type) {
- case 'S':
- $allowed_extensions_str = variable_get('textbook_companion_source_extensions', '');
- break;
- case 'R':
- $allowed_extensions_str = variable_get('textbook_companion_result_extensions', '');
- break;
- case 'X':
- $allowed_extensions_str = variable_get('textbook_companion_xcos_extensions', '');
- break;
- } //$file_type
- $allowed_extensions = explode(',', $allowed_extensions_str);
- $temp_ext = explode('.', strtolower($_FILES['files']['name'][$file_form_name]));
- $temp_extension = end($temp_ext);
- if (!in_array($temp_extension, $allowed_extensions)) {
- $form_state->setErrorByName($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.'));
- }
- if ($_FILES['files']['size'][$file_form_name] <= 0) {
- $form_state->setErrorByName($file_form_name, t('File size cannot be zero.'));
- }
- /* check if valid file name */
- if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) {
- $form_state->setErrorByName($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.'));
- }
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- } //isset($_FILES['files'])
- /* add javascript again for automatic book title, check if example uploaded, dependency selection effects */
- /*$chapter_name_js = " $(document).ready(function() {
- $('#edit-number').change(function() {
- $.get('" . base_path() . "textbook-companion/ajax/chapter-title/' + $('#edit-number').val() + '/' + " . $row->pre_id . ", function(data) {
- $('#edit-name').val(data);
- });
- });
- $('#edit-example-number').change(function() {
- $.get('" . base_path() . "textbook-companion/ajax/example-exists/' + $('#edit-number').val() + '/' + $('#edit-example-number').val(), function(data) {
- if (data) {
- alert(data);
- }
- });
- });
- $('#edit-existing-depfile-dep-book-title').change(function() {
-
- var dep_selected = '';
- /* showing and hiding relevant files */
- /*$('.form-checkboxes .option').hide();
- $('.form-checkboxes .option').each(function(index) {
- var activeClass = $('#edit-existing-depfile-dep-book-title').val();
- if ($(this).children().hasClass(activeClass)) {
- $(this).show();
- }
- if ($(this).children().attr('checked') == true) {
- dep_selected += $(this).children().next().text() + ' ';
- }
- });
- /* showing list of already existing dependencies */
- /* $('#existing_depfile_selected').html(dep_selected);
-
- });
-
- $('.form-checkboxes .option').change(function() {
- $('#edit-existing-depfile-dep-book-title').trigger('change');
- });
- $('#edit-existing-depfile-dep-book-title').trigger('change');
- });";
- drupal_add_js($chapter_name_js, 'inline', 'header');*/
+ foreach ($_FILES['files']['name'] as $field_name => $file_name) {
+ if (!$file_name) continue;
+ $file_type = strstr($field_name, 'source') ? 'S' : (strstr($field_name, 'result') ? 'R' : (strstr($field_name, 'xcos') ? 'X' : 'U'));
+ $ext_map = ['S' => 'textbook_companion_source_extensions', 'R' => 'textbook_companion_result_extensions', 'X' => 'textbook_companion_xcos_extensions'];
+ $allowed_str = isset($ext_map[$file_type]) ? ($config->get($ext_map[$file_type]) ?? '') : '';
+ $allowed = explode(',', $allowed_str);
+ $parts = explode('.', strtolower($file_name));
+ if (!in_array(end($parts), $allowed)) {
+ $form_state->setErrorByName($field_name, $this->t('Only files with @ext extensions can be uploaded.', ['@ext' => $allowed_str]));
+ }
+ if ($_FILES['files']['size'][$field_name] <= 0) {
+ $form_state->setErrorByName($field_name, $this->t('File size cannot be zero.'));
+ }
+ if (function_exists('textbook_companion_check_valid_filename') && !textbook_companion_check_valid_filename($file_name)) {
+ $form_state->setErrorByName($field_name, $this->t('Invalid file name. Only alphabets, numbers and underscore are allowed.'));
+ }
+ }
+ }
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- $example_id = arg(3);
- /* get example details */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $example_id);
- $query->range(0, 1);
- $example_q = $query->execute();
- $example_data = $example_q->fetchObject();
- if (!$example_q) {
- drupal_set_message(t("Invalid example selected."), 'error');
- drupal_goto('');
- return;
- } //!$example_q
- if ($example_data->approval_status != 0) {
- drupal_set_message(t("You cannot edit an example after it has been approved or dis-approved. Please contact site administrator if you want to edit this example."), 'error');
- drupal_goto('');
- return;
- } //$example_data->approval_status != 0
- /* get chapter details */
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- if (!$chapter_data) {
- drupal_set_message(t("Invalid chapter selected."), 'error');
- drupal_goto('');
- return;
- } //!$chapter_data
- /* get preference details */
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- if (!$preference_data) {
- drupal_set_message(t("Invalid book selected."), 'error');
- drupal_goto('');
- return;
- } //!$preference_data
- if ($preference_data->approval_status != 1) {
- drupal_set_message(t("Cannot edit example. Either the book proposal has not been approved or it has been rejected."), 'error');
- drupal_goto('');
- return;
- } //$preference_data->approval_status != 1
- /* get proposal details */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $preference_data->proposal_id);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- if (!$proposal_data) {
- drupal_set_message(t("Invalid proposal selected."), 'error');
- drupal_goto('');
- return;
- } //!$proposal_data
- if ($proposal_data->uid != $user->uid) {
- drupal_set_message(t("You do not have permissions to edit this example."), 'error');
- drupal_goto('');
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $uid = $this->currentUser->id();
+ $example_id = $form_state->getValue('example_id_hidden');
+
+ $example_data = $this->database->select('textbook_companion_example', 'e')
+ ->fields('e')->condition('id', $example_id)->range(0, 1)->execute()->fetchObject();
+ if (!$example_data || $example_data->approval_status != 0) {
+ $this->messenger()->addError($this->t('Cannot edit example at this stage.'));
return;
- } //$proposal_data->uid != $user->uid
- /* creating directories */
- $root_path = textbook_companion_path();
- $dest_path = $preference_data->directory_name . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path);
- }
- $dest_path .= 'CH' . $chapter_data->number . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path);
}
- $dest_path .= 'EX' . $example_data->number . '/';
- if (!is_dir($root_path . $dest_path)) {
- mkdir($root_path . $dest_path);
+
+ $chapter_data = $this->database->select('textbook_companion_chapter', 'c')
+ ->fields('c')->condition('id', $example_data->chapter_id)->execute()->fetchObject();
+ $preference_data = $chapter_data
+ ? $this->database->select('textbook_companion_preference', 'p')->fields('p')->condition('id', $chapter_data->preference_id)->execute()->fetchObject()
+ : NULL;
+ $proposal_data = $preference_data
+ ? $this->database->select('textbook_companion_proposal', 'pr')->fields('pr')->condition('id', $preference_data->proposal_id)->execute()->fetchObject()
+ : NULL;
+
+ if (!$proposal_data || $proposal_data->uid != $uid) {
+ $this->messenger()->addError($this->t('You do not have permissions to edit this example.'));
+ return;
}
- $filepath = 'CH' . $chapter_data->number . '/' . 'EX' . $example_data->number . '/';
- /* updating example caption */
- /*db_query("UPDATE {textbook_companion_example} SET caption = '%s' WHERE id = %d", $form_state['values']['example_caption'], $example_id);*/
- $query = db_update('textbook_companion_example');
- $query->fields(['caption' => $form_state->getValue(['example_caption'])]);
- $query->condition('id', $example_id);
- $num_updated = $query->execute();
- /* handle source file */
- if (!$form_state->getValue(['cur_source_file_id'])) {
- $cur_file_id = $form_state->getValue(['cur_source_file_id']);
- } //isset($form_state['values']['cur_source_file_id'])
- else {
- $cur_file_id = !$form_state->getValue(['cur_source_file_id']);
+
+ $root_path = function_exists('textbook_companion_path') ? textbook_companion_path() : '';
+ $dest_path = $preference_data->directory_name . '/CH' . $chapter_data->number . '/EX' . $example_data->number . '/';
+ $filepath = 'CH' . $chapter_data->number . '/EX' . $example_data->number . '/';
+
+ if ($root_path) {
+ $base = $preference_data->directory_name . '/';
+ if (!is_dir($root_path . $base)) mkdir($root_path . $base);
+ $base .= 'CH' . $chapter_data->number . '/';
+ if (!is_dir($root_path . $base)) mkdir($root_path . $base);
+ $base .= 'EX' . $example_data->number . '/';
+ if (!is_dir($root_path . $base)) mkdir($root_path . $base);
}
- //var_dump($cur_file_id);die;
+
+ $this->database->update('textbook_companion_example')
+ ->fields(['caption' => $form_state->getValue('example_caption')])
+ ->condition('id', $example_id)->execute();
+
+ $cur_file_id = (int) $form_state->getValue('cur_source_file_id');
if ($cur_file_id > 0) {
- /*$file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id);
- $file_data = db_fetch_object($file_q);*/
- //var_dump($cur_file_id. $example_data->id);die;
- $query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('id', $cur_file_id);
- $query->condition('example_id', $example_data->id);
- $result = $query->execute();
- $file_data = $result->fetchObject();
- if (!$file_data) {
- drupal_set_message("Error deleting example source file. File not present in database.", 'error');
- return;
- } //!$file_data
- if (($form_state->getValue(['cur_source_checkbox']) == 1) && (!$_FILES['files']['name']['sourcefile1'])) {
- if (!delete_file($cur_file_id)) {
- drupal_set_message("Error deleting example source file.", 'error');
- return;
- } //!delete_file($cur_file_id)
- } //($form_state['values']['cur_source_checkbox'] == 1) && (!$_FILES['files']['name']['sourcefile1'])
- } //$cur_file_id > 0
- if ($_FILES['files']['name']['sourcefile1']) {
- if ($cur_file_id > 0) {
- if (!delete_file($cur_file_id)) {
- drupal_set_message("Error removing previous example source file.", 'error');
- return;
- } //!delete_file($cur_file_id)
- } //$cur_file_id > 0
- if (file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) {
- drupal_set_message(t("Error uploading source file. File !filename already exists.", [
- '!filename' => $_FILES['files']['name']['sourcefile1']
- ]), 'error');
- return;
- } //file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])
- /* uploading file */
- if (move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) {
- /* for uploaded files making an entry in the database */
- /*db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp)
- VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)",
- $example_data->id,
- $_FILES['files']['name']['sourcefile1'],
- $dest_path . $_FILES['files']['name']['sourcefile1'],
- $_FILES['files']['type']['sourcefile1'],
- $_FILES['files']['size']['sourcefile1'],
- 'S',
- time()
- );*/
- $query = "INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) VALUES (:example_id, :filename, :filepath, :filemime, :filesize, :filetype,:timestamp)";
- $args = [
- ":example_id" => $example_data->id,
- ":filename" => $_FILES['files']['name']['sourcefile1'],
- ":filepath" => $filepath . $_FILES['files']['name']['sourcefile1'],
- ":filemime" => 'application/dwxml',
- ":filesize" => $_FILES['files']['size']['sourcefile1'],
- ":filetype" => 'S',
- ":timestamp" => time(),
- ];
- $result = db_query($query, $args, [
- 'return' => Database::RETURN_INSERT_ID
- ]);
- drupal_set_message($_FILES['files']['name']['sourcefile1'] . ' uploaded successfully.', 'status');
- } //move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])
+ $file_data = $this->database->select('textbook_companion_example_files', 'f')
+ ->fields('f')->condition('id', $cur_file_id)->condition('example_id', $example_data->id)->execute()->fetchObject();
+ if (!$file_data) { $this->messenger()->addError($this->t('Error: source file not found in database.')); return; }
+ if ($form_state->getValue('cur_source_checkbox') == 1 && empty($_FILES['files']['name']['sourcefile1'])) {
+ if (function_exists('delete_file') && !delete_file($cur_file_id)) {
+ $this->messenger()->addError($this->t('Error deleting example source file.')); return;
+ }
+ }
+ }
+
+ if (!empty($_FILES['files']['name']['sourcefile1'])) {
+ if ($cur_file_id > 0 && function_exists('delete_file') && !delete_file($cur_file_id)) {
+ $this->messenger()->addError($this->t('Error removing previous source file.')); return;
+ }
+ $upload_filename = $_FILES['files']['name']['sourcefile1'];
+ if ($root_path && file_exists($root_path . $dest_path . $upload_filename)) {
+ $this->messenger()->addError($this->t('Error: file @file already exists.', ['@file' => $upload_filename])); return;
+ }
+ if (!$root_path || move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $upload_filename)) {
+ $this->database->insert('textbook_companion_example_files')->fields([
+ 'example_id' => $example_data->id,
+ 'filename' => $upload_filename,
+ 'filepath' => $filepath . $upload_filename,
+ 'filemime' => 'application/dwxml',
+ 'filesize' => $_FILES['files']['size']['sourcefile1'],
+ 'filetype' => 'S',
+ 'timestamp' => time(),
+ ])->execute();
+ $this->messenger()->addStatus($this->t('@file uploaded successfully.', ['@file' => $upload_filename]));
+ }
else {
- drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['sourcefile1'], 'error');
+ $this->messenger()->addError($this->t('Error uploading file.'));
}
- } //$_FILES['files']['name']['sourcefile1']
- /* sending email */
- $email_to = $user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
+ }
+
+ $email_to = $this->currentUser->getEmail();
$params['example_updated']['example_id'] = $example_id;
- $params['example_updated']['user_id'] = $user->uid;
- $params['example_updated']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('textbook_companion', 'example_updated', $email_to, language_default(), $params, $from, TRUE)) {
- drupal_set_message('Error sending email message.', 'error');
+ $params['example_updated']['user_id'] = $uid;
+ if (!$this->mailService->sendMail('textbook_companion', 'example_updated', $email_to, $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
}
- drupal_set_message(t("Example successfully udpated."), 'status');
+
+ $this->messenger()->addStatus($this->t('Example successfully updated.'));
+ $form_state->setRedirect('textbook_companion.list_chapters');
}
}
-?>
diff --git a/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesForm.php b/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesForm.php
new file mode 100644
index 0000000..584271f
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Form/UploadExamplesForm.php
@@ -0,0 +1,399 @@
+database = $database;
+ $this->currentUser = $current_user;
+ $this->configFactory = $config_factory;
+ $this->mailService = $mail_service;
+ $this->ajaxHelper = $ajax_helper;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_user'),
+ $container->get('config.factory'),
+ $container->get('textbook_companion.mail_service'),
+ $container->get('textbook_companion.ajax_helper')
+ );
+ }
+
+ public function getFormId() {
+ return 'upload_examples_form';
+ }
+
+ protected function redirectFront() {
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromRoute('')->toString()));
+ }
+
+ protected function redirectCode() {
+ throw new EnforcedResponseException(new RedirectResponse(Url::fromRoute('textbook_companion.list_chapters')->toString()));
+ }
+
+ /**
+ * Shared proposal/preference gate used by build and submit.
+ */
+ protected function loadApprovedContext() {
+ $proposal_data = $this->database->select('textbook_companion_proposal')
+ ->fields('textbook_companion_proposal')
+ ->condition('uid', $this->currentUser->id())
+ ->orderBy('id', 'DESC')
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if (!$proposal_data) {
+ $link = Link::fromTextAndUrl($this->t('proposal'), Url::fromRoute('textbook_companion.proposal_all'))->toString();
+ $this->messenger()->addError($this->t('Please submit a @link.', ['@link' => $link]));
+ $this->redirectFront();
+ }
+
+ if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) {
+ $here = Link::fromTextAndUrl($this->t('here'), Url::fromRoute('textbook_companion.proposal_all'))->toString();
+ switch ($proposal_data->proposal_status) {
+ case 0:
+ $this->messenger()->addStatus($this->t('We have already received your proposal. We will get back to you soon.'));
+ $this->redirectFront();
+ case 2:
+ $this->messenger()->addError($this->t('Your proposal has been dis-approved. Please create another proposal @here.', ['@here' => $here]));
+ $this->redirectFront();
+ case 3:
+ $this->messenger()->addStatus($this->t('Congratulations! You have completed your last book proposal. You have to create another proposal @here.', ['@here' => $here]));
+ $this->redirectFront();
+ case 5:
+ $this->messenger()->addStatus($this->t('You have submitted your all codes.'));
+ $this->redirectFront();
+ default:
+ $this->messenger()->addError($this->t('Invalid proposal state. Please contact site administrator for further information.'));
+ $this->redirectFront();
+ }
+ }
+
+ $preference_data = $this->database->select('textbook_companion_preference')
+ ->fields('textbook_companion_preference')
+ ->condition('proposal_id', $proposal_data->id)
+ ->condition('approval_status', 1)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+
+ if (!$preference_data) {
+ $this->messenger()->addError($this->t('Invalid Book Preference status. Please contact site administrator for further information.'));
+ $this->redirectFront();
+ }
+
+ return [$proposal_data, $preference_data];
+ }
+
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ list($proposal_data, $preference_data) = $this->loadApprovedContext();
+
+ $form['#attributes'] = ['enctype' => 'multipart/form-data'];
+ $form['book_details']['pref_id'] = [
+ '#type' => 'hidden',
+ '#value' => $preference_data->id,
+ ];
+ $form['book_details']['book'] = [
+ '#type' => 'item',
+ '#markup' => $preference_data->book,
+ '#title' => $this->t('Title of the Book'),
+ ];
+ $form['contributor_name'] = [
+ '#type' => 'item',
+ '#markup' => $proposal_data->full_name,
+ '#title' => $this->t('Contributor Name'),
+ ];
+
+ $options = ['' => '(Select)'];
+ for ($i = 1; $i <= 100; $i++) {
+ $options[$i] = $i;
+ }
+ $form['number'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Chapter No'),
+ '#options' => $options,
+ '#required' => TRUE,
+ '#ajax' => [
+ 'callback' => '::ajaxChapterNameCallback',
+ 'event' => 'change',
+ ],
+ ];
+ $form['name'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Title of the Chapter'),
+ '#size' => 40,
+ '#maxlength' => 255,
+ '#required' => TRUE,
+ '#prefix' => '',
+ '#suffix' => '
',
+ ];
+ $form['example_number'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Example No'),
+ '#size' => 5,
+ '#maxlength' => 10,
+ '#description' => $this->t('Example number should be separated by dots only. Example: 1.1.a or 1.1.1'),
+ '#required' => TRUE,
+ ];
+ $form['example_caption'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Caption'),
+ '#size' => 40,
+ '#maxlength' => 255,
+ '#description' => $this->t('Example caption should contain only alphabets, numbers and spaces.'),
+ '#required' => TRUE,
+ ];
+ $form['example_warning'] = [
+ '#type' => 'item',
+ '#title' => $this->t('You should upload all the files as zip (main or source files, result files, executable file if any): '),
+ '#prefix' => '',
+ '#suffix' => '
',
+ ];
+
+ $ext = $this->configFactory->get('textbook_companion.settings')->get('textbook_companion_source_extensions');
+ if (!$ext && function_exists('tc_variable_get')) {
+ $ext = tc_variable_get('textbook_companion_source_extensions', '');
+ }
+ $form['sourcefile'] = [
+ '#type' => 'fieldset',
+ '#title' => $this->t('Main or Source Files'),
+ ];
+ $form['sourcefile']['sourcefile1'] = [
+ '#type' => 'file',
+ '#title' => $this->t('Upload main or source file'),
+ '#size' => 48,
+ '#description' => $this->t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . 'Allowed file extensions : ' . $ext . ' ',
+ ];
+ $form['submit'] = ['#type' => 'submit', '#value' => $this->t('Submit')];
+ $form['cancel'] = [
+ '#type' => 'link',
+ '#title' => $this->t('Cancel'),
+ '#url' => Url::fromRoute('textbook_companion.list_chapters'),
+ ];
+
+ return $form;
+ }
+
+ /**
+ * AJAX: fill chapter title when chapter number already exists.
+ */
+ public function ajaxChapterNameCallback(array &$form, FormStateInterface $form_state) {
+ $pref_id = $form_state->getValue('pref_id');
+ $chapter_number = $form_state->getValue('number');
+ $chapter = $this->database->select('textbook_companion_chapter')
+ ->fields('textbook_companion_chapter')
+ ->condition('preference_id', $pref_id)
+ ->condition('number', $chapter_number)
+ ->execute()
+ ->fetchObject();
+
+ if ($chapter) {
+ $form['name']['#value'] = $chapter->name;
+ $form['name']['#attributes']['readonly'] = 'readonly';
+ }
+ else {
+ $form['name']['#value'] = ' ';
+ unset($form['name']['#attributes']['readonly']);
+ }
+
+ return $this->ajaxHelper->replaceWrapper('#ajax-chapter-name-replace', $form['name']);
+ }
+
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if (function_exists('check_name') && !check_name($form_state->getValue('name'))) {
+ $form_state->setErrorByName('name', $this->t('Title of the Chapter can contain only alphabets, numbers and spaces.'));
+ }
+ if (function_exists('check_name') && !check_name($form_state->getValue('example_caption'))) {
+ $form_state->setErrorByName('example_caption', $this->t('Example Caption can contain only alphabets, numbers and spaces.'));
+ }
+ if (function_exists('check_chapter_number') && !check_chapter_number($form_state->getValue('example_number'))) {
+ $form_state->setErrorByName('example_number', $this->t('Invalid Example Number. Example Number can contain only alphabets and numbers sepereated by dot.'));
+ }
+ if (empty($_FILES['files']['name']['sourcefile1'])) {
+ $form_state->setErrorByName('sourcefile1', $this->t('Please upload source file.'));
+ }
+ if (!empty($_FILES['files']['name'])) {
+ $allowed_extensions_str = function_exists('tc_variable_get')
+ ? tc_variable_get('textbook_companion_source_extensions', '')
+ : (string) $this->configFactory->get('textbook_companion.settings')->get('textbook_companion_source_extensions');
+ $allowed_extensions = array_filter(array_map('trim', explode(',', $allowed_extensions_str)));
+ foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
+ if ($file_name) {
+ $temp_ext = explode('.', strtolower($file_name));
+ $temp_extension = end($temp_ext);
+ if ($allowed_extensions && !in_array($temp_extension, $allowed_extensions)) {
+ $form_state->setErrorByName($file_form_name, $this->t('Only file with @ext extensions can be uploaded.', ['@ext' => $allowed_extensions_str]));
+ }
+ if ($_FILES['files']['size'][$file_form_name] <= 0) {
+ $form_state->setErrorByName($file_form_name, $this->t('File size cannot be zero.'));
+ }
+ }
+ }
+ }
+ }
+
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ list($proposal_data, $preference_data) = $this->loadApprovedContext();
+ $root_path = function_exists('textbook_companion_path') ? textbook_companion_path() : '';
+
+ $dup = $this->database->select('textbook_companion_preference')
+ ->fields('textbook_companion_preference')
+ ->condition('proposal_id', $proposal_data->id)
+ ->condition('approval_status', 1)
+ ->execute()
+ ->rowCount();
+ if ($dup > 1) {
+ $this->messenger()->addError($this->t('You cannot upload your code. This name of book directory alrady preasent in directory folder, please contact to administrator.'));
+ return;
+ }
+
+ $proposal_directory = $preference_data->directory_name;
+ $dest_path = $proposal_directory . '/';
+ if ($root_path && !is_dir($root_path . $dest_path)) {
+ if (!mkdir($root_path . $dest_path)) {
+ $this->messenger()->addError($this->t('You cannot upload your code. Error in creating directory'));
+ }
+ }
+
+ $preference_id = $preference_data->id;
+ $chapter_row = $this->database->select('textbook_companion_chapter')
+ ->fields('textbook_companion_chapter')
+ ->condition('preference_id', $preference_id)
+ ->condition('number', $form_state->getValue('number'))
+ ->execute()
+ ->fetchObject();
+
+ if (!$chapter_row) {
+ $chapter_id = $this->database->insert('textbook_companion_chapter')
+ ->fields([
+ 'preference_id' => $preference_id,
+ 'number' => $form_state->getValue('number'),
+ 'name' => $form_state->getValue('name'),
+ ])
+ ->execute();
+ }
+ else {
+ $chapter_id = $chapter_row->id;
+ $this->database->update('textbook_companion_chapter')
+ ->fields(['name' => $form_state->getValue('name')])
+ ->condition('id', $chapter_id)
+ ->execute();
+ }
+
+ $cur_example = $this->database->select('textbook_companion_example')
+ ->fields('textbook_companion_example')
+ ->condition('chapter_id', $chapter_id)
+ ->condition('number', $form_state->getValue('example_number'))
+ ->execute()
+ ->fetchObject();
+ if ($cur_example) {
+ if ($cur_example->approval_status == 1) {
+ $this->messenger()->addError($this->t('Example already approved. Cannot overwrite it.'));
+ }
+ elseif ($cur_example->approval_status == 0) {
+ $this->messenger()->addError($this->t('Example is under pending review. Delete the example and reupload it.'));
+ }
+ else {
+ $this->messenger()->addError($this->t('Error uploading example. Please contact administrator.'));
+ }
+ $this->redirectCode();
+ }
+
+ $dest_path .= 'CH' . $form_state->getValue('number') . '/';
+ if ($root_path && !is_dir($root_path . $dest_path)) {
+ mkdir($root_path . $dest_path);
+ }
+ $dest_path .= 'EX' . $form_state->getValue('example_number') . '/';
+ if ($root_path && !is_dir($root_path . $dest_path)) {
+ mkdir($root_path . $dest_path);
+ }
+ $filepath = 'CH' . $form_state->getValue('number') . '/' . 'EX' . $form_state->getValue('example_number') . '/';
+
+ $example_id = $this->database->insert('textbook_companion_example')
+ ->fields([
+ 'chapter_id' => $chapter_id,
+ 'number' => $form_state->getValue('example_number'),
+ 'caption' => $form_state->getValue('example_caption'),
+ 'approval_date' => time(),
+ 'approval_status' => 0,
+ 'timestamp' => time(),
+ ])
+ ->execute();
+
+ if (!empty($_FILES['files']['name'])) {
+ foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
+ if ($file_name) {
+ $file_type = 'S';
+ if ($root_path && file_exists($root_path . $dest_path . $file_name)) {
+ $this->messenger()->addError($this->t('Error uploading file. File @filename already exists.', ['@filename' => $file_name]));
+ return;
+ }
+ if ($root_path && move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $file_name)) {
+ $this->database->insert('textbook_companion_example_files')
+ ->fields([
+ 'example_id' => $example_id,
+ 'filename' => $file_name,
+ 'filepath' => $filepath . $file_name,
+ 'filemime' => 'application/zip',
+ 'filesize' => $_FILES['files']['size'][$file_form_name],
+ 'filetype' => $file_type,
+ 'timestamp' => time(),
+ ])
+ ->execute();
+ $this->messenger()->addStatus($file_name . ' uploaded successfully.');
+ }
+ else {
+ $this->messenger()->addError('Error uploading file : ' . $dest_path . '/' . $file_name);
+ }
+ }
+ }
+ }
+
+ $this->messenger()->addStatus($this->t('Example uploaded successfully.'));
+ $params = [];
+ $params['example_uploaded']['example_id'] = $example_id;
+ $params['example_uploaded']['user_id'] = $this->currentUser->id();
+ if (!$this->mailService->sendMail('textbook_companion', 'example_uploaded', $this->currentUser->getEmail(), $params)) {
+ $this->messenger()->addError($this->t('Error sending email message.'));
+ }
+ $form_state->setRedirect('textbook_companion.list_chapters');
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Services/AjaxHelper.php b/modules/custom/DWSIM_textbook_companion/src/Services/AjaxHelper.php
new file mode 100644
index 0000000..c1385f1
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Services/AjaxHelper.php
@@ -0,0 +1,132 @@
+renderer = $renderer;
+ }
+
+ /**
+ * Replaces the HTML of a given CSS selector.
+ *
+ * @param string $selector
+ * The CSS selector to target.
+ * @param string|array $content
+ * The replacement content (string or render array).
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function replaceWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new ReplaceCommand($selector, $rendered));
+ return $response;
+ }
+
+ /**
+ * Sets the inner HTML of a given CSS selector.
+ *
+ * @param string $selector
+ * The CSS selector to target.
+ * @param string|array $content
+ * The content to inject (string or render array).
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function htmlWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new HtmlCommand($selector, $rendered));
+ return $response;
+ }
+
+ /**
+ * Generates a DataCommand response for setting jQuery data attributes.
+ *
+ * @param string $selector
+ * The CSS selector.
+ * @param string $name
+ * The data attribute name.
+ * @param mixed $value
+ * The data value.
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function dataCommand($selector, $name, $value) {
+ $response = new AjaxResponse();
+ $response->addCommand(new DataCommand($selector, $name, $value));
+ return $response;
+ }
+
+ /**
+ * Returns a status/warning/error message command.
+ *
+ * @param string $message
+ * The message text.
+ * @param string $type
+ * Message type: 'status', 'warning', or 'error'. Defaults to 'status'.
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function messageCommand($message, $type = 'status') {
+ $response = new AjaxResponse();
+ $response->addCommand(new MessageCommand($message, NULL, ['type' => $type]));
+ return $response;
+ }
+
+ /**
+ * Builds a response with multiple HTML/Replace/Data commands at once.
+ *
+ * @param array $commands
+ * Keyed array of commands. Each entry must have:
+ * - 'type': 'html', 'replace', or 'data'
+ * - 'content': the content (for html/replace)
+ * - 'name' and 'value': for data type
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function buildMultiCommandResponse(array $commands) {
+ $response = new AjaxResponse();
+ foreach ($commands as $selector => $data) {
+ $rendered = isset($data['content']) && is_array($data['content'])
+ ? $this->renderer->render($data['content'])
+ : ($data['content'] ?? '');
+
+ if ($data['type'] === 'html') {
+ $response->addCommand(new HtmlCommand($selector, $rendered));
+ }
+ elseif ($data['type'] === 'replace') {
+ $response->addCommand(new ReplaceCommand($selector, $rendered));
+ }
+ elseif ($data['type'] === 'data') {
+ $response->addCommand(new DataCommand($selector, $data['name'], $data['value']));
+ }
+ }
+ return $response;
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Services/MailService.php b/modules/custom/DWSIM_textbook_companion/src/Services/MailService.php
new file mode 100644
index 0000000..6483721
--- /dev/null
+++ b/modules/custom/DWSIM_textbook_companion/src/Services/MailService.php
@@ -0,0 +1,210 @@
+mailManager = $mail_manager;
+ $this->loggerFactory = $logger_factory;
+ $this->configFactory = $config_factory;
+ $this->languageManager = $language_manager;
+ }
+
+ /**
+ * Sends an email using the module's hook_mail and MailManager.
+ *
+ * Validates recipient, attaches standard headers, and logs failures.
+ *
+ * @param string $module_name
+ * The module name (matches hook_mail module parameter).
+ * @param string $mail_key
+ * The mail key (matches the switch case in hook_mail).
+ * @param string $to
+ * The recipient email address.
+ * @param array $params
+ * Parameters passed to hook_mail.
+ * @param bool $send
+ * Whether to actually send (defaults TRUE).
+ *
+ * @return bool
+ * TRUE on success, FALSE on failure.
+ */
+ public function sendMail($module_name, $mail_key, $to, array $params = [], $send = TRUE) {
+ if (empty($to)) {
+ $this->loggerFactory->get($module_name)->warning(
+ 'Email not sent: recipient is empty for mail key: @key',
+ ['@key' => $mail_key]
+ );
+ return FALSE;
+ }
+
+ $config = $this->configFactory->get($module_name . '.settings');
+ $from = $config->get($module_name . '_from_email')
+ ?: $this->configFactory->get('system.site')->get('mail');
+
+ // Set standard headers if not already provided.
+ if (!isset($params[$mail_key]['headers'])) {
+ $params[$mail_key]['headers'] = [
+ 'From' => $from,
+ 'MIME-Version' => '1.0',
+ 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
+ 'Content-Transfer-Encoding' => '8Bit',
+ 'X-Mailer' => 'Drupal',
+ ];
+ }
+ else {
+ $params[$mail_key]['headers']['From'] = $params[$mail_key]['headers']['From'] ?? $from;
+ }
+
+ // Attach Cc from config if not already overridden.
+ if (!isset($params[$mail_key]['headers']['Cc'])) {
+ $cc = $config->get($module_name . '_cc_emails');
+ if (!empty($cc)) {
+ $params[$mail_key]['headers']['Cc'] = $cc;
+ }
+ }
+
+ // Attach Bcc from config if not already overridden.
+ if (!isset($params[$mail_key]['headers']['Bcc'])) {
+ $bcc = $config->get($module_name . '_emails');
+ if (!empty($bcc)) {
+ $params[$mail_key]['headers']['Bcc'] = $bcc;
+ }
+ }
+
+ $langcode = $this->languageManager->getCurrentLanguage()->getId();
+
+ $result = $this->mailManager->mail(
+ $module_name,
+ $mail_key,
+ $to,
+ $langcode,
+ $params,
+ $from,
+ $send
+ );
+
+ if (empty($result['result'])) {
+ $this->loggerFactory->get($module_name)->error(
+ 'Failed to send email for key @key to @to',
+ ['@key' => $mail_key, '@to' => $to]
+ );
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ /**
+ * Sends a proposal approval notification email.
+ *
+ * @param string $module_name
+ * @param int $proposal_id
+ * @param int $user_id
+ * @param string $to
+ * @param array $extra_params
+ *
+ * @return bool
+ */
+ public function sendApprovalMail($module_name, $proposal_id, $user_id, $to, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_approved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Sends a proposal rejection notification email.
+ *
+ * @param string $module_name
+ * @param int $proposal_id
+ * @param int $user_id
+ * @param string $to
+ * @param string $reason
+ * @param array $extra_params
+ *
+ * @return bool
+ */
+ public function sendRejectionMail($module_name, $proposal_id, $user_id, $to, $reason, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_disapproved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+ $params[$mail_key]['reason'] = $reason;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Sends a generic notification email with explicit subject and body.
+ *
+ * @param string $module_name
+ * @param string $mail_key
+ * @param string $to
+ * @param string $subject
+ * @param string $body
+ * @param array $extra_params
+ *
+ * @return bool
+ */
+ public function sendNotification($module_name, $mail_key, $to, $subject, $body, array $extra_params = []) {
+ $params = $extra_params;
+ $params[$mail_key]['subject'] = $subject;
+ $params[$mail_key]['body'] = $body;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+}
diff --git a/modules/custom/DWSIM_textbook_companion/src/Services/TextbookCompanionGlobalFunction.php b/modules/custom/DWSIM_textbook_companion/src/Services/TextbookCompanionGlobalFunction.php
index f3b0aa4..3892cd5 100755
--- a/modules/custom/DWSIM_textbook_companion/src/Services/TextbookCompanionGlobalFunction.php
+++ b/modules/custom/DWSIM_textbook_companion/src/Services/TextbookCompanionGlobalFunction.php
@@ -1,119 +1,170 @@
database = $database;
+ $this->messenger = $messenger;
+ $this->currentUser = $current_user;
+ $this->moduleHandler = $module_handler;
+ $this->fileSystem = $file_system;
+ $this->mailService = $mail_service;
+ }
-function _list_of_books($category_default_value) {
- $book_titles = [
- 0 => 'Please select ...',
- ];
+ public function _list_of_books($category_default_value) {
+ $book_titles = [
+ 0 => 'Please select ...',
+ ];
- $connection = \Drupal::database();
+ // Main query on textbook_companion_preference table.
+ $query = $this->database->select('textbook_companion_preference', 'tcp');
+ $query->fields('tcp');
- // Main query on textbook_companion_preference table.
- $query = $connection->select('textbook_companion_preference', 'tcp');
- $query->fields('tcp');
+ // Apply filters.
+ $query->condition('tcp.category', $category_default_value);
+ $query->condition('tcp.approval_status', 1);
- // Apply filters.
- $query->condition('tcp.category', $category_default_value);
- $query->condition('tcp.approval_status', 1);
+ // Subquery on textbook_companion_proposal table.
+ $subquery = $this->database->select('textbook_companion_proposal', 'tcpp');
+ $subquery->fields('tcpp', ['id']);
+ $subquery->condition('tcpp.proposal_status', 3);
- // Subquery on textbook_companion_proposal table.
- $subquery = $connection->select('textbook_companion_proposal', 'tcpp');
- $subquery->fields('tcpp', ['id']);
- $subquery->condition('tcpp.proposal_status', 3);
+ $query->condition('tcp.proposal_id', $subquery, 'IN');
- $query->condition('tcp.proposal_id', $subquery, 'IN');
+ // Order by book ASC.
+ $query->orderBy('tcp.book', 'ASC');
- // Order by book ASC.
- $query->orderBy('tcp.book', 'ASC');
+ // Execute query.
+ $result = $query->execute();
- // Execute query.
- $result = $query->execute();
+ foreach ($result as $book_titles_data) {
+ $book_titles[$book_titles_data->id] =
+ $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')';
+ }
- foreach ($result as $book_titles_data) {
- $book_titles[$book_titles_data->id] =
- $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')';
+ return $book_titles;
}
- return $book_titles;
-}
+ public function _list_of_examples($chapter_id = 0) {
+ $book_examples = [
+ 0 => 'Please select...',
+ ];
-function _list_of_examples($chapter_id = 0) {
- $book_examples = [
- 0 => 'Please select...',
- ];
+ // Main query.
+ $query = $this->database->select('textbook_companion_example', 'tce');
+ $query->fields('tce');
+ $query->condition('tce.chapter_id', $chapter_id);
+ $query->condition('tce.approval_status', 1);
- $connection = \Drupal::database();
+ // Sorting examples properly (similar to original raw SQL).
+ $query->addExpression("CAST(SUBSTRING_INDEX(tce.number, '.', 1) AS UNSIGNED)", 'part1');
+ $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(tce.number, '.', 2), '.', -1) AS UNSIGNED)", 'part2');
+ $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(tce.number, '.', -1), '.', 1) AS UNSIGNED)", 'part3');
- // Main query.
- $query = $connection->select('textbook_companion_example', 'tce');
- $query->fields('tce');
- $query->condition('tce.chapter_id', $chapter_id);
- $query->condition('tce.approval_status', 1);
+ $query->orderBy('part1', 'ASC');
+ $query->orderBy('part2', 'ASC');
+ $query->orderBy('part3', 'ASC');
- // Sorting examples properly (similar to original raw SQL).
- // Equivalent to SUBSTRING_INDEX logic.
- $query->addExpression("CAST(SUBSTRING_INDEX(tce.number, '.', 1) AS UNSIGNED)", 'part1');
- $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(tce.number, '.', 2), '.', -1) AS UNSIGNED)", 'part2');
- $query->addExpression("CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(tce.number, '.', -1), '.', 1) AS UNSIGNED)", 'part3');
+ // Execute query.
+ $result = $query->execute();
- $query->orderBy('part1', 'ASC');
- $query->orderBy('part2', 'ASC');
- $query->orderBy('part3', 'ASC');
+ foreach ($result as $book_examples_data) {
+ $book_examples[$book_examples_data->id] =
+ $book_examples_data->number . ' (' . $book_examples_data->caption . ')';
+ }
- // Execute query.
- $result = $query->execute();
-
- foreach ($result as $book_examples_data) {
- $book_examples[$book_examples_data->id] =
- $book_examples_data->number . ' (' . $book_examples_data->caption . ')';
+ return $book_examples;
}
- return $book_examples;
-}
-
-function _list_of_chapters($preference_id = 0) {
- $book_chapters = [
- 0 => 'Please select...',
- ];
+ public function _list_of_chapters($preference_id = 0) {
+ $book_chapters = [
+ 0 => 'Please select...',
+ ];
- $connection = \Drupal::database();
+ // Build query.
+ $query = $this->database->select('textbook_companion_chapter', 'tcc');
+ $query->fields('tcc');
+ $query->condition('tcc.preference_id', $preference_id);
+ $query->orderBy('tcc.number', 'ASC');
- // Build query.
- $query = $connection->select('textbook_companion_chapter', 'tcc');
- $query->fields('tcc');
- $query->condition('tcc.preference_id', $preference_id);
- $query->orderBy('tcc.number', 'ASC');
+ // Execute query.
+ $result = $query->execute();
- // Execute query.
- $result = $query->execute();
+ foreach ($result as $book_chapters_data) {
+ $book_chapters[$book_chapters_data->id] =
+ $book_chapters_data->number . '. ' . $book_chapters_data->name;
+ }
- foreach ($result as $book_chapters_data) {
- $book_chapters[$book_chapters_data->id] =
- $book_chapters_data->number . '. ' . $book_chapters_data->name;
+ return $book_chapters;
}
- return $book_chapters;
-}
-
-public function textbook_companion_path()
-{
+ public function textbook_companion_path() {
return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_uploads/';
-}
-public function textbook_companion_samplecode_path()
-{
+ }
+
+ public function textbook_companion_samplecode_path() {
return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_sample_code/';
-}
+ }
}
diff --git a/modules/custom/DWSIM_textbook_companion/textbook_companion.info.yml b/modules/custom/DWSIM_textbook_companion/textbook_companion.info.yml
index e93d864..f17de22 100755
--- a/modules/custom/DWSIM_textbook_companion/textbook_companion.info.yml
+++ b/modules/custom/DWSIM_textbook_companion/textbook_companion.info.yml
@@ -1,7 +1,6 @@
name: 'Textbook Companion'
description: 'IIT Bombay Textbook Companion project'
package: IITB
-core: 8.x
-core_version_requirement: ^8 || ^9 || ^10
+core_version_requirement: '^10 || ^11'
type: module
dependencies: { }
\ No newline at end of file
diff --git a/modules/custom/DWSIM_textbook_companion/textbook_companion.module b/modules/custom/DWSIM_textbook_companion/textbook_companion.module
index 0aefaa5..cc01e9d 100755
--- a/modules/custom/DWSIM_textbook_companion/textbook_companion.module
+++ b/modules/custom/DWSIM_textbook_companion/textbook_companion.module
@@ -1,4058 +1,1875 @@
'Book Proposal Form',
- 'description' => 'Book Proposal Form.',
- 'page callback' => 'textbook_companion_proposal_all',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'create book proposal'
- ),
- 'type' => MENU_CALLBACK
- );
- /*$items["aicte_proposal"] = array(
- "title" => "AICTE Book Proposal",
- "description" => "AICTE Book Proposal Form",
- "page callback" => "textbook_companion_aicte_proposal_all",
- 'access arguments' => array('create book proposal'),
- 'type' => MENU_CALLBACK,
- );*/
- $items["textbook-companion/all_proposal"] = array(
- "title" => "Book Proposal",
- "description" => "Book Proposal Form",
- "page callback" => "textbook_companion_aicte_proposal_all",
- 'access arguments' => array(
- 'create book proposal'
- ),
- 'type' => MENU_CALLBACK
- );
- /* for reviewers */
- $items['textbook-companion/manage-proposal'] = array(
- 'title' => 'Manage Book Proposals',
- 'description' => 'Manage Book Proposals',
- 'page callback' => '_proposal_pending',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'approve book proposal'
- ),
- 'file' => 'manage_proposal.inc'
- );
- $items['textbook-companion/manage-proposal/pending'] = array(
- 'title' => 'Pending Proposals',
- 'description' => 'Pending Proposals Queue',
- 'page callback' => '_proposal_pending',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'approve book proposal'
- ),
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => 1,
- 'file' => 'manage_proposal.inc'
- );
- $items['textbook-companion/manage-proposal/all'] = array(
- 'title' => 'All Proposals',
- 'description' => 'All Proposals',
- 'page callback' => '_proposal_all',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'approve book proposal'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => 2,
- 'file' => 'manage_proposal.inc'
- );
- /*$items['manage_proposal/category'] = array(
- 'title' => 'Categorize',
- 'description' => 'Categorize Books',
- 'page callback' => '_category_all',
- 'access callback' => 'user_access',
- 'access arguments' => array('approve book proposal'),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => 2,
- 'file' => 'manage_proposal.inc',
- );*/
- $items['textbook-companion/manage-proposal/failed'] = array(
- 'title' => 'Failed Proposals',
- 'description' => 'Failed to submit code',
- 'page callback' => '_failed_all',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'approve book proposal'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => 3,
- 'file' => 'manage_proposal.inc'
- );
- $items['textbook-companion/manage-proposal/approve'] = array(
- 'title' => 'Proposal Approval',
- 'description' => 'Proposal Approval',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'proposal_approval_form'
- ),
- 'access arguments' => array(
- 'approve book proposal'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'manage_proposal.inc'
- );
- $items['textbook-companion/manage-proposal/status'] = array(
- 'title' => 'Proposal Status',
- 'description' => 'Proposal Status',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'proposal_status_form'
- ),
- 'access arguments' => array(
- 'approve book proposal'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'manage_proposal.inc'
- );
- $items['textbook-companion/manage-proposal/edit'] = array(
- 'title' => 'Edit Proposal',
- 'description' => 'Edit Proposal',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'proposal_edit_form'
- ),
- 'access arguments' => array(
- 'edit book proposal'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'manage_proposal.inc'
- );
- /*$items['manage_proposal/category/edit'] = array(
- 'title' => 'Edit Category',
- 'description' => 'Edit category',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('category_edit_form'),
- 'access arguments' => array('edit book proposal'),
- 'type' => MENU_CALLBACK,
- 'file' => 'manage_proposal.inc',
- );*/
- $items['textbook-companion/code-approval'] = array(
- 'title' => 'Manage Code Approval',
- 'description' => 'Manage Code Approval',
- 'page callback' => 'code_approval',
- 'access arguments' => array(
- 'approve code'
- ),
- 'type' => MENU_NORMAL_ITEM,
- 'file' => 'code_approval.inc'
- );
- $items['textbook-companion/code-approval/approve'] = array(
- 'title' => 'Code Approval',
- 'description' => 'Code Approval',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'code_approval_form'
- ),
- 'access arguments' => array(
- 'approve code'
- ),
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => 1,
- 'file' => 'code_approval.inc'
- );
- $items['textbook-companion/code-approval/bulk'] = array(
- 'title' => 'Bulk Manage',
- 'description' => 'Bulk Mangage',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'bulk_approval_form'
- ),
- 'access arguments' => array(
- 'bulk manage code'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => 2,
- 'file' => 'code_approval.inc'
- );
- /* $items['textbook-companion/code-approval/edit-code-submission'] = array(
- 'title' => 'Edit Code Submission',
- 'description' => 'Enable users code submission interface',
- // 'page callback' => 'drupal_get_form',
- 'page callback' => 'edit_code_submission',
- // 'page arguments' => array(
- // 'edit_code_submission_form'
- // ),
- 'access arguments' => array(
- 'bulk manage code'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => 3,
- 'file' => 'code_approval.inc'
- );*/
- $items['textbook-companion/code-approval/edit-code-submission/edit'] = array(
- 'title' => 'Edit Code Submission',
- 'description' => 'Enable users code submission interface',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'edit_code_submission_form'
- ),
- 'access arguments' => array(
- 'bulk manage code'
- ),
- 'file' => 'code_approval.inc'
- );
- $items['textbook-companion/code-approval/editcode'] = array(
- 'title' => 'Admin Edit Example',
- 'description' => 'Admin Edit Example',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'upload_examples_admin_edit_form'
- ),
- 'access arguments' => array(
- 'approve code'
- ),
- 'type' => MENU_CALLBACK,
- 'weight' => 3,
- 'file' => 'editcodeadmin.inc'
- );
- $items['textbook-companion/code-approval/notes'] = array(
- 'title' => 'Notes for Reviewers',
- 'description' => 'Notes for Reviewers',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'book_notes_form'
- ),
- 'access arguments' => array(
- 'bulk manage code'
- ),
- 'type' => MENU_CALLBACK,
- 'weight' => 4,
- 'file' => 'notes.inc'
- );
- /* $items['code_approval/dependency'] = array(
- 'title' => 'Dependency',
- 'description' => 'Dependency',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('textbook_companion_dependency_approval_form'),
- 'access arguments' => array('bulk manage code'),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => 3,
- 'file' => 'dependency_approval.inc',
- );*/
- $items['textbook-companion/code'] = array(
- 'title' => 'Code Submission',
- 'description' => 'Code Submission',
- 'page callback' => 'list_chapters',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'upload code'
- ),
- 'file' => 'general.inc'
- );
- $items['textbook-companion/code/list_chapters'] = array(
- 'title' => 'List Chapters',
- 'description' => 'List Chapters',
- 'page callback' => 'list_chapters',
- 'access arguments' => array(
- 'upload code'
- ),
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'file' => 'general.inc',
- 'weight' => 1
- );
- $items['textbook-companion/code/upload'] = array(
- 'title' => 'Code Submission',
- 'description' => 'Code Submission',
- 'page callback' => 'upload_examples',
- 'access arguments' => array(
- 'upload code'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'code.inc',
- 'weight' => 2
- );
- /* $items['textbook_companion/code/upload_dep'] = array(
- 'title' => 'Upload Dependency',
- 'description' => 'Upload Dependency Files',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('upload_dependency_form'),
- 'access arguments' => array('upload code'),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'dependency.inc',
- 'weight' => 3,
- );
- $items['textbook_companion/code/edit_dep'] = array(
- 'title' => 'Edit Dependency',
- 'description' => 'Edit Dependency File',
- 'page callback' => 'edit_dependency',
- 'access arguments' => array('upload code'),
- 'type' => MENU_CALLBACK,
- 'file' => 'dependency.inc',
- );
- $items['textbook_companion/code/delete_dep'] = array(
- 'title' => 'Delete Dependency',
- 'description' => 'Delete Dependency File',
- 'page callback' => 'delete_dependency',
- 'access arguments' => array('upload code'),
- 'type' => MENU_CALLBACK,
- 'file' => 'dependency.inc',
- );*/
- $items['textbook-companion/code/edit'] = array(
- 'title' => 'Edit Example',
- 'description' => 'Edit Example',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'upload_examples_edit_form'
- ),
- 'access arguments' => array(
- 'edit uploaded code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'editcode.inc'
- );
- $items['textbook-companion/code/delete'] = array(
- 'title' => 'Delete Example',
- 'description' => 'Delete Example',
- 'page callback' => '_upload_examples_delete',
- 'access arguments' => array(
- 'upload code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'code.inc'
- );
- $items['textbook-companion/code/chapter/edit'] = array(
- 'title' => 'Edit Chapter Title',
- 'description' => 'Edit Chapter Title',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'edit_chapter_title_form'
- ),
- 'access arguments' => array(
- 'upload code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'editcode.inc'
- );
- $items['textbook-companion/code/list-examples'] = array(
- 'title' => 'List Examples',
- 'description' => 'List Examples',
- 'page callback' => 'list_examples',
- 'access arguments' => array(
- 'upload code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'general.inc',
- 'weight' => 3
- );
- $items['textbook-companion/textbook-search'] = array(
- 'title' => 'Book Search',
- 'description' => '',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'textbook_companion_search_form'
- ),
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_NORMAL_ITEM,
- 'file' => 'search.inc'
- );
- $items['textbook-companion/textbook-search/search'] = array(
- 'title' => 'Book Search',
- 'description' => '',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'textbook_companion_search_form'
- ),
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'file' => 'search.inc',
- 'weight' => 1
- );
- $items['textbook-companion/textbook-search/book'] = array(
- 'title' => 'By Book Title',
- 'description' => '',
- 'page callback' => 'textbook_companion_browse_book',
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'search.inc',
- 'weight' => 2
- );
- $items['textbook-companion/textbook-search/author'] = array(
- 'title' => 'By Author',
- 'description' => '',
- 'page callback' => 'textbook_companion_browse_author',
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'search.inc',
- 'weight' => 3
- );
- $items['textbook-companion/textbook-search/college'] = array(
- 'title' => 'By College',
- 'description' => '',
- 'page callback' => 'textbook_companion_browse_college',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'textbook_companion_browse_college_form'
- ),
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'search.inc',
- 'weight' => 4
- );
- $items['textbook-companion/textbook-search/student'] = array(
- 'title' => 'By Student',
- 'description' => '',
- 'page callback' => 'textbook_companion_browse_student',
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'search.inc',
- 'weight' => 5
- );
- /* $items['textbook_run'] = array(
- 'title' => 'Download Codes',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('textbook_companion_run_form_ajax'),
- 'access arguments' => array('access content'),
- 'type' => MENU_NORMAL_ITEM,
- 'file' => 'run.inc',
- );*/
- $items['textbook-companion/textbook-run'] = array(
- 'title' => 'Download Codes',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'textbook_companion_run_form'
- ),
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'run.inc'
- );
- /*$items['textbook_run_ajax'] = array(
- 'page callback' => 'textbook_run_ajax',
- 'access callback' => TRUE,
- 'file' => 'run.inc',
- );*/
- /*$items['download_codes'] = array(
- 'title' => 'Download Codes',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('textbook_companion_run_form_ajax'),
- 'access arguments' => array('access content'),
- 'type' => MENU_NORMAL_ITEM,
- 'file' => 'run.inc',
- );*/
- $items['textbook-companion/download-codes'] = array(
- 'title' => 'Download Codes',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'textbook_companion_run_form'
- ),
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'run.inc'
- );
- /* download callbacks */
- $items['textbook-companion/download/file'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_example_file',
- 'access arguments' => array(
- 'download code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- $items['textbook-companion/download/samplecode'] = array(
- 'title' => 'Sample Code Download',
- 'description' => 'Sample Code Download',
- 'page callback' => 'textbook_companion_download_sample_code',
- 'access arguments' => array(
- 'download code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- /* $items['download/dependency'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_dependency_file',
- 'access arguments' => array('download code'),
- 'type' => MENU_CALLBACK,
- 'file' => 'download.inc',
- );*/
- $items['textbook-companion/download/example'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_example',
- 'access arguments' => array(
- 'download code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- $items['textbook-companion/download/chapter'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_chapter',
- 'access arguments' => array(
- 'download code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- $items['textbook-companion/download/book'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_book',
- 'access arguments' => array(
- 'download code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- /* reviewer download */
- $items['textbook-companion/full-download/chapter'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_full_chapter',
- 'access arguments' => array(
- 'approve code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'full_download.inc'
- );
- $items['textbook-companion/full-download/book'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_full_book',
- 'access arguments' => array(
- 'approve code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'full_download.inc'
- );
- /* external reviewer download */
- $items['textbook-companion/full-download-external/chapter'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_full_chapter',
- 'access arguments' => array(
- 'download books to review'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'full_download.inc'
- );
- $items['textbook-companion/full-download-external/book'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'textbook_companion_download_full_book',
- 'access arguments' => array(
- 'download books to review'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'full_download.inc'
- );
- /* latex script for book generation */
- $items['textbook-companion/generate-book'] = array(
- 'title' => 'Generate Book',
- 'description' => 'Generate Book From Latex Script',
- 'page callback' => 'textbook_companion_download_book',
- 'access arguments' => array(
- 'generate book'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'latex.inc'
- );
- $items['textbook-companion/delete-book'] = array(
- 'title' => 'Delete Book PDF',
- 'description' => 'Delete Book PDF',
- 'page callback' => 'textbook_companion_delete_book',
- 'access arguments' => array(
- 'approve code'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'latex.inc'
- );
- /* general purpose callbacks */
- $items['textbook-companion/ajax'] = array(
- 'title' => 'Ajax',
- 'description' => 'Ajax',
- 'page callback' => 'textbook_companion_ajax',
- 'access arguments' => array(
- 'access content'
- ),
- 'type' => MENU_CALLBACK
- );
- /* for admin */
- $items['admin/settings/book_companion'] = array(
- 'title' => 'Book Companion Settings',
- 'description' => 'Textbook Companion Settings',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'textbook_companion_settings_form'
- ),
- 'access arguments' => array(
- 'administer book companion'
- ),
- 'type' => MENU_NORMAL_ITEM,
- 'file' => 'settings.inc'
- );
- /* for data entry */
- $items['textbook-companion/dataentry-book'] = array(
- 'title' => 'Approved books list',
- 'page callback' => '_data_entry_proposal_all',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dataentry book proposal'
- ),
- 'file' => 'manage_proposal.inc'
- );
- $items['textbook-companion/dataentry-edit'] = array(
- 'title' => 'Edit book details',
- 'page callback' => 'dataentry_edit',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dataentry book proposal'
- ),
- 'type' => MENU_NORMAL_ITEM,
- 'file' => 'manage_proposal.inc'
- );
- /*Cheque Details and Contact Form */
- $items['textbook-companion/cheque-manage/all'] = array(
- 'title' => 'Cheque Proposals',
- 'description' => 'Cheque Proposals',
- 'page callback' => 'cheque_proposal_all',
- 'access arguments' => array(
- 'cheque proposal'
- ),
- 'file' => 'cheque_manage.inc'
- );
- $items['textbook-companion/mycontact'] = array(
- 'title' => 'Update Contact Details',
- 'description' => 'Update Contact Details',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'contact_details'
- ),
- 'access arguments' => array(
- 'contact_details'
- ),
- 'file' => 'cheque_contact.inc'
- );
- $items['textbook-companion/cheque-contct'] = array(
- 'title' => 'Report',
- 'description' => 'Cheque Contact Form',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'cheque_contct_form'
- ),
- 'access arguments' => array(
- 'cheque contct form'
- ),
- 'file' => 'cheque_contact.inc'
- );
- $items['textbook-companion/cheque-contact/status'] = array(
- 'title' => 'Cheque Status',
- 'description' => 'Cheque Status',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'cheque_status_form'
- ),
- 'access' => 'user_is_logged_in',
- 'access arguments' => array(
- 'cheque status form'
- ),
- 'file' => 'cheque_contact.inc'
- );
- $items['textbook-companion/cheque-contct/report'] = array(
- 'title' => 'Report',
- 'description' => 'Report',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'cheque_report_form'
- ),
- 'access' => 'user_is_logged_in',
- 'access arguments' => array(
- 'cheque report form'
- ),
- 'file' => 'cheque_contact.inc'
- );
- $items['textbook-companion/certificates'] = array(
- 'title' => 'List of all Certificates',
- 'description' => 'List of all Certificates',
- 'page callback' => '_list_all_certificates',
- 'access arguments' => array(
- 'list all certificates'
- ),
- 'file' => 'pdf/list_all_certificates.inc'
- );
- $items['textbook-companion/certificates/generate-pdf'] = array(
- 'title' => 'Download Certificate',
- 'description' => 'Download Certificate',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'generate_pdf'
- ),
- 'type' => MENU_CALLBACK,
- 'access arguments' => array(
- 'generate pdf'
- ),
- 'file' => 'pdf/generate_pdf.inc'
- );
- $items["textbook-companion/certificates/verify"] = array(
- "title" => "Certificate Verification",
- "page callback" => "verify_certificates",
- "access arguments" => array(
- "verify certificates"
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'pdf/verify_certificates.inc'
- );
- /*******************/
- $items['Summer_Internship_Forms/forms'] = array(
- 'title' => 'List of all Copyright Form and Undertaking Form for books',
- 'description' => 'List of all Copyright Form for books',
- 'page callback' => '_list_all_copyright_forms',
- 'access arguments' => array(
- 'list all certificates'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'pdf/list_all_form_pdf.inc'
- );
- $items['Summer_Internship_Forms/copyright-form/generate_pdf'] = array(
- 'title' => 'Download Copyright Form for books',
- 'description' => 'Download Copyright Form for books',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'generate_copyright_form_pdf'
- ),
- 'access arguments' => array(
- 'generate pdf'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'pdf/generate_pdf.inc'
- );
- $items['Summer_Internship_Forms/undertaking-form/generate_pdf'] = array(
- 'title' => 'Download Undertaking Form for books',
- 'description' => 'Download Undertaking Form for books',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'generate_undertaking_form_pdf'
- ),
- 'access arguments' => array(
- 'generate pdf'
- ),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'pdf/generate_pdf.inc'
- );
- $items['textbook-companion/manage-proposal/paper-submission'] = array(
- 'title' => 'Application Submission',
- 'description' => 'Application Submission',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'paper_submission_form'
- ),
- 'access arguments' => array(
- 'paper submission form'
- ),
- 'type' => MENU_CALLBACK,
- 'file' => 'cheque_contact.inc'
- );
- $items["textbook-companion/nonaicte-proposal"] = array(
- "title" => "Book Suggestion Form ",
- "description" => "NON-AICTE Book Proposal Form",
- 'page callback' => 'textbook_companion_nonaicte_proposal_all',
- 'access arguments' => array(
- 'create book proposal'
- ),
- 'type' => MENU_CALLBACK
- );
- /* COMPLETED DWSIM TBC Completed Books */
- $items['textbook-companion/completed-books'] = array(
- 'title' => 'Completed Books',
- 'page callback' => 'dwsim_tbc_completed_book_proposal_all',
- 'access arguments' => array(
- 'download code'
- ),
- 'file' => 'tbc_details.inc',
- );
- return $items;
-}
+
/**
- * Implementation of hook_perm().
+ * @file
+ * Contains textbook_companion.module hook implementations and helper functions.
*/
-function textbook_companion_permission()
-{
- return array(
- "create book proposal" => array(
- "title" => t("Book Proposal Form"),
- "description" => t("Book Proposal Form.")
- ),
- "approve book proposal" => array(
- "title" => t("Approve book proposal"),
- "description" => t("Allows users to approve book proposal.")
- ),
- "approve code" => array(
- "title" => t("Approve code"),
- "description" => t("Allows users to approve code.")
- ),
- "upload code" => array(
- "title" => t("Upload code"),
- "description" => t("Allows users to upload code.")
- ),
- "edit uploaded code" => array(
- "title" => t("Edit uploaded code"),
- "description" => t("Allows users to edit uploaded code.")
- ),
- "download code" => array(
- "title" => t("Download code"),
- "description" => t("Allows users to download code.")
- ),
- "create feedback" => array(
- "title" => t("Create feedback"),
- "description" => t("Allows users to create feedback.")
- ),
- "bulk manage code" => array(
- "title" => t("Bulk manage code"),
- "description" => t("Allows users to manage Bulk code.")
- ),
- "bulk delete code" => array(
- "title" => t("Bulk delete code"),
- "description" => t("Allows users to delete bulk code.")
- ),
- "edit book proposal" => array(
- "title" => t("Edit book proposal"),
- "description" => t("Allows users to edit book proposal.")
- ),
- "administer book companion" => array(
- "title" => t("Administer book companion"),
- "description" => t("Allows users to administer book companion.")
- ),
- "generate book" => array(
- "title" => t("Generate book"),
- "description" => t("Allows users to generate book.")
- ),
- "cheque contct form" => array(
- "title" => t("Cheque contact form"),
- "description" => t("Cheque contct form.")
- ),
- "contact_details" => array(
- "title" => t("Contact_details"),
- "description" => t("Contact_details.")
- ),
- "comment cheque" => array(
- "title" => t("Comment cheque"),
- "description" => t("Comment cheque.")
- ),
- "list all certificates" => array(
- "title" => t("list all certificates"),
- "description" => t("Allows users to list all certificates.")
- ),
- "generate pdf" => array(
- "title" => t("Generate pdf"),
- "description" => t("Allows users to Generate pdf.")
- ),
- "paper submission form" => array(
- "title" => t("paper submission form"),
- "description" => t("Paper submission form.")
- ),
- "cheque status form" => array(
- "title" => t("Cheque status form"),
- "description" => t("Cheque status form.")
- ),
- "cheque report form" => array(
- "title" => t("Cheque report form"),
- "description" => t("Cheque report form.")
- ),
- "cheque proposal" => array(
- "title" => t("Cheque proposal"),
- "description" => t("Cheque proposal.")
- ),
- "download books to review" => array(
- "title" => t("download books to review"),
- "description" => t("Download books to review.")
- ),
- "list all certificates" => array(
- "title" => t("list the certificates"),
- "description" => t("list the certificates")
- ),
- "verify certificates" => array(
- "title" => t("verify the certificates"),
- "description" => t("verify the certificates")
- ),
- /*'dwsim tbc completed books' => array(
- 'title' => t('dwsim textbook-companion completed code'),
- "description" => t("Allows to view completed books")
- )*/
- 'TBC download abstract' => array(
- 'title' => t('dwsim textbook-companion completed code'),
- 'restrict access' => TRUE
- ),
- );
-}
-/* Aicte books pickup before the proposal form */
-/*function textbook_companion_aicte_proposal_form($form_state) {
-/* $query = "
-SELECT * FROM textbook_companion_aicte
-WHERE status = 0 AND selected = 0
-";
-$result = db_query($query);*/
-/* $query = "
-SELECT * FROM textbook_companion_aicte
-WHERE status = :status AND selected = :selected
-";
-$args = array(
-':status' => 0,
-':selected' => 0,
-);
-$result = db_query($query,$args); */
-/* $query = db_select('textbook_companion_aicte');
-$query->fields('textbook_companion_aicte');
-$query->condition('status', 0);
-$query->condition('selected', 0);
-$result = $query->execute();
-
-$form = array();
-$form["wrapper"] = array(
-"#type" => "fieldset",
-"#prefix" => "",
-"#suffix" => "
",
-);
-// $num_rows = mysql_num_rows($result);
-$num_rows = $query->countQuery();
-if ($num_rows > 0) {
-while($row = $result->fetchObject()) {
-/* fixing title string */
-/* $title = "";
-$edition = "";
-$year = "";
-$title = "{$row->book} by {$row->author}";
-if($row->edition) {
-$edition = "ed : {$row->edition}";
-}
-if($row->year) {
-if($row->edition) {
-$year = ", pub : {$row->year}";
-} else {
-$year = "pub : {$row->year}";
-}
-}
-if($edition or $year) {
-$title .= "({$edition} {$year})";
-}
-$form["wrapper"][$row->id] = array(
-"#type" => "checkbox",
-"#title" => $title,
-"#prefix" => "",
-"#suffix" => "
",
-);
-}
-}
-$form["submit"] = array(
-"#type" => "submit",
-"#value" => "Submit Book Selections"
-);
-return $form;
-}*/
-/*function textbook_companion_aicte_proposal_form_validate($form, &$form_state) {
-/*$query = "
-SELECT * FROM textbook_companion_aicte
-WHERE status = 0 AND selected = 0
-";
-$result = db_query($query);*/
-/*$query = db_select('textbook_companion_aicte');
-$query->fields('textbook_companion_aicte');
-$query->condition('status', 0);
-$query->condition('selected', 0);
-$result = $query->execute();
-
-$count = 0;
-$selections = array();
-while($row = $result->fetchObject()) {
-if($form_state["values"][$row->id] == 1) {
-$count++;
-array_push($selections, $row->id);
-}
-}
-/* user can choose only 3 books to propose */
-/* if($count != 3) {
-form_set_error("", "Please select exactly 3 books. You currently selected {$count} ");
-} else {
-$form_state["values"]["selections"] = $selections;
-}
-}*/
-/*function textbook_companion_aicte_proposal_form_submit($form, &$form_state) {
-global $user;
-$selections = $form_state["values"]["selections"];
-var_dump($selections);
-variable_set("aicte_".$user->uid, $selections);
-drupal_goto("proposal");
-}*/
-/*function textbook_companion_aicte_report_form($form_state) {
-/*$query = "
-SELECT * FROM textbook_companion_aicte
-WHERE status = 0
-ORDER BY book
-";
-$result = db_query($query);*/
-/*$query = db_select('textbook_companion_aicte');
-$query->fields('textbook_companion_aicte');
-$query->condition('status', 0);
-$query->orderBy('book', 'ASC');
-$result = $query->execute();
-
-$books = array();
-$books[0] = "Please select a book";
-while($row = $result->fetchObject()) {
-$books[$row->id] = "{$row->book} ({$row->author})";
-}
-$form = array();
-$form["name"] = array(
-"#type" => "textfield",
-"#title" => "Name",
-"#description" => t("Please enter your name."),
-);
-$form["email"] = array(
-"#type" => "textfield",
-"#title" => "Email",
-"#description" => t("Please enter your valid email id."),
-);
-$form["number"] = array(
-"#type" => "textfield",
-"#title" => "Number",
-"#description" => t("Please enter your valid phone number."),
-);
-$form["book"] = array(
-"#type" => "select",
-"#title" => "AICTE Book",
-"#description" => t("Please select a book."),
-"#options" => $books
-);
-$form["comment"] = array(
-"#type" => "textarea",
-"#title" => "Any other comment?",
-"#description" => t("Please enter your query (if any)")
-);
-$form["submit"] = array(
-"#type" => "submit",
-"#value" => "Submit"
-);
-return $form;
-}
-*/
-/*function textbook_companion_aicte_report_form_submit($form, &$form_state) {
-$v = $form_state["values"];
-
-/*$query = "
-INSERT INTO textbook_companion_aicte_report
-(aicte_id, name, number, email, comment)
-VALUES
-(%d, '%s', '%s', '%s', '%s')
-";
-$result = db_query($query,
-$v["book"], $v["name"], $v["number"], $v["email"], $v["comment"]
-);*/
-/*$query = "INSERT INTO textbook_companion_aicte_report
-(aicte_id, name, number, email, comment)
-VALUES (:aicte_id, :name, :number, :email, :comment)";
-$args = array(
-":aicte_id" => $v["book"],
-":name" => $v["name"],
-":number" => $v["number"],
-":email" =>$v["email"],
-":comment" => $v["comment"]
-);
-$result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
-
-drupal_set_message("Thank you for reporting.", "status");
-}
-*/
-function textbook_companion_aicte_proposal_all()
-{
- global $user;
- $page_content = "";
- if (!$user->uid)
- {
- /*$query = "
- SELECT * FROM textbook_companion_aicte
- WHERE status = 0
- ";
- $result = db_query($query);*/
- $query = db_select('textbook_companion_aicte');
- $query->fields('textbook_companion_aicte');
- $query->condition('status', 0);
- $result = $query->execute();
- $page_content .= "";
- $page_content .= "These are the list of books available for Textbook Companion proposal. ";
- $page_content .= "Please Login to create a proposal. ";
- //$page_content .= "Unable to propose particular book: Click here ";
- //$page_content .= "Do not wish to propose any of the below books: Click here ";
- $page_content .= " ";
- $page_content .= "Search : ";
- $page_content .= " ";
- $page_content .= "";
- $num_rows = $result->rowCount();
- if ($num_rows > 0)
- {
- $i = 1;
- while ($row = $result->fetchObject())
- {
- /* fixing title string */
- $title = "";
- $edition = "";
- $year = "";
- $title = "{$row->book} by {$row->author}";
- if ($row->edition)
- {
- $edition = "
ed : {$row->edition}";
- } //$row->edition
- if ($row->year)
- {
- if ($row->edition)
- {
- $year = ",
pub : {$row->year}";
- } //$row->edition
- else
- {
- $year = "
pub : {$row->year}";
- }
- } //$row->year
- if ($edition or $year)
- {
- $title .= "({$edition} {$year})";
- } //$edition or $year
- $page_content .= "
{$i}) {$title}
";
- $i++;
- } //$row = $result->fetchObject()
- } //$num_rows > 0
- $page_content .= "
";
- /* adding aicte report form */
- //$page_content .= drupal_get_form("textbook_companion_aicte_report_form");
- return $page_content;
- } //!$user->uid
- /* check if user has already submitted a proposal */
- /* $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- if ($proposal_q)
- {
- if ($proposal_data = $proposal_q->fetchObject())
- {
- switch ($proposal_data->proposal_status)
- {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 1:
- drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error');
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status');
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data = $proposal_q->fetchObject()
- } //$proposal_q
- variable_del("aicte_" . $user->uid);
- $page_content .= "* Please select any 3 books from the below list. ";
- //$page_content .= "Unable to propose particular book: Click here ";
- //$page_content .= "Do not wish to propose any of the below books: Click here ";
- $page_content .= "Search : ";
- $page_content .= " ";
- //$page_content .= drupal_get_form("textbook_companion_aicte_report_form");
- $textbook_companion_aicte_proposal_form = drupal_get_form("textbook_companion_aicte_proposal_form");
- $page_content .= drupal_render($textbook_companion_aicte_proposal_form);
- return $page_content;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\user\Entity\User;
+
+/**
+ * Safe helper to get a value from form state (works with array or object).
+ */
+function tc_form_state_get_value($form_state, $key, $default = NULL) {
+ if (is_array($form_state)) {
+ return isset($form_state['values'][$key]) ? $form_state['values'][$key] : $default;
+ }
+ if ($form_state instanceof FormStateInterface) {
+ return $form_state->getValue($key, $default);
+ }
+ return $default;
}
-/*non aicte book proposal */
-function textbook_companion_nonaicte_proposal_all()
-{
- global $user;
- $page_content = "";
- if (!$user->uid)
- {
- $page_content .= "";
- $page_content .= "Please Login to create a proposal. ";
- $page_content .= " ";
- return $page_content;
- } //!$user->uid
- /* check if user has already submitted a proposal */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- if ($proposal_q)
- {
- if ($proposal_data = $proposal_q->fetchObject())
- {
- switch ($proposal_data->proposal_status)
- {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 1:
- drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error');
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status');
- break;
- case 5:
- drupal_set_message(t('You have submitted your all codes.'), 'status');
- drupal_goto('');
- return;
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data = $proposal_q->fetchObject()
- } //$proposal_q
- //variable_del("aicte_".$user->uid);
- $book_proposal_nonaicte_form = drupal_get_form("book_proposal_nonaicte_form");
- $page_content .= drupal_render($book_proposal_nonaicte_form);
- return $page_content;
+
+/**
+ * Safe helper to set a value in form state (works with array or object).
+ */
+function tc_form_state_set_value(&$form_state, $key, $value) {
+ if (is_array($form_state)) {
+ $form_state['values'][$key] = $value;
+ } elseif ($form_state instanceof FormStateInterface) {
+ $form_state->setValue($key, $value);
+ }
}
-/* Textbook Companion Proposal */
-function textbook_companion_proposal_all()
-{
- global $user;
- $page_content = "";
- if (!$user->uid)
- {
- drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error');
- drupal_goto('');
- return;
- } //!$user->uid
- /* check if user has already submitted a proposal */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('uid', $user->uid);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- if ($proposal_q)
- {
- if ($proposal_data = $proposal_q->fetchObject())
- {
- switch ($proposal_data->proposal_status)
- {
- case 0:
- drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
- return;
- break;
- case 1:
- drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status');
- drupal_goto('');
- return;
- break;
- case 2:
- drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error');
- break;
- case 3:
- drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status');
- break;
- default:
- drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- drupal_goto('');
- return;
- break;
- } //$proposal_data->proposal_status
- } //$proposal_data = $proposal_q->fetchObject()
- } //$proposal_q
- $book_proposal_form = drupal_get_form("book_proposal_form");
- $page_content .= drupal_render($book_proposal_form);
- // drupal_goto("aicte_proposal");
- return $page_content;
+
+/**
+ * Safe helper to set form error (works with array or object).
+ */
+function tc_form_set_error($field, $message, $form_state = NULL) {
+ if ($form_state instanceof FormStateInterface) {
+ $form_state->setErrorByName($field, $message);
+ } else {
+ \Drupal::messenger()->addError($message);
+ }
}
-function book_proposal_form($form, &$form_state)
-{
- global $user;
- $form = array();
- $form['imp_notice'] = array(
- '#type' => 'item',
- '#markup' => 'Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion '
- );
- $form['full_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Full Name'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- );
- $form['email_id'] = array(
- '#type' => 'textfield',
- '#title' => t('Email'),
- '#size' => 30,
- '#value' => $user->mail,
- '#disabled' => TRUE
- );
- $form['mobile'] = array(
- '#type' => 'textfield',
- '#title' => t('Mobile No.'),
- '#size' => 30,
- '#maxlength' => 15,
- '#required' => TRUE
- );
- $form['gender'] = array(
- '#type' => 'radios',
- '#title' => t('Gender'),
- '#options' => array(
- 'M' => 'Male',
- 'F' => 'Female'
- ),
- '#required' => TRUE
- );
- $form['how_project'] = array(
- '#type' => 'select',
- '#title' => t('How did you come to know about this project'),
- '#options' => array(
- 'DWSIM Website' => 'DWSIM Website',
- 'Friend' => 'Friend',
- 'Professor/Teacher' => 'Professor/Teacher',
- 'Mailing List' => 'Mailing List',
- 'Poster in my/other college' => 'Poster in my/other college',
- 'Others' => 'Others'
- ),
- '#required' => TRUE
- );
- $form['course'] = array(
- '#type' => 'textfield',
- '#title' => t('Course'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- );
- $form['branch'] = array(
- '#type' => 'select',
- '#title' => t('Department/Branch'),
- '#options' => _list_of_departments(),
- '#required' => TRUE
- );
- $form['university'] = array(
- '#type' => 'textfield',
- '#title' => t('University/ Institute'),
- '#size' => 80,
- '#maxlength' => 200,
- '#required' => TRUE,
- '#attributes' => array(
- 'placeholder' => 'Insert full name of your institute/ university.... '
- )
- );
- $form['country'] = array(
- '#type' => 'select',
- '#title' => t('Country'),
- '#options' => array(
- 'India' => 'India',
- 'Others' => 'Others'
- ),
- '#required' => TRUE,
- '#tree' => TRUE,
- '#validated' => TRUE
- );
- $form['other_country'] = array(
- '#type' => 'textfield',
- '#title' => t('Other than India'),
- '#size' => 100,
- '#attributes' => array(
- 'placeholder' => t('Enter your country name')
- ),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'Others'
- )
- )
- )
- );
- $form['other_state'] = array(
- '#type' => 'textfield',
- '#title' => t('State other than India'),
- '#size' => 100,
- '#attributes' => array(
- 'placeholder' => t('Enter your state/region name')
- ),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'Others'
- )
- )
- )
- );
- $form['other_city'] = array(
- '#type' => 'textfield',
- '#title' => t('City other than India'),
- '#size' => 100,
- '#attributes' => array(
- 'placeholder' => t('Enter your city name')
- ),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'Others'
- )
- )
- )
- );
- $form['all_state'] = array(
- '#type' => 'select',
- '#title' => t('State'),
- '#selected' => array(
- '' => '-select-'
- ),
- '#options' => _list_of_states(),
- '#validated' => TRUE,
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'India'
- )
- )
- )
- );
- $form['city'] = array(
- '#type' => 'select',
- '#title' => t('City'),
- '#options' => _list_of_cities(),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'India'
- )
- )
- )
- );
- $form['pincode'] = array(
- '#type' => 'textfield',
- '#title' => t('Pincode'),
- '#size' => 30,
- '#maxlength' => 6,
- '#required' => False,
- '#attributes' => array(
- 'placeholder' => 'Enter pincode....'
- )
- );
- /***************************************************************************/
- $form['hr'] = array(
- '#type' => 'item',
- '#markup' => ' '
- );
- $form['faculty'] = array(
- '#type' => 'hidden',
- '#value' => 'None',
- '#title' => t('College Teacher/Professor'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- );
- $form['faculty_email'] = array(
- '#type' => 'hidden',
- '#value' => 'None',
- '#title' => t('Teacher/Professor Email Id'),
- '#value' => '@email.com',
- '#size' => 30,
- '#maxlength' => 50
- );
- $form['reviewer'] = array(
- '#type' => 'hidden',
- '#value' => 'None',
- '#title' => t('Reviewer'),
- '#size' => 30,
- '#maxlength' => 50
- );
- $form['version'] = array(
- '#type' => 'select',
- '#title' => t('Version'),
- '#options' => _list_of_software_version(),
- '#required' => TRUE
- );
- $form['older'] = array(
- '#type' => 'textfield',
- '#size' => 30,
- '#maxlength' => 50,
- //'#required' => TRUE,
- '#description' => t('Specify the Older version used'),
- '#states' => array(
- 'visible' => array(
- ':input[name="version"]' => array(
- 'value' => 'olderversion'
- )
- )
- )
- );
- $form['completion_date'] = array(
- '#type' => 'textfield',
- '#title' => t('Expected Date of Completion'),
- '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'),
- '#size' => 10,
- '#maxlength' => 10
- );
- $form['operating_system'] = array(
- '#type' => 'textfield',
- '#title' => t('Operating System'),
- '#required' => TRUE,
- '#size' => 30,
- '#maxlength' => 50
- );
- $reason = array(
- 'Used in more than one University' => t('Used in more than one University'),
- 'The book has multiple editions' => t('The book has multiple editions'),
- 'Extremely useful' => t('Extremely useful'),
- 'Other reason' => t('Any other reason state below')
- );
- $form['reason'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Reasons'),
- '#options' => $reason,
- '#required' => TRUE
- );
- $form['other_reason'] = array(
- '#type' => 'textarea',
- '#size' => 300,
- '#maxlength' => 300,
- '#states' => array(
- 'visible' => array(
- ':input[name="reason[Other reason]"]' => array(
- 'checked' => TRUE
- )
- )
- )
- //'#required' => FALSE,
- );
- $form['proposal_type'] = array(
- '#type' => 'hidden',
- '#default_value' => '1',
- '#required' => FALSE
- );
- $form['reference'] = array(
- '#type' => 'textarea',
- '#title' => t('Reference'),
- '#required' => TRUE,
- '#size' => 500,
- '#maxlength' => 500,
- '#attributes' => array(
- 'placeholder' => 'Links of the syllabus must be provided....'
- )
- );
- $form['form_type'] = array(
- '#type' => 'hidden',
- '#value' => 1
- );
- $form['preference1'] = array(
- '#type' => 'fieldset',
- '#title' => t('Book Preference'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE
- );
- $form['preference1']['book1'] = array(
- '#type' => 'textfield',
- '#title' => t('Title of the book'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE
- );
- $form['preference1']['author1'] = array(
- '#type' => 'textfield',
- '#title' => t('Author Name'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE
- //'#value' => $row1->author,
- //'#disabled' => ($row1->author?TRUE:FALSE),
- );
- $form['preference1']['isbn1'] = array(
- '#type' => 'textfield',
- '#title' => t('ISBN No'),
- '#size' => 30,
- '#maxlength' => 25,
- '#required' => TRUE
- // '#value' => $row1->isbn,
- // '#disabled' => ($row1->isbn?TRUE:FALSE),
- );
- $form['preference1']['publisher1'] = array(
- '#type' => 'textfield',
- '#title' => t('Publisher & Place'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- //'#value' => $row1->publisher,
- );
- $form['preference1']['edition1'] = array(
- '#type' => 'textfield',
- '#title' => t('Edition'),
- '#size' => 4,
- '#maxlength' => 2,
- '#required' => TRUE
- //'#value' => $row1->edition,
- );
- $form['preference1']['year1'] = array(
- '#type' => 'textfield',
- '#title' => t('Year of publication'),
- '#size' => 4,
- '#maxlength' => 4,
- '#required' => TRUE
- //'#value' => $row1->year,
- );
- /*$form['preference2'] = array(
- '#type' => 'fieldset',
- '#title' => t('Book Preference 2'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE
- );
- $form['preference2']['book2'] = array(
- '#type' => 'textfield',
- '#title' => t('Title of the book'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE
- //'#value' => $row2->book,
- //'#disabled' => ($row2->book?TRUE:FALSE),
- );
- $form['preference2']['author2'] = array(
- '#type' => 'textfield',
- '#title' => t('Author Name'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE
- //'#value' => $row2->author,
- //'#disabled' => ($row2->author?TRUE:FALSE),
- );
- $form['preference2']['isbn2'] = array(
- '#type' => 'textfield',
- '#title' => t('ISBN No'),
- '#size' => 30,
- '#maxlength' => 25,
- '#required' => TRUE
- // '#value' => $row2->isbn,
- // '#disabled' => ($row2->isbn?TRUE:FALSE),
- );
- $form['preference2']['publisher2'] = array(
- '#type' => 'textfield',
- '#title' => t('Publisher & Place'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- //'#value' => $row2->publisher,
- );
- $form['preference2']['edition2'] = array(
- '#type' => 'textfield',
- '#title' => t('Edition'),
- '#size' => 4,
- '#maxlength' => 2,
- '#required' => TRUE
- //'#value' => $row2->edition,
- );
- $form['preference2']['year2'] = array(
- '#type' => 'textfield',
- '#title' => t('Year of pulication'),
- '#size' => 4,
- '#maxlength' => 4,
- '#required' => TRUE
- //'#value' => $row2->year,
- );
- $form['preference3'] = array(
- '#type' => 'fieldset',
- '#title' => t('Book Preference 3'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE
- );
- $form['preference3']['book3'] = array(
- '#type' => 'textfield',
- '#title' => t('Title of the book'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE
- //'#value' => $row3->book,
- //'#disabled' => ($row3->book?TRUE:FALSE),
- );
- $form['preference3']['author3'] = array(
- '#type' => 'textfield',
- '#title' => t('Author Name'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE
- //'#value' => $row3->author,
- // '#disabled' => ($row3->author?TRUE:FALSE),
- );
- $form['preference3']['isbn3'] = array(
- '#type' => 'textfield',
- '#title' => t('ISBN No'),
- '#size' => 30,
- '#maxlength' => 25,
- '#required' => TRUE
- //'#value' => $row3->isbn,
- //'#disabled' => ($row3->isbn?TRUE:FALSE),
- );
- $form['preference3']['publisher3'] = array(
- '#type' => 'textfield',
- '#title' => t('Publisher & Place'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- // '#value' => $row3->publisher,
- );
- $form['preference3']['edition3'] = array(
- '#type' => 'textfield',
- '#title' => t('Edition'),
- '#size' => 4,
- '#maxlength' => 2,
- '#required' => TRUE
- //'#value' => $row3->edition,
- );
- $form['preference3']['year3'] = array(
- '#type' => 'textfield',
- '#title' => t('Year of pulication'),
- '#size' => 4,
- '#maxlength' => 4,
- '#required' => TRUE
- //'#value' => $row3->year,
- );
- /*$form['termconditions'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Terms And Conditions'),
- '#options' => array(
- 'status' => t('I agree to the Terms and Conditions '),),
- '#required' => TRUE,
- );*/
- $form['samplefile'] = array(
- '#type' => 'fieldset',
- '#title' => t('Sample Source Files'),
- '#collapsible' => FALSE,
- '#collapsed' => FALSE
- );
- $form['samplefile']['samplefile1'] = array(
- '#type' => 'file',
- '#title' => t('Upload sample source file'),
- '#size' => 48,
- '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') . ' '
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit')
- );
- $form['dir_name'] = array(
- '#type' => 'hidden',
- '#value' => 'None'
- );
- /* #value fix for #default_value bug drupal6
- foreach(array("preference1", "preference2", "preference3") as $preference) {
- foreach($form[$preference] as $key => $value) {
- if(!$form[$preference][$key]["#value"]) {
- unset($form[$preference][$key]["#value"]);
- }
- }
- }*/
- return $form;
+
+/**
+ * Modern replacement for variable_get using Drupal State API.
+ */
+function tc_variable_get($key, $default = '') {
+ return \Drupal::state()->get($key, $default);
}
-function book_proposal_form_validate($form, &$form_state)
-{
- /* mobile */
- if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state['values']['mobile']))
- form_set_error('mobile', t('Invalid mobile number'));
- /* date of completion */
- if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state['values']['completion_date']))
- form_set_error('completion_date', t('Invalid expected date of completion'));
- list($d, $m, $y) = explode('-', $form_state['values']['completion_date']);
- $d = (int) $d;
- $m = (int) $m;
- $y = (int) $y;
- if (!checkdate($m, $d, $y))
- form_set_error('completion_date', t('Invalid expected date of completion'));
- if (mktime(0, 0, 0, $m, $d, $y) <= time())
- form_set_error('completion_date', t('Expected date of completion should be in future'));
- /* edition */
- $cur_year = date('Y');
- if (!preg_match('/^[A-Za-z]/', $form_state['values']['book1']))
- form_set_error('book1', t('Invalid book name for Book Preference 1'));
- if (!preg_match('/^[A-Za-z]/', $form_state['values']['author1']))
- if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn1']))
- form_set_error('isbn1', t('Invalid ISBN for Book Preference 1'));
- if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition1']))
- form_set_error('edition1', t('Invalid edition for Book Preference 1'));
- if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year1']))
- form_set_error('year1', t('Invalid year of pulication for Book Preference 1'));
- if ((int) $form_state['values']['year1'] > $cur_year)
- form_set_error('year1', t('Year of pulication should be not in the future for Book Preference 1'));
- if ($form_state['values']['book1'] && $form_state['values']['author1'])
- {
- $bk1 = trim($form_state['values']['book1']);
- $auth1 = trim($form_state['values']['author1']);
- //var_dump(_dir_name($bk1, $auth1))
- $pref_id = NULL;
- if (_dir_name($bk1, $auth1, $pref_id) != NULL)
- {
- $form_state['values']['dir_name1'] = _dir_name($bk1, $auth1, $pref_id);
- } //_dir_name($bk1, $auth1, $pref_id) != NULL
- } //$form_state['values']['book1'] && $form_state['values']['author1']
- /*****************************************************************************
- if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn2']))
- form_set_error('isbn2', t('Invalid ISBN for Book Preference 2'));
- if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition2']))
- form_set_error('edition2', t('Invalid edition for Book Preference 2'));
- if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year2']))
- form_set_error('year2', t('Invalid year of pulication for Book Preference 2'));
- if ((int) $form_state['values']['year2'] > $cur_year)
- form_set_error('year2', t('Year of pulication should be not in the future for Book Preference 2'));
- if ($form_state['values']['book2'] && $form_state['values']['author2']) {
- $bk2 = trim($form_state['values']['book2']);
- $auth2 = trim($form_state['values']['author2']);
- //var_dump(_dir_name($bk1, $auth1))
- $pref_id = NULL;
- if (_dir_name($bk2, $auth2, $pref_id) != NULL) {
- $form_state['values']['dir_name2'] = _dir_name($bk2, $auth2, $pref_id);
- }
- /*****************************************************************************
- }
- if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn3']))
- form_set_error('isbn3', t('Invalid ISBN for Book Preference 3'));
- if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition3']))
- form_set_error('edition3', t('Invalid edition for Book Preference 3'));
- if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year3']))
- form_set_error('year3', t('Invalid year of pulication for Book Preference 3'));
- if ((int) $form_state['values']['year3'] > $cur_year)
- form_set_error('year3', t('Year of pulication should be not in the future for Book Preference 3'));
- if ($form_state['values']['book3'] && $form_state['values']['author3']) {
- $bk3 = trim($form_state['values']['book3']);
- $auth3 = trim($form_state['values']['author3']);
- //var_dump(_dir_name($bk1, $auth1))
- $pref_id = NULL;
- if (_dir_name($bk1, $auth1, $pref_id) != NULL) {
- $form_state['values']['dir_name3'] = _dir_name($bk3, $auth3, $pref_id);
- }
- /*****************************************************************************
-
- }*/
- if ($form_state['values']['version'] == 'olderversion')
- {
- if ($form_state['values']['older'] == '')
- {
- form_set_error('older', t('Please provide valid version'));
- } //$form_state['values']['older'] == ''
- } //$form_state['values']['version'] == 'olderversion'
- if (isset($_FILES['files']))
- {
- /* check if atleast one source or result file is uploaded */
- if (!($_FILES['files']['name']['samplefile1']))
- form_set_error('samplefile1', t('Please upload sample code main or source file.'));
- /* check for valid filename extensions */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name)
- {
- if ($file_name)
- {
- /* checking file type */
- if (strstr($file_form_name, 'sample'))
- $file_type = 'S';
- else
- $file_type = 'U';
- $allowed_extensions_str = '';
- switch ($file_type)
- {
- case 'S':
- $allowed_extensions_str = variable_get('textbook_companion_source_extensions', '');
- break;
- } //$file_type
- $allowed_extensions = explode(',', $allowed_extensions_str);
- $fnames = explode('.', strtolower($_FILES['files']['name'][$file_form_name]));
- $temp_extension = end($fnames);
- if (!in_array($temp_extension, $allowed_extensions))
- form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.'));
- if ($_FILES['files']['size'][$file_form_name] <= 0)
- form_set_error($file_form_name, t('File size cannot be zero.'));
- /* check if valid file name */
- if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name]))
- form_set_error($file_form_name, t('Invalid file name specified. Only alphabets and numbers are allowed as a valid filename.'));
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- } //isset($_FILES['files'])
- if ($form_state['values']['version'] == 'olderversion')
- {
- if ($form_state['values']['older'] == '')
- {
- form_set_error('older', t('Please provide valid version'));
- } //$form_state['values']['older'] == ''
- } //$form_state['values']['version'] == 'olderversion'
- return;
+
+/**
+ * Modern replacement for variable_set using Drupal State API.
+ */
+function tc_variable_set($key, $value) {
+ \Drupal::state()->set($key, $value);
}
-function book_proposal_form_submit($form, &$form_state, $directory_name = NULL)
-{
- global $user;
- $root_path = textbook_companion_samplecode_path();
- $selections = variable_get("aicte_" . $user->uid, "");
- if (!$user->uid)
- {
- drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error');
- return;
- } //!$user->uid
- /* completion date to timestamp */
- list($d, $m, $y) = explode('-', $form_state['values']['completion_date']);
- $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y);
- $dwsim_version = $form_state['values']['version'];
- if ($form_state['values']['version'] == 'olderversion')
- {
- $form_state['values']['version'] = $form_state['values']['older'];
- } //$form_state['values']['version'] == 'olderversion'
- if ($form_state['values']['country'] == 'other')
- {
- $form_state['values']['country'] = trim($form_state['values']['other_country']);
- $form_state['values']['all_state'] = trim($form_state['values']['other_state']);
- } //$form_state['values']['country'] == 'other'
- if (isset($_POST['reason']))
- {
- if (!($form_state['values']['other_reason']))
- {
- $my_reason = implode(", ", $_POST['reason']);
- } //!($form_state['values']['other_reason'])
- else
- {
- $my_reason = implode(", ", $_POST['reason']);
- $my_reason = $my_reason . "-" . " " . $form_state['values']['other_reason'];
- }
- $form_state['values']['reason'] = $my_reason;
- } //isset($_POST['reason'])
- //var_dump($form_state['values']);
- /*$query = "INSERT INTO {textbook_companion_proposal}
- (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university, faculty, reviewer, completion_date, creation_date, approval_date, proposal_status, scilab_version, operating_system, teacher_email) VALUES (".$user->uid.", 0, '".ucwords(strtolower($form_state['values']['full_name']))."', '".$form_state['values']['mobile']."', '".$form_state['values']['gender']."', '".$form_state['values']['how_project']."', '".$form_state['values']['course']."', '".$form_state['values']['branch']."', '".$form_state['values']['university']."', '".ucwords(strtolower($form_state['values']['faculty']))."', '".ucwords(strtolower($form_state['values']['reviewer']))."', '".$completion_date_timestamp."', '".time()."', 0, 0, '".$scilab_version."', '".$form_state['values']['operating_system']."', '".$form_state['values']['faculty_email']."')";
-
- $result = db_query($query);*/
- $query = "INSERT INTO {textbook_companion_proposal}
- (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university,city,pincode,state,country, faculty, reviewer,reference, completion_date, creation_date, approval_date, proposal_status, dwsim_version, operating_system, teacher_email,reason,samplefilepath,proposal_type,proposed_completion_date) VALUES (:uid, :approver_uid, :full_name, :mobile, :gender, :how_project, :course, :branch, :university, :city,:pincode,:state,:country, :faculty, :reviewer,:reference, :completion_date,
- :creation_date, :approval_date, :proposal_status, :dwsim_version, :operating_system,
-:teacher_email,:reason,:samplefilepath,:proposal_type,:proposed_completion_date)";
- $args = array(
- ":uid" => $user->uid,
- ":approver_uid" => 0,
- ":full_name" => trim(ucwords(strtolower($form_state['values']['full_name']))),
- ":mobile" => trim($form_state['values']['mobile']),
- ":gender" => $form_state['values']['gender'],
- ":how_project" => $form_state['values']['how_project'],
- ":course" => trim($form_state['values']['course']),
- ":branch" => $form_state['values']['branch'],
- ":university" => trim($form_state['values']['university']),
- ":city" => trim($form_state['values']['city']),
- ":pincode" => $form_state['values']['pincode'],
- ":state" => trim($form_state['values']['all_state']),
- ":country" => $form_state['values']['country'],
- ":faculty" => ucwords(strtolower($form_state['values']['faculty'])),
- ":reviewer" => "DWSIM TBC Team",
- ":reference" => trim($form_state['values']['reference']),
- ":completion_date" => $completion_date_timestamp,
- ":creation_date" => time(),
- ":approval_date" => 0,
- ":proposal_status" => 0,
- ":dwsim_version" => trim($form_state['values']['version']),
- ":operating_system" => trim($form_state['values']['operating_system']),
- ":teacher_email" => $form_state['values']['faculty_email'],
- ":reason" => $form_state['values']['reason'],
- ":samplefilepath" => "",
- ":proposal_type" => 0,
- ":proposed_completion_date" => $completion_date_timestamp
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- $dest_path = $result . '/';
- if (!is_dir($root_path . $dest_path))
- mkdir($root_path . $dest_path);
- /* uploading files */
- foreach ($_FILES['files']['name'] as $file_form_name => $file_name)
- {
- if ($file_name)
- {
- /* checking file type */
- $file_type = 'S';
- if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]))
- {
- // drupal_set_message(t("Error uploading file. File !filename already exists.", array('!filename' => $_FILES['files']['name'][$file_form_name])), 'error');
- unlink($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]);
- } //file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
- /* uploading file */
- if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name]))
- {
- $query = "UPDATE {textbook_companion_proposal} SET samplefilepath = :samplefilepath WHERE id = :id";
- $args = array(
- ":samplefilepath" => $dest_path . $_FILES['files']['name'][$file_form_name],
- ":id" => $result
- );
- $updateresult = db_query($query, $args);
- drupal_set_message($file_name . ' uploaded successfully.', 'status');
- } //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
- else
- {
- drupal_set_message('Error uploading file : ' . $dest_path . '/' . $file_name, 'error');
- }
- } //$file_name
- } //$_FILES['files']['name'] as $file_form_name => $file_name
- if (!$result)
- {
- drupal_set_message(t('Error receiving your proposal. Please try again.'), 'error');
- return;
- } //!$result
- /* proposal id */
- $proposal_id = $result;
- /* inserting first book preference */
- if ($form_state['values']['book1'])
- {
- /*$result = db_query("INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES
- (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
- $proposal_id,
- 1,
- ucwords(strtolower($form_state['values']['book1'])),
- ucwords(strtolower($form_state['values']['author1'])),
- $form_state['values']['isbn1'],
- ucwords(strtolower($form_state['values']['publisher1'])),
- $form_state['values']['edition1'],
- $form_state['values']['year1'],
- 0,
- 0
- );*/
- $bk1 = trim($form_state['values']['book1']);
- $auth1 = trim($form_state['values']['author1']);
- $pref_id = NULL;
- $directory_name = _dir_name($bk1, $auth1, $pref_id);
- $query = "INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, directory_name) VALUES (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :directory_name)
- ";
- $args = array(
- ":proposal_id" => $proposal_id,
- ":pref_number" => 1,
- ":book" => trim(ucwords(strtolower($form_state['values']['book1']))),
- ":author" => trim(ucwords(strtolower($form_state['values']['author1']))),
- ":isbn" => trim($form_state['values']['isbn1']),
- ":publisher" => trim(ucwords(strtolower($form_state['values']['publisher1']))),
- ":edition" => trim($form_state['values']['edition1']),
- ":year" => trim($form_state['values']['year1']),
- ":category" => 0,
- ":approval_status" => 0,
- ":directory_name" => $form_state['values']['dir_name1']
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- if (!$result)
- {
- drupal_set_message(t('Error receiving your first book preference.'), 'error');
- } //!$result
- } //$form_state['values']['book1']
- /*******************************************************/
- /* if ($form_state['values']['book2']) {
- /*$result = db_query("INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES
- (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
- $proposal_id,
- 1,
- ucwords(strtolower($form_state['values']['book1'])),
- ucwords(strtolower($form_state['values']['author1'])),
- $form_state['values']['isbn1'],
- ucwords(strtolower($form_state['values']['publisher1'])),
- $form_state['values']['edition1'],
- $form_state['values']['year1'],
- 0,
- 0
- );*/
- /**$bk2 = trim($form_state['values']['book2']);
- $auth2 = trim($form_state['values']['author2']);
- $pref_id = NULL;
- $directory_name = _dir_name($bk2, $auth2, $pref_id);
- $query = "INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, directory_name) VALUES (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :directory_name)
- ";
- $args = array(
- ":proposal_id" => $proposal_id,
-
-
- ":pref_number" => 2,
- ":book" => trim(ucwords(strtolower($form_state['values']['book2']))),
- ":author" => trim(ucwords(strtolower($form_state['values']['author2']))),
- ":isbn" => trim($form_state['values']['isbn2']),
- ":publisher" => trim(ucwords(strtolower($form_state['values']['publisher2']))),
- ":edition" => trim($form_state['values']['edition2']),
- ":year" => trim($form_state['values']['year2']),
- ":category" => 0,
- ":approval_status" => 0,
- ":directory_name" => $form_state['values']['dir_name2']
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- if (!$result) {
- drupal_set_message(t('Error receiving your second book preference.'), 'error');
- }
- }**/
- /*******************************************************/
- /**if ($form_state['values']['book3']) {
- /*$result = db_query("INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES
- (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
- $proposal_id,
- 1,
- ucwords(strtolower($form_state['values']['book1'])),
- ucwords(strtolower($form_state['values']['author1'])),
- $form_state['values']['isbn1'],
- ucwords(strtolower($form_state['values']['publisher1'])),
- $form_state['values']['edition1'],
- $form_state['values']['year1'],
- 0,
- 0
- );*/
- /** $bk3 = trim($form_state['values']['book3']);
- $auth3 = trim($form_state['values']['author3']);
- $pref_id = NULL;
- $directory_name = _dir_name($bk3, $auth3, $pref_id);
- $query = "INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, directory_name) VALUES (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :directory_name)
- ";
- $args = array(
- ":proposal_id" => $proposal_id,
- ":pref_number" => 3,
- ":book" => trim(ucwords(strtolower($form_state['values']['book3']))),
- ":author" => trim(ucwords(strtolower($form_state['values']['author3']))),
- ":isbn" => trim($form_state['values']['isbn3']),
- ":publisher" => trim(ucwords(strtolower($form_state['values']['publisher3']))),
- ":edition" => trim($form_state['values']['edition3']),
- ":year" => trim($form_state['values']['year3']),
- ":category" => 0,
- ":approval_status" => 0,
- ":directory_name" => $form_state['values']['dir_name3']
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- if (!$result) {
- drupal_set_message(t('Error receiving your third book preference.'), 'error');
- }
-
- }**/
- /*******************************************************/
- /* sending email */
- $email_to = $user->mail;
- $from = variable_get('textbook_companion_from_email', '');
- $bcc = variable_get('textbook_companion_bcc_emails', '');
- $cc = variable_get('textbook_companion_cc_emails', '');
- $params['proposal_received']['proposal_id'] = $proposal_id;
- $params['proposal_received']['user_id'] = $user->uid;
- $params['proposal_received']['headers'] = array(
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc
- );
- if (!drupal_mail('textbook_companion', 'proposal_received', $email_to, language_default(), $params, $from, TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message(t('We have received you book proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
+
+/**
+ * Modern replacement for variable_del using Drupal State API.
+ */
+function tc_variable_del($key) {
+ \Drupal::state()->delete($key);
}
+
/**
- * Implementation of hook_mail().
+ * Implements hook_mail().
*/
-function textbook_companion_mail($key, &$message, $params)
-{
- global $user;
- // $language = $message['lianguage'];
- /*$tbc_bcc_emails = array(
- 'Bcc' => variable_get('textbook_companion_bcc_emails', '')
- );*/
- switch ($key)
- {
- case 'proposal_received':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /* initializing data */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_received']['proposal_id']);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $params['proposal_received']['proposal_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- $samplecodefilename = "";
- if (strlen($proposal_data->samplefilepath) >= 5)
- {
- $samplecodefilename = substr($proposal_data->samplefilepath, strrpos($proposal_data->samplefilepath, '/') + 1);
- } //strlen($proposal_data->samplefilepath) >= 5
- else
- {
- $samplecodefilename = "Not provided";
- }
- /*$preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_received']['proposal_id'], 1);
- $preference1_data = db_fetch_object($preference1_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['proposal_received']['proposal_id']);
- $query->condition('pref_number', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference1_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['proposal_received']['proposal_id']);
- $query->condition('pref_number', 2);
- $query->range(0, 1);
- $result = $query->execute();
- $preference2_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['proposal_received']['proposal_id']);
- $query->condition('pref_number', 3);
- $query->range(0, 1);
- $result = $query->execute();
- $preference3_data = $result->fetchObject();
- $user_data = user_load($params['proposal_received']['user_id']);
- $message['headers'] = $params['proposal_received']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] Your textbook companion book proposal has been received', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+function textbook_companion_mail($key, &$message, $params) {
+ $site_name = \Drupal::config('system.site')->get('name');
+ switch ($key) {
+ case 'proposal_received':
+ $query = \Drupal::database()->select('textbook_companion_proposal');
+ $query->fields('textbook_companion_proposal');
+ $query->condition('id', $params['proposal_received']['proposal_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $proposal_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('proposal_id', $params['proposal_received']['proposal_id']);
+ $query->condition('pref_number', 1);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $preference1_data = $result->fetchObject();
+
+ $user_data = User::load($params['proposal_received']['user_id']);
+ $message['headers'] = $params['proposal_received']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] Your textbook companion book proposal has been received', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
We have received your proposal for DWSIM Textbook Companion with the following details:
-Full Name : ' . $proposal_data->full_name . '
-Email : ' . $user_data->mail . '
-Mobile : ' . $proposal_data->mobile . '
-Course : ' . $proposal_data->course . '
-Department/Branch : ' . $proposal_data->branch . '
-University/Institute : ' . $proposal_data->university . '
-City : ' . $proposal_data->city . '
-State : ' . $proposal_data->state . '
-Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . '
-
+Full Name : @full_name
+Email : @email
+Mobile : @mobile
+Course : @course
+Department/Branch : @branch
+University/Institute : @university
+City : @city
+State : @state
+Expected date of completion : @completion_date
Your Book Preferences :
Book Preference :-
-Title of the book : ' . $preference1_data->book . '
-Author name : ' . $preference1_data->author . '
-ISBN No. : ' . $preference1_data->isbn . '
-Publisher and Place : ' . $preference1_data->publisher . '
-Edition : ' . $preference1_data->edition . '
-Year of publication : ' . $preference1_data->year . '
-
-
-
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
Your proposal is under review. You will soon receive an email when your proposal has been approved/ disapproved. Thank you for your submission.
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- break;
- case 'proposal_disapproved':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /* initializing data */
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_disapproved']['proposal_id']);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $params['proposal_disapproved']['proposal_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- /*$preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_disapproved']['proposal_id'], 1);
- $preference1_data = db_fetch_object($preference1_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['proposal_disapproved']['proposal_id']);
- $query->condition('pref_number', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $preference1_data = $result->fetchObject();
- $user_data = user_load($params['proposal_disapproved']['user_id']);
- $message['headers'] = $params['proposal_disapproved']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] Your textbook companion book proposal has been disapproved', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
-
-We regret to inform you that all the uploaded examples including the book
-with following details have been deleted permanently.
-
-Full Name : ' . $proposal_data->full_name . '
-Email : ' . $user_data->mail . '
-Mobile : ' . $proposal_data->mobile . '
-Course : ' . $proposal_data->course . '
-Department/Branch : ' . $proposal_data->branch . '
-University/Institute : ' . $proposal_data->university . '
-City : ' . $proposal_data->city . '
-State : ' . $proposal_data->state . '
-
-Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . '
-
-Reason : ' . $proposal_data->reason . '
-
-
-Reference : ' . $proposal_data->reference . '
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@full_name' => $proposal_data ? $proposal_data->full_name : '',
+ '@email' => $user_data ? $user_data->getEmail() : '',
+ '@mobile' => $proposal_data ? $proposal_data->mobile : '',
+ '@course' => $proposal_data ? $proposal_data->course : '',
+ '@branch' => $proposal_data ? $proposal_data->branch : '',
+ '@university' => $proposal_data ? $proposal_data->university : '',
+ '@city' => $proposal_data ? $proposal_data->city : '',
+ '@state' => $proposal_data ? $proposal_data->state : '',
+ '@completion_date' => $proposal_data ? date('d-m-Y', $proposal_data->completion_date) : '',
+ '@book' => $preference1_data ? $preference1_data->book : '',
+ '@author' => $preference1_data ? $preference1_data->author : '',
+ '@isbn' => $preference1_data ? $preference1_data->isbn : '',
+ '@publisher' => $preference1_data ? $preference1_data->publisher : '',
+ '@edition' => $preference1_data ? $preference1_data->edition : '',
+ '@year' => $preference1_data ? $preference1_data->year : '',
+ ]);
+ break;
+
+ case 'proposal_disapproved':
+ $query = \Drupal::database()->select('textbook_companion_proposal');
+ $query->fields('textbook_companion_proposal');
+ $query->condition('id', $params['proposal_disapproved']['proposal_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $proposal_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('proposal_id', $params['proposal_disapproved']['proposal_id']);
+ $query->condition('pref_number', 1);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $preference1_data = $result->fetchObject();
+
+ $user_data = User::load($params['proposal_disapproved']['user_id']);
+ $message['headers'] = $params['proposal_disapproved']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] Your textbook companion book proposal has been disapproved', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
+
+We regret to inform you that all the uploaded examples including the book with following details have been deleted permanently.
+
+Full Name : @full_name
+Email : @email
+Mobile : @mobile
+Course : @course
+Department/Branch : @branch
+University/Institute : @university
+City : @city
+State : @state
+Expected date of completion : @completion_date
+
+Reason : @reason
+Reference : @reference
Your Book Preferences :
Book Preference 1 :-
-Title of the book : ' . $preference1_data->book . '
-Author name : ' . $preference1_data->author . '
-ISBN No. : ' . $preference1_data->isbn . '
-Publisher and Place : ' . $preference1_data->publisher . '
-Edition : ' . $preference1_data->edition . '
-Year of publication : ' . $preference1_data->year . '
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
-Reason for disapproval: ' . $proposal_data->message . '
+Reason for disapproval: @message
You are welcome to submit a new proposal.
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'proposal_approved':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_approved']['proposal_id']);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $params['proposal_approved']['proposal_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- /* $approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_approved']['proposal_id']);
- $approved_preference_data = db_fetch_object($approved_preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['proposal_approved']['proposal_id']);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $approved_preference_data = $result->fetchObject();
- $user_data = user_load($params['proposal_approved']['user_id']);
- $message['headers'] = $params['proposal_approved']['headers'];
- $message['headers'] = $params['proposal_approved']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] Your book proposal has been approved', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@full_name' => $proposal_data ? $proposal_data->full_name : '',
+ '@email' => $user_data ? $user_data->getEmail() : '',
+ '@mobile' => $proposal_data ? $proposal_data->mobile : '',
+ '@course' => $proposal_data ? $proposal_data->course : '',
+ '@branch' => $proposal_data ? $proposal_data->branch : '',
+ '@university' => $proposal_data ? $proposal_data->university : '',
+ '@city' => $proposal_data ? $proposal_data->city : '',
+ '@state' => $proposal_data ? $proposal_data->state : '',
+ '@completion_date' => $proposal_data ? date('d-m-Y', $proposal_data->completion_date) : '',
+ '@reason' => $proposal_data ? $proposal_data->reason : '',
+ '@reference' => $proposal_data ? $proposal_data->reference : '',
+ '@book' => $preference1_data ? $preference1_data->book : '',
+ '@author' => $preference1_data ? $preference1_data->author : '',
+ '@isbn' => $preference1_data ? $preference1_data->isbn : '',
+ '@publisher' => $preference1_data ? $preference1_data->publisher : '',
+ '@edition' => $preference1_data ? $preference1_data->edition : '',
+ '@year' => $preference1_data ? $preference1_data->year : '',
+ '@message' => $proposal_data ? $proposal_data->message : '',
+ ]);
+ break;
+
+ case 'proposal_approved':
+ $query = \Drupal::database()->select('textbook_companion_proposal');
+ $query->fields('textbook_companion_proposal');
+ $query->condition('id', $params['proposal_approved']['proposal_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $proposal_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('proposal_id', $params['proposal_approved']['proposal_id']);
+ $query->condition('approval_status', 1);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $approved_preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['proposal_approved']['user_id']);
+ $message['headers'] = $params['proposal_approved']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] Your book proposal has been approved', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
Congratulations! Your proposal for DWSIM Textbook Companion with the following details is approved.
-Full Name : ' . $proposal_data->full_name . '
-Email : ' . $user_data->mail . '
-Mobile : ' . $proposal_data->mobile . '
-Course : ' . $proposal_data->course . '
-Department/Branch : ' . $proposal_data->branch . '
-University/Institute : ' . $proposal_data->university . '
-College Teacher / Professor : ' . $proposal_data->faculty . '
-Reviewer : ' . $proposal_data->reviewer . '
-Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . '
-
-Reason : ' . $proposal_data->reason . '
-
-Reference : ' . $proposal_data->reference . '
-
-Title of the book : ' . $approved_preference_data->book . '
-Author name : ' . $approved_preference_data->author . '
-ISBN No. : ' . $approved_preference_data->isbn . '
-Publisher and Place : ' . $approved_preference_data->publisher . '
-Edition : ' . $approved_preference_data->edition . '
-Year of publication : ' . $approved_preference_data->year . '
+Full Name : @full_name
+Email : @email
+Mobile : @mobile
+Course : @course
+Department/Branch : @branch
+University/Institute : @university
+College Teacher / Professor : @faculty
+Reviewer : @reviewer
+Expected date of completion : @completion_date
+
+Reason : @reason
+Reference : @reference
+
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
Please ensure that ALL the guidelines for coding are strictly followed:
-
http://dwsim.fossee.in/textbook-companion/guidelines-coding
-
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'proposal_completed':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_completed']['proposal_id']);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $params['proposal_completed']['proposal_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- /*$approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_completed']['proposal_id']);
- $approved_preference_data = db_fetch_object($approved_preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['proposal_completed']['proposal_id']);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $approved_preference_data = $result->fetchObject();
- $user_data = user_load($params['proposal_completed']['user_id']);
- $message['headers'] = $params['proposal_approved']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] Congratulations on the completion of the Textbook Companion.', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@full_name' => $proposal_data ? $proposal_data->full_name : '',
+ '@email' => $user_data ? $user_data->getEmail() : '',
+ '@mobile' => $proposal_data ? $proposal_data->mobile : '',
+ '@course' => $proposal_data ? $proposal_data->course : '',
+ '@branch' => $proposal_data ? $proposal_data->branch : '',
+ '@university' => $proposal_data ? $proposal_data->university : '',
+ '@faculty' => $proposal_data ? $proposal_data->faculty : '',
+ '@reviewer' => $proposal_data ? $proposal_data->reviewer : '',
+ '@completion_date' => $proposal_data ? date('d-m-Y', $proposal_data->completion_date) : '',
+ '@reason' => $proposal_data ? $proposal_data->reason : '',
+ '@reference' => $proposal_data ? $proposal_data->reference : '',
+ '@book' => $approved_preference_data ? $approved_preference_data->book : '',
+ '@author' => $approved_preference_data ? $approved_preference_data->author : '',
+ '@isbn' => $approved_preference_data ? $approved_preference_data->isbn : '',
+ '@publisher' => $approved_preference_data ? $approved_preference_data->publisher : '',
+ '@edition' => $approved_preference_data ? $approved_preference_data->edition : '',
+ '@year' => $approved_preference_data ? $approved_preference_data->year : '',
+ ]);
+ break;
+
+ case 'proposal_completed':
+ $query = \Drupal::database()->select('textbook_companion_proposal');
+ $query->fields('textbook_companion_proposal');
+ $query->condition('id', $params['proposal_completed']['proposal_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $proposal_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('proposal_id', $params['proposal_completed']['proposal_id']);
+ $query->condition('approval_status', 1);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $approved_preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['proposal_completed']['user_id']);
+ $message['headers'] = $params['proposal_approved']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] Congratulations on the completion of the Textbook Companion.', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
The textbook companion on the following book has been completed successfully by you:
-Full Name : ' . $proposal_data->full_name . '
-Email : ' . $user_data->mail . '
-Mobile : ' . $proposal_data->mobile . '
-Course : ' . $proposal_data->course . '
-Department/Branch : ' . $proposal_data->branch . '
-University/Institute : ' . $proposal_data->university . '
-College Teacher / Professor : ' . $proposal_data->faculty . '
-Reviewer : ' . $proposal_data->reviewer . '
-Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . '
-
-
-Title of the book : ' . $approved_preference_data->book . '
-Author name : ' . $approved_preference_data->author . '
-ISBN No. : ' . $approved_preference_data->isbn . '
-Publisher and Place : ' . $approved_preference_data->publisher . '
-Edition : ' . $approved_preference_data->edition . '
-Year of publication : ' . $approved_preference_data->year . '
-
-Your book is now available at following link to download.
-
-http://dwsim.fossee.in/textbook-companion/textbook-run/' . $approved_preference_data->id . '
+Full Name : @full_name
+Email : @email
+Mobile : @mobile
+Course : @course
+Department/Branch : @branch
+University/Institute : @university
+College Teacher / Professor : @faculty
+Reviewer : @reviewer
+Expected date of completion : @completion_date
+
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
+
+Your book is now available at following link to download:
+http://dwsim.fossee.in/textbook-companion/textbook-run/@preference_id
Now you should be able to propose a new book.
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- /***********************************************************************************************/
- case 'all_code_submitted':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_completed']['proposal_id']);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $params['all_code_submitted']['proposal_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- /*$approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_completed']['proposal_id']);
- $approved_preference_data = db_fetch_object($approved_preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['all_code_submitted']['proposal_id']);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $approved_preference_data = $result->fetchObject();
- $user_data = user_load($params['all_code_submitted']['user_id']);
- $message['headers'] = $params['all_code_submitted']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] You have marked to submited code for all examples.', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@full_name' => $proposal_data ? $proposal_data->full_name : '',
+ '@email' => $user_data ? $user_data->getEmail() : '',
+ '@mobile' => $proposal_data ? $proposal_data->mobile : '',
+ '@course' => $proposal_data ? $proposal_data->course : '',
+ '@branch' => $proposal_data ? $proposal_data->branch : '',
+ '@university' => $proposal_data ? $proposal_data->university : '',
+ '@faculty' => $proposal_data ? $proposal_data->faculty : '',
+ '@reviewer' => $proposal_data ? $proposal_data->reviewer : '',
+ '@completion_date' => $proposal_data ? date('d-m-Y', $proposal_data->completion_date) : '',
+ '@book' => $approved_preference_data ? $approved_preference_data->book : '',
+ '@author' => $approved_preference_data ? $approved_preference_data->author : '',
+ '@isbn' => $approved_preference_data ? $approved_preference_data->isbn : '',
+ '@publisher' => $approved_preference_data ? $approved_preference_data->publisher : '',
+ '@edition' => $approved_preference_data ? $approved_preference_data->edition : '',
+ '@year' => $approved_preference_data ? $approved_preference_data->year : '',
+ '@preference_id' => $approved_preference_data ? $approved_preference_data->id : '',
+ ]);
+ break;
+
+ case 'all_code_submitted':
+ $query = \Drupal::database()->select('textbook_companion_proposal');
+ $query->fields('textbook_companion_proposal');
+ $query->condition('id', $params['all_code_submitted']['proposal_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $proposal_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('proposal_id', $params['all_code_submitted']['proposal_id']);
+ $query->condition('approval_status', 1);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $approved_preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['all_code_submitted']['user_id']);
+ $message['headers'] = $params['all_code_submitted']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] You have marked to submitted code for all examples.', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
You have submitted codes for all examples:
-Full Name : ' . $proposal_data->full_name . '
-Email : ' . $user_data->mail . '
-Mobile : ' . $proposal_data->mobile . '
-Course : ' . $proposal_data->course . '
-Department/Branch : ' . $proposal_data->branch . '
-University/Institute : ' . $proposal_data->university . '
-College Teacher / Professor : ' . $proposal_data->faculty . '
-Reviewer : ' . $proposal_data->reviewer . '
-Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . '
-
-
-Title of the book : ' . $approved_preference_data->book . '
-Author name : ' . $approved_preference_data->author . '
-ISBN No. : ' . $approved_preference_data->isbn . '
-Publisher and Place : ' . $approved_preference_data->publisher . '
-Edition : ' . $approved_preference_data->edition . '
-Year of publication : ' . $approved_preference_data->year . '
+Full Name : @full_name
+Email : @email
+Mobile : @mobile
+Course : @course
+Department/Branch : @branch
+University/Institute : @university
+College Teacher / Professor : @faculty
+Reviewer : @reviewer
+Expected date of completion : @completion_date
+
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
You shall be notified after the code is reviewed.
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'all_code_submitted_status_changed':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_completed']['proposal_id']);
- $proposal_data = db_fetch_object($proposal_q);*/
- $query = db_select('textbook_companion_proposal');
- $query->fields('textbook_companion_proposal');
- $query->condition('id', $params['all_code_submitted_status_changed']['proposal_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $proposal_data = $result->fetchObject();
- /*$approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_completed']['proposal_id']);
- $approved_preference_data = db_fetch_object($approved_preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('proposal_id', $params['all_code_submitted_status_changed']['proposal_id']);
- $query->condition('approval_status', 1);
- $query->range(0, 1);
- $result = $query->execute();
- $approved_preference_data = $result->fetchObject();
- $user_data = user_load($params['all_code_submitted_status_changed']['user_id']);
- $message['headers'] = $params['all_code_submitted_status_changed']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] Your interface for code submission has been enabled by the reviewer', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@full_name' => $proposal_data ? $proposal_data->full_name : '',
+ '@email' => $user_data ? $user_data->getEmail() : '',
+ '@mobile' => $proposal_data ? $proposal_data->mobile : '',
+ '@course' => $proposal_data ? $proposal_data->course : '',
+ '@branch' => $proposal_data ? $proposal_data->branch : '',
+ '@university' => $proposal_data ? $proposal_data->university : '',
+ '@faculty' => $proposal_data ? $proposal_data->faculty : '',
+ '@reviewer' => $proposal_data ? $proposal_data->reviewer : '',
+ '@completion_date' => $proposal_data ? date('d-m-Y', $proposal_data->completion_date) : '',
+ '@book' => $approved_preference_data ? $approved_preference_data->book : '',
+ '@author' => $approved_preference_data ? $approved_preference_data->author : '',
+ '@isbn' => $approved_preference_data ? $approved_preference_data->isbn : '',
+ '@publisher' => $approved_preference_data ? $approved_preference_data->publisher : '',
+ '@edition' => $approved_preference_data ? $approved_preference_data->edition : '',
+ '@year' => $approved_preference_data ? $approved_preference_data->year : '',
+ ]);
+ break;
+
+ case 'all_code_submitted_status_changed':
+ $query = \Drupal::database()->select('textbook_companion_proposal');
+ $query->fields('textbook_companion_proposal');
+ $query->condition('id', $params['all_code_submitted_status_changed']['proposal_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $proposal_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('proposal_id', $params['all_code_submitted_status_changed']['proposal_id']);
+ $query->condition('approval_status', 1);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $approved_preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['all_code_submitted_status_changed']['user_id']);
+ $message['headers'] = $params['all_code_submitted_status_changed']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] Your interface for code submission has been enabled by the reviewer', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
Your interface for code submission has been enabled by the reviewer, you can now able to send more code for this book.
-Full Name : ' . $proposal_data->full_name . '
-Email : ' . $user_data->mail . '
-Mobile : ' . $proposal_data->mobile . '
-Course : ' . $proposal_data->course . '
-Department/Branch : ' . $proposal_data->branch . '
-University/Institute : ' . $proposal_data->university . '
-College Teacher / Professor : ' . $proposal_data->faculty . '
-Reviewer : ' . $proposal_data->reviewer . '
-Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . '
-
-
-Title of the book : ' . $approved_preference_data->book . '
-Author name : ' . $approved_preference_data->author . '
-ISBN No. : ' . $approved_preference_data->isbn . '
-Publisher and Place : ' . $approved_preference_data->publisher . '
-Edition : ' . $approved_preference_data->edition . '
-Year of publication : ' . $approved_preference_data->year . '
-
+Full Name : @full_name
+Email : @email
+Mobile : @mobile
+Course : @course
+Department/Branch : @branch
+University/Institute : @university
+College Teacher / Professor : @faculty
+Reviewer : @reviewer
+Expected date of completion : @completion_date
+
+Title of the book : @book
+Author name : @author
+ISBN No. : @isbn
+Publisher and Place : @publisher
+Edition : @edition
+Year of publication : @year
+
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- /*****************************************************************************************/
- case 'example_uploaded':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_uploaded']['example_id']);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $params['example_uploaded']['example_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $example_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $query->range(0, 1);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- $user_data = user_load($params['example_uploaded']['user_id']);
- $message['headers'] = $params['example_uploaded']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] You have uploaded example for Textbook Companion', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
-
-You have uploaded the following solution :
-
-Title of the book : ' . $preference_data->book . '
-Title of the chapter : ' . $chapter_data->name . '
-Example number : ' . $example_data->number . '
-Caption : ' . $example_data->caption . '
-
-You shall be notified after the solution is reviewed
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@full_name' => $proposal_data ? $proposal_data->full_name : '',
+ '@email' => $user_data ? $user_data->getEmail() : '',
+ '@mobile' => $proposal_data ? $proposal_data->mobile : '',
+ '@course' => $proposal_data ? $proposal_data->course : '',
+ '@branch' => $proposal_data ? $proposal_data->branch : '',
+ '@university' => $proposal_data ? $proposal_data->university : '',
+ '@faculty' => $proposal_data ? $proposal_data->faculty : '',
+ '@reviewer' => $proposal_data ? $proposal_data->reviewer : '',
+ '@completion_date' => $proposal_data ? date('d-m-Y', $proposal_data->completion_date) : '',
+ '@book' => $approved_preference_data ? $approved_preference_data->book : '',
+ '@author' => $approved_preference_data ? $approved_preference_data->author : '',
+ '@isbn' => $approved_preference_data ? $approved_preference_data->isbn : '',
+ '@publisher' => $approved_preference_data ? $approved_preference_data->publisher : '',
+ '@edition' => $approved_preference_data ? $approved_preference_data->edition : '',
+ '@year' => $approved_preference_data ? $approved_preference_data->year : '',
+ ]);
+ break;
+
+ case 'example_uploaded':
+ $query = \Drupal::database()->select('textbook_companion_example');
+ $query->fields('textbook_companion_example');
+ $query->condition('id', $params['example_uploaded']['example_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $example_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_chapter');
+ $query->fields('textbook_companion_chapter');
+ $query->condition('id', $example_data->chapter_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $chapter_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('id', $chapter_data->preference_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['example_uploaded']['user_id']);
+ $message['headers'] = $params['example_uploaded']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] You have uploaded example for Textbook Companion', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
+
+You have uploaded the following solution:
+
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
+
+You shall be notified after the solution is reviewed.
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'example_updated':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_updated']['example_id']);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $params['example_updated']['example_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $example_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $query->range(0, 1);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- $user_data = user_load($params['example_updated']['user_id']);
- $message['headers'] = $params['example_updated']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] You have updated example for Textbook Companion', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $preference_data ? $preference_data->book : '',
+ '@chapter' => $chapter_data ? $chapter_data->name : '',
+ '@number' => $example_data ? $example_data->number : '',
+ '@caption' => $example_data ? $example_data->caption : '',
+ ]);
+ break;
+
+ case 'example_updated':
+ $query = \Drupal::database()->select('textbook_companion_example');
+ $query->fields('textbook_companion_example');
+ $query->condition('id', $params['example_updated']['example_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $example_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_chapter');
+ $query->fields('textbook_companion_chapter');
+ $query->condition('id', $example_data->chapter_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $chapter_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('id', $chapter_data->preference_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['example_updated']['user_id']);
+ $message['headers'] = $params['example_updated']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] You have updated example for Textbook Companion', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
You have updated the following example:
-Title of the book : ' . $preference_data->book . '
-Title of the chapter : ' . $chapter_data->name . '
-Example number : ' . $example_data->number . '
-Caption : ' . $example_data->caption . '
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
The example is still under review. You will be notified when it has been approved.
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'example_updated_admin':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_updated_admin']['example_id']);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $params['example_updated_admin']['example_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $example_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $query->range(0, 1);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- $user_data = user_load($params['example_updated_admin']['user_id']);
- $message['headers'] = $params['example_updated_admin']['headers'];
- $message['subject'] = t('[!site_name] Reviewer have updated example for Textbook Companion ', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
-
-Reviewer have updated the following example:
-
-Title of the book : ' . $preference_data->book . '
-Title of the chapter : ' . $chapter_data->name . '
-Example number : ' . $example_data->number . '
-Caption : ' . $example_data->caption . '
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $preference_data ? $preference_data->book : '',
+ '@chapter' => $chapter_data ? $chapter_data->name : '',
+ '@number' => $example_data ? $example_data->number : '',
+ '@caption' => $example_data ? $example_data->caption : '',
+ ]);
+ break;
+
+ case 'example_updated_admin':
+ $query = \Drupal::database()->select('textbook_companion_example');
+ $query->fields('textbook_companion_example');
+ $query->condition('id', $params['example_updated_admin']['example_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $example_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_chapter');
+ $query->fields('textbook_companion_chapter');
+ $query->condition('id', $example_data->chapter_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $chapter_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('id', $chapter_data->preference_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['example_updated_admin']['user_id']);
+ $message['headers'] = $params['example_updated_admin']['headers'] ?? [];
+ $message['subject'] = t('[@site_name] Reviewer has updated example for Textbook Companion', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
+
+Reviewer has updated the following example:
+
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'example_approved':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_approved']['example_id']);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $params['example_approved']['example_id']);
- $query->range(0, 1);
- $result = $query->execute();
- $example_data = $result->fetchObject();
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $query->range(0, 1);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $chapter_data->preference_id);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- $user_data = user_load($params['example_approved']['user_id']);
- $message['headers'] = $params['example_approved']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] Your uploaded example has been approved for Textbook Companion', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $preference_data ? $preference_data->book : '',
+ '@chapter' => $chapter_data ? $chapter_data->name : '',
+ '@number' => $example_data ? $example_data->number : '',
+ '@caption' => $example_data ? $example_data->caption : '',
+ ]);
+ break;
+
+ case 'example_approved':
+ $query = \Drupal::database()->select('textbook_companion_example');
+ $query->fields('textbook_companion_example');
+ $query->condition('id', $params['example_approved']['example_id']);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $example_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_chapter');
+ $query->fields('textbook_companion_chapter');
+ $query->condition('id', $example_data->chapter_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $chapter_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('id', $chapter_data->preference_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $preference_data = $result->fetchObject();
+
+ $user_data = User::load($params['example_approved']['user_id']);
+ $message['headers'] = $params['example_approved']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] Your uploaded example has been approved for Textbook Companion', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
Your example for DWSIM Textbook Companion with the following details is approved.
-Title of the book : ' . $preference_data->book . '
-Title of the chapter : ' . $chapter_data->name . '
-Example number : ' . $example_data->number . '
-Caption : ' . $example_data->caption . '
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'example_disapproved':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['example_disapproved']['user_id']);
- $preference_id = $params['example_disapproved']['preference_id'];
- $chapter_id = $params['example_disapproved']['chapter_id'];
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $chapter_id);
- $query->range(0, 1);
- $result = $query->execute();
- $chapter_data = $result->fetchObject();
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $preference_id);
- $query->range(0, 1);
- $result = $query->execute();
- $preference_data = $result->fetchObject();
- $message['headers'] = $params['example_disapproved']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] Your uploaded example has been disapproved for Textbook Companion', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $preference_data ? $preference_data->book : '',
+ '@chapter' => $chapter_data ? $chapter_data->name : '',
+ '@number' => $example_data ? $example_data->number : '',
+ '@caption' => $example_data ? $example_data->caption : '',
+ ]);
+ break;
+
+ case 'example_disapproved':
+ $user_data = User::load($params['example_disapproved']['user_id']);
+ $preference_id = $params['example_disapproved']['preference_id'];
+ $chapter_id = $params['example_disapproved']['chapter_id'];
+
+ $query = \Drupal::database()->select('textbook_companion_chapter');
+ $query->fields('textbook_companion_chapter');
+ $query->condition('id', $chapter_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $chapter_data = $result->fetchObject();
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('id', $preference_id);
+ $query->range(0, 1);
+ $result = $query->execute();
+ $preference_data = $result->fetchObject();
+
+ $message['headers'] = $params['example_disapproved']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] Your uploaded example has been disapproved for Textbook Companion', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
Your following example has been disapproved:
-Title of the book : ' . $preference_data->book . '
-Title of the chapter : ' . $chapter_data->name . '
-Example number : ' . $params['example_disapproved']['example_number'] . '
-Caption : ' . $params['example_disapproved']['example_caption'] . '
+Title of the book : @book
+Title of the chapter : @chapter
+Example number : @number
+Caption : @caption
-Reason for dis-approval : ' . $params['example_disapproved']['message'] . '
+Reason for dis-approval : @reason
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'example_deleted_user':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['example_deleted_user']['user_id']);
- $message['headers'] = $params['example_deleted_user']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] User has deleted pending example for Textbook Companion', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $preference_data ? $preference_data->book : '',
+ '@chapter' => $chapter_data ? $chapter_data->name : '',
+ '@number' => $params['example_disapproved']['example_number'],
+ '@caption' => $params['example_disapproved']['example_caption'],
+ '@reason' => $params['example_disapproved']['message'],
+ ]);
+ break;
+
+ case 'example_deleted_user':
+ $user_data = User::load($params['example_deleted_user']['user_id']);
+ $message['headers'] = $params['example_deleted_user']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] User has deleted pending example for Textbook Companion', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
Your following pending example has been deleted :
-Title of the Book : ' . $params['example_deleted_user']['book_title'] . '
-Title of the Chapter : ' . $params['example_deleted_user']['chapter_title'] . '
-Example number : ' . $params['example_deleted_user']['example_number'] . '
-Caption : ' . $params['example_deleted_user']['example_caption'] . '
+Title of the Book : @book
+Title of the Chapter : @chapter
+Example number : @number
+Caption : @caption
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'dependency_uploaded':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['dependency_uploaded']['user_id']);
- $dependency_files = implode(',', $params['dependency_uploaded']['dependency_names']);
- $message['headers'] = $params['dependency_uploaded']['headers'];
- $message['subject'] = t('[!site_name][Textbook Companion] You have uploaded dependency file', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $params['example_deleted_user']['book_title'],
+ '@chapter' => $params['example_deleted_user']['chapter_title'],
+ '@number' => $params['example_deleted_user']['example_number'],
+ '@caption' => $params['example_deleted_user']['example_caption'],
+ ]);
+ break;
+
+ case 'dependency_uploaded':
+ $user_data = User::load($params['dependency_uploaded']['user_id']);
+ $dependency_files = implode(',', $params['dependency_uploaded']['dependency_names']);
+ $message['headers'] = $params['dependency_uploaded']['headers'] ?? [];
+ $message['subject'] = t('[@site_name][Textbook Companion] You have uploaded dependency file', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
You have uploaded following dependency files :
- ' . $dependency_files . '
+ @files
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'feedback_received':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['feedback_received']['user_id']);
- $message['subject'] = t('[!site_name][Textbook Companion] We have received your feedback', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@files' => $dependency_files,
+ ]);
+ break;
+
+ case 'feedback_received':
+ $user_data = User::load($params['feedback_received']['user_id']);
+ $message['subject'] = t('[@site_name][Textbook Companion] We have received your feedback', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
We have received your following feedback
-Title of the Book: ' . $params['feedback_received']['book_title'] . '
-Title of the Chapter: ' . $params['feedback_received']['chapter_number'] . ' ' . $params['feedback_received']['chapter_title'] . '
-Example No.: ' . $params['feedback_received']['example_no'] . '
+Title of the Book: @book
+Title of the Chapter: @chapter_num @chapter_title
+Example No.: @example_no
Your feedback :
-' . $params['feedback_received']['feedback'] . '
+@feedback
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'internshipform':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['internshipform']['user_id']);
- $message['subject'] = t('[!site_name][Textbook Companion] We have received your feedback', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $params['feedback_received']['book_title'],
+ '@chapter_num' => $params['feedback_received']['chapter_number'],
+ '@chapter_title' => $params['feedback_received']['chapter_title'],
+ '@example_no' => $params['feedback_received']['example_no'],
+ '@feedback' => $params['feedback_received']['feedback'],
+ ]);
+ break;
+
+ case 'internshipform':
+ $user_data = User::load($params['internshipform']['user_id']);
+ $message['subject'] = t('[@site_name][Textbook Companion] We have received your feedback', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
We have received your Internship Form Application for the book
-Title of the Book: ' . $params['internshipform']['book_title'] . '
-Title of the Chapter: ' . $params['internshipform']['chapter_number'] . ' ' . $params['internshipform']['chapter_title'] . '
-Example No.: ' . $params['internshipform']['example_no'] . '
+Title of the Book: @book
+Title of the Chapter: @chapter_num @chapter_title
+Example No.: @example_no
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'copyrighttransferform':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['copyrighttransferform']['user_id']);
- $message['subject'] = t('[!site_name][Textbook Companion] We have received your feedback', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $params['internshipform']['book_title'],
+ '@chapter_num' => $params['internshipform']['chapter_number'],
+ '@chapter_title' => $params['internshipform']['chapter_title'],
+ '@example_no' => $params['internshipform']['example_no'],
+ ]);
+ break;
+
+ case 'copyrighttransferform':
+ $user_data = User::load($params['copyrighttransferform']['user_id']);
+ $message['subject'] = t('[@site_name][Textbook Companion] We have received your feedback', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
We have received your Copyright Form Application for the book
-Title of the Book: ' . $params['copyrighttransferform']['book_title'] . '
-Title of the Chapter: ' . $params['copyrighttransferform']['chapter_number'] . ' ' . $params['copyrighttransferform']['chapter_title'] . '
-Example No.: ' . $params['copyrighttransferform']['example_no'] . '
+Title of the Book: @book
+Title of the Chapter: @chapter_num @chapter_title
+Example No.: @example_no
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'undertakingform':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['undertakingform']['user_id']);
- $message['subject'] = t('[!site_name][Textbook Companion] We have received your feedback', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $params['copyrighttransferform']['book_title'],
+ '@chapter_num' => $params['copyrighttransferform']['chapter_number'],
+ '@chapter_title' => $params['copyrighttransferform']['chapter_title'],
+ '@example_no' => $params['copyrighttransferform']['example_no'],
+ ]);
+ break;
+
+ case 'undertakingform':
+ $user_data = User::load($params['undertakingform']['user_id']);
+ $message['subject'] = t('[@site_name][Textbook Companion] We have received your feedback', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
We have received your Undertaking Form Application for the book
-Title of the Book: ' . $params['undertakingform']['book_title'] . '
-Title of the Chapter: ' . $params['undertakingform']['chapter_number'] . ' ' . $params['undertakingform']['chapter_title'] . '
-Example No.: ' . $params['undertakingform']['example_no'] . '
+Title of the Book: @book
+Title of the Chapter: @chapter_num @chapter_title
+Example No.: @example_no
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'remark':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['remark']['user_id']);
- $message['subject'] = t('[!site_name][Textbook Companion] A remark has been given.Please check your contact detail form', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $params['undertakingform']['book_title'],
+ '@chapter_num' => $params['undertakingform']['chapter_number'],
+ '@chapter_title' => $params['undertakingform']['chapter_title'],
+ '@example_no' => $params['undertakingform']['example_no'],
+ ]);
+ break;
+
+ case 'remark':
+ $user_data = User::load($params['remark']['user_id']);
+ $message['subject'] = t('[@site_name][Textbook Companion] A remark has been given.Please check your contact detail form', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
A Remark has been given.Please check your Contact Detail Form
-Title of the Book: ' . $params['internshipform']['book_title'] . '
-Title of the Chapter: ' . $params['internshipform']['chapter_number'] . ' ' . $params['internshipform']['chapter_title'] . '
-Example No.: ' . $params['internshipform']['example_no'] . '
+Title of the Book: @book
+Title of the Chapter: @chapter_num @chapter_title
+Example No.: @example_no
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'cheque_sent':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $user_data = user_load($params['cheque_sent']['user_id']);
- $message['subject'] = t('[!site_name][Textbook Companion] We have received your feedback', array(
- '!site_name' => variable_get('site_name', '')
- ));
- $message['body'] = array(
- 'body' => t('
-Dear !user_name,
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $params['internshipform']['book_title'],
+ '@chapter_num' => $params['internshipform']['chapter_number'],
+ '@chapter_title' => $params['internshipform']['chapter_title'],
+ '@example_no' => $params['internshipform']['example_no'],
+ ]);
+ break;
+
+ case 'cheque_sent':
+ $user_data = User::load($params['cheque_sent']['user_id']);
+ $message['subject'] = t('[@site_name][Textbook Companion] We have received your feedback', [
+ '@site_name' => $site_name,
+ ]);
+ $message['body'][] = t('
+Dear @user_name,
We have Sent Cheque for the following book proposed
-Title of the Book: ' . $params['cheque_sent']['book_title'] . '
-Title of the Chapter: ' . $params['cheque_sent']['chapter_number'] . ' ' . $params['cheque_sent']['chapter_title'] . '
-Example No.: ' . $params['cheque_sent']['example_no'] . '
+Title of the Book: @book
+Title of the Chapter: @chapter_num @chapter_title
+Example No.: @example_no
Best Wishes,
-!site_name Team,
-FOSSEE,IIT Bombay', array(
- '!site_name' => variable_get('site_name', ''),
- '!user_name' => $user_data->name
- ))
- );
- break;
- case 'standard':
- // bcc to textbook_companion_emails
- //$message['headers'] += $tbc_bcc_emails;
- $message['headers'] = $params['standard']['headers'];
- $message['subject'] = $params['standard']['subject'];
- $message['body'] = $params['standard']['body'];
- break;
- } //$key
-}
-/* AJAX CALLS */
-function textbook_companion_ajax()
-{
- $query_type = arg(2);
- if ($query_type == 'chapter_title')
- {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if ($chapter_data = $chapter_q->fetchObject())
- {
- echo $chapter_data->name;
- return;
- } //$chapter_data = $chapter_q->fetchObject()
- } //$query_type == 'chapter_title'
- else if ($query_type == 'example_exists')
- {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- $example_number = arg(5);
- $chapter_id = 0;
- /* $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if (!$chapter_data = $chapter_q->fetchObject())
- {
- echo '';
- return;
- } //!$chapter_data = $chapter_q->fetchObject()
- else
- {
- $chapter_id = $chapter_data->id;
- }
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND number = '%s' LIMIT 1", $chapter_id, $example_number);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_id);
- $query->condition('number', $example_number);
- $query->range(0, 1);
- $example_q = $query->execute();
- if ($example_data = $example_q->fetchObject())
- {
- if ($example_data->approval_status == 1)
- echo 'Warning! Example already approved. You cannot upload the same example again.';
- else
- echo 'Warning! Example already uploaded. Delete the example and reupload it.';
- return;
- } //$example_data = $example_q->fetchObject()
- } //$query_type == 'example_exists'
- echo '';
-}
-/*************************** VALIDATION FUNCTIONS *****************************/
-function textbook_companion_check_valid_filename($file_name)
-{
- if (!preg_match('/^[0-9a-zA-Z\_\.]+$/', $file_name))
- return FALSE;
- else if (substr_count($file_name, ".") > 1)
- return FALSE;
- else
- return TRUE;
+@site_name Team,
+FOSSEE,IIT Bombay', [
+ '@site_name' => $site_name,
+ '@user_name' => $user_data ? $user_data->getDisplayName() : '',
+ '@book' => $params['cheque_sent']['book_title'],
+ '@chapter_num' => $params['cheque_sent']['chapter_number'],
+ '@chapter_title' => $params['cheque_sent']['chapter_title'],
+ '@example_no' => $params['cheque_sent']['example_no'],
+ ]);
+ break;
+
+ case 'failed_reminder':
+ $message['subject'] = t('Failed to upload the TBC codes on time');
+ $message['body'][] = t('Dear user,
+
+This is to inform you that you have failed to upload the TBC codes on time.
+Please note that the time you have taken is way past the deadline as well.
+Kindly upload the TBC codes on the interface within 5 days from now.
+Failure to submit the same will result in disapproval of your work and cancellation of your internship.
+
+Regards,
+DWSIM TBC Team,
+FOSSEE.');
+ break;
+
+ case 'standard':
+ $message['headers'] = $params['standard']['headers'] ?? [];
+ $message['subject'] = $params['standard']['subject'] ?? '';
+ $message['body'][] = $params['standard']['body'] ?? '';
+ break;
+ }
}
-function check_name($name = '')
-{
- if (!preg_match('/^[0-9a-zA-Z\ ]+$/', $name))
- return FALSE;
- else
- return TRUE;
+
+
+/**
+ * Removed: book_proposal_form / validate / submit.
+ * Active implementation: Drupal\textbook_companion\Form\TextbookCompanionProposalForm
+ */
+
+/**
+ * Form constructor for the non-AICTE book proposal form.
+ */
+function book_proposal_nonaicte_form($form_state) {
+ $user = \Drupal::currentUser();
+ $row1 = (object) [
+ 'book' => '',
+ 'author' => '',
+ 'isbn' => '',
+ 'publisher' => '',
+ 'edition' => '',
+ 'year' => ''
+ ];
+
+ $form = array();
+ $form['imp_notice'] = array(
+ '#type' => 'item',
+ '#markup' => 'Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion and also follow the additional guidelines. '
+ );
+ $form['guidelines'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Guidelines'),
+ '#attributes' => array(
+ 'style' => 'font-weight: bold'
+ ),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE
+ );
+ $form['guidelines']['book'] = array(
+ '#type' => 'item',
+ '#required' => TRUE,
+ '#markup' => '
+ All the fields are compulsory
+ Proof (example: syllabus) to the usage/ popularity of the textbook must be provided in the references box below
+ Please make sure that the book proposed by you has at least 80 examples which include numerical computations and which can be coded in DWSIM
+ If the book has less than 80 examples the honorarium will be provided on a pro-rata basis
+ Make sure the book you propose is not already an AICTE recommended book , completed book or a book in progress
+ You will be intimated about the approval or rejection of your suggestion via e-mail
+ '
+ );
+ $form['full_name'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Full Name'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE
+ );
+ $form['email_id'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Email'),
+ '#size' => 30,
+ '#value' => $user->getEmail(),
+ '#disabled' => TRUE
+ );
+ $form['mobile'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Mobile No.'),
+ '#size' => 30,
+ '#maxlength' => 15,
+ '#required' => TRUE
+ );
+ $form['gender'] = array(
+ '#type' => 'radios',
+ '#title' => t('Gender'),
+ '#options' => array(
+ 'M' => 'Male',
+ 'F' => 'Female'
+ ),
+ '#required' => TRUE
+ );
+ $form['how_project'] = array(
+ '#type' => 'select',
+ '#title' => t('How did you come to know about this project'),
+ '#options' => array(
+ 'DWSIM Website' => 'DWSIM Website',
+ 'Friend' => 'Friend',
+ 'Professor/Teacher' => 'Professor/Teacher',
+ 'Mailing List' => 'Mailing List',
+ 'Poster in my/other college' => 'Poster in my/other college',
+ 'Others' => 'Others'
+ ),
+ '#required' => TRUE
+ );
+ $form['course'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Course'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE
+ );
+ $form['department'] = array(
+ '#type' => 'select',
+ '#title' => t('Department/Branch'),
+ '#options' => _list_of_departments(),
+ '#required' => TRUE
+ );
+ $form['university'] = array(
+ '#type' => 'textfield',
+ '#title' => t('University/ Institute'),
+ '#size' => 80,
+ '#maxlength' => 200,
+ '#required' => TRUE,
+ '#attributes' => array(
+ 'placeholder' => 'Insert full name of your institute/ university.... '
+ )
+ );
+ $form['country'] = array(
+ '#type' => 'select',
+ '#title' => t('Country'),
+ '#options' => array(
+ 'India' => 'India',
+ 'Others' => 'Others'
+ ),
+ '#required' => TRUE
+ );
+ $form['other_country'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Other than India'),
+ '#size' => 100,
+ '#attributes' => array(
+ 'placeholder' => t('Enter your country name')
+ ),
+ '#states' => array(
+ 'visible' => array(
+ ':input[name="country"]' => array(
+ 'value' => 'Others'
+ )
+ )
+ )
+ );
+ $form['other_state'] = array(
+ '#type' => 'textfield',
+ '#title' => t('State other than India'),
+ '#size' => 100,
+ '#attributes' => array(
+ 'placeholder' => t('Enter your state/region name')
+ ),
+ '#states' => array(
+ 'visible' => array(
+ ':input[name="country"]' => array(
+ 'value' => 'Others'
+ )
+ )
+ )
+ );
+ $form['other_city'] = array(
+ '#type' => 'textfield',
+ '#title' => t('City other than India'),
+ '#size' => 100,
+ '#attributes' => array(
+ 'placeholder' => t('Enter your city name')
+ ),
+ '#states' => array(
+ 'visible' => array(
+ ':input[name="country"]' => array(
+ 'value' => 'Others'
+ )
+ )
+ )
+ );
+ $form['all_state'] = array(
+ '#type' => 'select',
+ '#title' => t('State'),
+ '#options' => _list_of_states(),
+ '#states' => array(
+ 'visible' => array(
+ ':input[name="country"]' => array(
+ 'value' => 'India'
+ )
+ )
+ )
+ );
+ $form['city'] = array(
+ '#type' => 'select',
+ '#title' => t('City'),
+ '#options' => _list_of_cities(),
+ '#states' => array(
+ 'visible' => array(
+ ':input[name="country"]' => array(
+ 'value' => 'India'
+ )
+ )
+ )
+ );
+ $form['pincode'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Pincode'),
+ '#size' => 30,
+ '#maxlength' => 6,
+ '#required' => False,
+ '#attributes' => array(
+ 'placeholder' => 'Enter pincode....'
+ )
+ );
+ $form['hr'] = array(
+ '#type' => 'item',
+ '#markup' => ' '
+ );
+ $form['faculty'] = array(
+ '#type' => 'hidden',
+ '#value' => 'None',
+ '#title' => t('College Teacher/Professor'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE
+ );
+ $form['faculty_email'] = array(
+ '#type' => 'hidden',
+ '#title' => t('Teacher/Professor Email Id'),
+ '#value' => 'None@email.com',
+ '#size' => 30,
+ '#maxlength' => 50
+ );
+ $form['reviewer'] = array(
+ '#type' => 'hidden',
+ '#value' => 'None',
+ '#title' => t('Reviewer'),
+ '#size' => 30,
+ '#maxlength' => 50
+ );
+ $form['version'] = array(
+ '#type' => 'select',
+ '#title' => t('Version'),
+ '#options' => _list_of_software_version(),
+ '#required' => TRUE
+ );
+ $form['older'] = array(
+ '#type' => 'textfield',
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#description' => t('Specify the Older version used')
+ );
+ $form['completion_date'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Expected Date of Completion'),
+ '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'),
+ '#size' => 10,
+ '#maxlength' => 10,
+ '#required' => TRUE
+ );
+ $form['operating_system'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Operating System'),
+ '#required' => TRUE,
+ '#size' => 30,
+ '#maxlength' => 50
+ );
+ $reason = array(
+ 'Used in more than one University' => t('Used in more than one University'),
+ 'The book has multiple editions' => t('The book has multiple editions'),
+ 'Extremely useful' => t('Extremely useful'),
+ 'Other reason' => t('Any other reason state below')
+ );
+ $form['reason'] = array(
+ '#type' => 'checkboxes',
+ '#title' => t('Reasons'),
+ '#options' => $reason,
+ '#required' => TRUE
+ );
+ $form['other_reason'] = array(
+ '#type' => 'textarea',
+ '#size' => 300,
+ '#maxlength' => 300
+ );
+ $form['proposal_type'] = array(
+ '#type' => 'hidden',
+ '#value' => '1',
+ '#required' => FALSE
+ );
+ $form['reference'] = array(
+ '#type' => 'textarea',
+ '#title' => t('Reference'),
+ '#required' => TRUE,
+ '#size' => 500,
+ '#maxlength' => 500,
+ '#attributes' => array(
+ 'placeholder' => 'Links of the syllabus must be provided....'
+ )
+ );
+ $form['preference1'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Book Preference'),
+ '#collapsible' => TRUE,
+ '#collapsed' => FALSE
+ );
+ $form['preference1']['book1'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Title of the book'),
+ '#size' => 30,
+ '#maxlength' => 100,
+ '#required' => TRUE,
+ '#value' => $row1->book,
+ '#disabled' => FALSE
+ );
+ $form['preference1']['author1'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Author Name'),
+ '#size' => 30,
+ '#maxlength' => 100,
+ '#required' => TRUE,
+ '#value' => $row1->author,
+ '#disabled' => FALSE
+ );
+ $form['preference1']['isbn1'] = array(
+ '#type' => 'textfield',
+ '#title' => t('ISBN No'),
+ '#size' => 30,
+ '#maxlength' => 25,
+ '#required' => TRUE,
+ '#value' => $row1->isbn,
+ '#disabled' => FALSE
+ );
+ $form['preference1']['publisher1'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Publisher & Place'),
+ '#size' => 30,
+ '#maxlength' => 50,
+ '#required' => TRUE,
+ '#value' => $row1->publisher
+ );
+ $form['preference1']['edition1'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Edition'),
+ '#size' => 4,
+ '#maxlength' => 2,
+ '#required' => TRUE,
+ '#value' => $row1->edition
+ );
+ $form['preference1']['year1'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Year of publication'),
+ '#size' => 4,
+ '#maxlength' => 4,
+ '#required' => TRUE,
+ '#value' => $row1->year
+ );
+ $form['submit'] = array(
+ '#type' => 'submit',
+ '#value' => t('Submit')
+ );
+ return $form;
}
-function check_chapter_number($name = '')
-{
- if (!preg_match('/^([0-9])+(\.([0-9a-zA-Z])+)+$/', $name))
- return FALSE;
- else
- return TRUE;
+
+/**
+ * Submit handler for book_proposal_nonaicte_form.
+ */
+function book_proposal_nonaicte_form_submit($form, &$form_state) {
+ $user = \Drupal::currentUser();
+ $uid = $user->id();
+ $tbc_to_emails = tc_variable_get('textbook_companion_emails_all', '');
+ if (!$uid) {
+ \Drupal::messenger()->addError(t('It is mandatory to login on this website to access the proposal form'));
+ return;
+ }
+
+ $date_parts = explode('-', tc_form_state_get_value($form_state, 'completion_date', ''));
+ $completion_date_timestamp = time();
+ if (count($date_parts) === 3) {
+ list($d, $m, $y) = $date_parts;
+ $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y);
+ }
+
+ $my_reason = '';
+ if (isset($_POST['reason'])) {
+ $my_reason = implode(", ", $_POST['reason']);
+ $other_reason = tc_form_state_get_value($form_state, 'other_reason');
+ if ($other_reason) {
+ $my_reason .= "-" . " " . $other_reason;
+ }
+ }
+
+ $dwsim_version = tc_form_state_get_value($form_state, 'version');
+ if ($dwsim_version == 'olderversion') {
+ $dwsim_version = tc_form_state_get_value($form_state, 'older');
+ }
+
+ $country = tc_form_state_get_value($form_state, 'country');
+ $state = tc_form_state_get_value($form_state, 'all_state');
+ if ($country == 'other') {
+ $country = trim(tc_form_state_get_value($form_state, 'other_country', ''));
+ $state = trim(tc_form_state_get_value($form_state, 'other_state', ''));
+ }
+
+ $fields = [
+ 'uid' => $uid,
+ 'approver_uid' => 0,
+ 'full_name' => trim(ucwords(strtolower(tc_form_state_get_value($form_state, 'full_name')))),
+ 'mobile' => trim(tc_form_state_get_value($form_state, 'mobile')),
+ 'gender' => tc_form_state_get_value($form_state, 'gender'),
+ 'how_project' => tc_form_state_get_value($form_state, 'how_project'),
+ 'course' => trim(tc_form_state_get_value($form_state, 'course')),
+ 'branch' => tc_form_state_get_value($form_state, 'branch'),
+ 'university' => trim(tc_form_state_get_value($form_state, 'university')),
+ 'city' => trim(tc_form_state_get_value($form_state, 'city')),
+ 'pincode' => tc_form_state_get_value($form_state, 'pincode'),
+ 'state' => trim($state),
+ 'country' => $country,
+ 'faculty' => ucwords(strtolower(tc_form_state_get_value($form_state, 'faculty', 'None'))),
+ 'reviewer' => "DWSIM TBC Team",
+ 'reference' => trim(tc_form_state_get_value($form_state, 'reference')),
+ 'completion_date' => $completion_date_timestamp,
+ 'creation_date' => time(),
+ 'approval_date' => 0,
+ 'proposal_status' => 0,
+ 'dwsim_version' => trim($dwsim_version),
+ 'operating_system' => trim(tc_form_state_get_value($form_state, 'operating_system')),
+ 'teacher_email' => tc_form_state_get_value($form_state, 'faculty_email'),
+ 'reason' => $my_reason,
+ 'samplefilepath' => "",
+ 'proposal_type' => 1,
+ 'proposed_completion_date' => $completion_date_timestamp
+ ];
+
+ $proposal_id = \Drupal::database()
+ ->insert('textbook_companion_proposal')
+ ->fields($fields)
+ ->execute();
+
+ if (!$proposal_id) {
+ \Drupal::messenger()->addError(t('Error receiving your proposal. Please try again.'));
+ return;
+ }
+
+ if (tc_form_state_get_value($form_state, 'book1')) {
+ $pref_fields = [
+ 'proposal_id' => $proposal_id,
+ 'pref_number' => 1,
+ 'book' => ucwords(strtolower(tc_form_state_get_value($form_state, 'book1'))),
+ 'author' => ucwords(strtolower(tc_form_state_get_value($form_state, 'author1'))),
+ 'isbn' => tc_form_state_get_value($form_state, 'isbn1'),
+ 'publisher' => ucwords(strtolower(tc_form_state_get_value($form_state, 'publisher1'))),
+ 'edition' => tc_form_state_get_value($form_state, 'edition1'),
+ 'year' => tc_form_state_get_value($form_state, 'year1'),
+ 'category' => 0,
+ 'approval_status' => 0,
+ 'nonaicte_book' => 1
+ ];
+
+ $pref_result = \Drupal::database()
+ ->insert('textbook_companion_preference')
+ ->fields($pref_fields)
+ ->execute();
+
+ if (!$pref_result) {
+ \Drupal::messenger()->addError(t('Error receiving your first book preference.'));
+ }
+ }
+
+ $email_to = $user->getEmail();
+ $params['proposal_received']['proposal_id'] = $proposal_id;
+ $params['proposal_received']['user_id'] = $uid;
+
+ \Drupal::service('textbook_companion.mail_service')->sendMail('textbook_companion', 'nonaicte_proposal_received', $email_to, $params);
+ if (!empty($tbc_to_emails)) {
+ \Drupal::service('textbook_companion.mail_service')->sendMail('textbook_companion', 'nonaicte_proposal_to_pi', $tbc_to_emails, $params);
+ }
+
+ \Drupal::messenger()->addMessage(t('We have received your book proposal. We will get back to you soon.'), 'status');
+
+ if ($form_state instanceof FormStateInterface) {
+ $form_state->setRedirect('');
+ }
}
-function textbook_companion_path()
-{
- return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_uploads/';
+
+/**
+ * Validates file names.
+ */
+function textbook_companion_check_valid_filename($file_name) {
+ if (!preg_match('/^[0-9a-zA-Z\_\.]+$/', $file_name)) {
+ return FALSE;
+ }
+ if (substr_count($file_name, ".") > 1) {
+ return FALSE;
+ }
+ return TRUE;
}
-function textbook_companion_temp_path()
-{
- return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/';
+
+/**
+ * Validates standard name string.
+ */
+function check_name($name = '') {
+ if (!preg_match('/^[0-9a-zA-Z\ ]+$/', $name)) {
+ return FALSE;
+ }
+ return TRUE;
}
-function textbook_companion_samplecode_path()
-{
- return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_sample_code/';
+
+/**
+ * Validates chapter numbers.
+ */
+function check_chapter_number($name = '') {
+ if (!preg_match('/^([0-9])+(\.([0-9a-zA-Z])+)+$/', $name)) {
+ return FALSE;
+ }
+ return TRUE;
}
-/****************************** DELETION FUNCTIONS ****************************/
-function delete_example($example_id)
-{
- global $user;
- $root_path = textbook_companion_path();
- $status = TRUE;
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id);
- $example_data = db_fetch_object($example_q);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('id', $example_id);
- $example_q = $query->execute();
- $example_data = $example_q->fetchObject();
- if (!$example_data)
- {
- drupal_set_message(t('Invalid example.'), 'error');
- return FALSE;
- } //!$example_data
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- $chapter_q = db_query("SELECT tcp.id as pref_id, tcp.directory_name, tcc.*
-FROM textbook_companion_preference tcp
-JOIN textbook_companion_chapter tcc
-ON tcp.id= tcc.preference_id
-WHERE tcc.id = :chapter_id", array(
- ":chapter_id" => $example_data->chapter_id
- ));
- /*$query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $example_data->chapter_id);
- $chapter_q = $query->execute();*/
- $chapter_data = $chapter_q->fetchObject();
- if (!$chapter_data)
- {
- drupal_set_message(t('Invalid example chapter.'), 'error');
- return FALSE;
- } //!$chapter_data
- /* deleting example files */
- /*$examples_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id);*/
- $query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('example_id', $example_id);
- $examples_files_q = $query->execute();
- while ($examples_files_data = $examples_files_q->fetchObject())
- {
- if (!file_exists($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath))
- {
- $status = FALSE;
- //var_dump($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath);
- die;
- drupal_set_message(t('Error deleting !file. File does not exists.', array(
- '!file' => $examples_files_data->filepath
- )), 'error');
- continue;
- } //!file_exists($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath)
- /* removing example file */
- if (!unlink($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath))
- {
- $status = FALSE;
- drupal_set_message(t('Error deleting !file', array(
- '!file' => $examples_files_data->filepath
- )), 'error');
- /* sending email to admins */
- $email_to = variable_get('textbook_companion_bcc_emails', '');
- $params['standard']['subject'] = "[ERROR] Error deleting example file";
- $params['standard']['body'] = "Error deleting example files by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " :
- example id : " . $example_id . "
- file id : " . $examples_files_data->id . "
- file path : " . $examples_files_data->filepath;
- if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- } //!unlink($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath)
- else
- {
- /* deleting example files database entries */
- /*db_query("DELETE FROM {textbook_companion_example_files} WHERE id = %d", $examples_files_data->id);*/
- $query = db_delete('textbook_companion_example_files');
- $query->condition('id', $examples_files_data->id);
- $num_deleted = $query->execute();
- }
- } //$examples_files_data = $examples_files_q->fetchObject()
- if (!$status)
- return FALSE;
- /* removing example folder */
- $ex_path = $chapter_data->directory_name . '/' . 'CH' . $chapter_data->number . '/' . 'EX' . $example_data->number;
- $dir_path = $root_path . $ex_path;
- if (is_dir($dir_path))
- {
- if (!rmdir($dir_path))
- {
- drupal_set_message(t('Error deleting folder !folder', array(
- '!folder' => $dir_path
- )), 'error');
- /* sending email to admins */
- $email_to = variable_get('textbook_companion_bcc_emails', '');
- $params['standard']['subject'] = "[ERROR] Error deleting folder";
- $params['standard']['body'] = "Error deleting folder " . $dir_path . " by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
- if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- return FALSE;
- } //!rmdir($dir_path)
- } //is_dir($dir_path)
- else
- {
- drupal_set_message(t('Cannot delete example folder. !folder does not exists.', array(
- '!folder' => $dir_path
- )), 'error');
- return FALSE;
- }
- /* deleting example dependency and exmaple database entries */
- /*db_query("DELETE FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_id);*/
- //$query = db_delete('textbook_companion_example_dependency');
- //$query->condition('example_id', $example_id);
- //$num_deleted = $query->execute();
- /*db_query("DELETE FROM {textbook_companion_example} WHERE id = %d", $example_id);*/
- $query = db_delete('textbook_companion_example');
- $query->condition('id', $example_id);
- $num_deleted = $query->execute();
- return $status;
+
+/**
+ * Helper paths.
+ */
+function textbook_companion_path() {
+ return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_uploads/';
}
-function delete_chapter($chapter_id)
-{
- $status = TRUE;
- $root_path = textbook_companion_path();
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id);
- $chapter_data = db_fetch_object($chapter_q);*/
- /*$query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('id', $chapter_id);
- $chapter_q = $query->execute();
- $chapter_data = $chapter_q->fetchObject();*/
- $chapter_q = db_query("SELECT tcp.id as pref_id, tcp.directory_name, tcc.*
-FROM textbook_companion_preference tcp
-JOIN textbook_companion_chapter tcc
-ON tcp.id= tcc.preference_id
-WHERE tcc.id = :chapter_id", array(
- ":chapter_id" => $chapter_id
- ));
- $chapter_data = $chapter_q->fetchObject();
- if (!$chapter_data)
- {
- drupal_set_message('Invalid chapter.', 'error');
- return FALSE;
- } //!$chapter_data
- /* deleting examples */
- /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d", $chapter_id);*/
- $query = db_select('textbook_companion_example');
- $query->fields('textbook_companion_example');
- $query->condition('chapter_id', $chapter_id);
- $example_q = $query->execute();
- while ($example_data = $example_q->fetchObject())
- {
- if (!delete_example($example_data->id))
- $status = FALSE;
- } //$example_data = $example_q->fetchObject()
- if ($status)
- {
- $dir_path = $root_path . $chapter_data->directory_name . '/CH' . $chapter_data->number;
- if (is_dir($dir_path))
- {
- $res = rmdir($dir_path);
- if (!$res)
- {
- drupal_set_message(t('Error deleting chapter folder !folder', array(
- '!folder' => $dir_path
- )), 'error');
- /* sending email to admins */
- $email_to = variable_get('textbook_companion_bcc_emails', '');
- $params['standard']['subject'] = "[ERROR] Error deleting folder";
- $params['standard']['body'] = "Error deleting folder " . $dir_path;
- if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- return FALSE;
- } //!$res
- else
- {
- /* deleting chapter details from database */
- /*db_query("DELETE FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id);*/
- $query = db_delete('textbook_companion_chapter');
- $query->condition('id', $chapter_id);
- $num_deleted = $query->execute();
- return TRUE;
- }
- } //is_dir($dir_path)
- else
- {
- drupal_set_message(t('Cannot delete chapter folder. !folder does not exists.', array(
- '!folder' => $dir_path
- )), 'error');
- return FALSE;
- }
- } //$status
- return FALSE;
+
+function textbook_companion_temp_path() {
+ return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/';
}
-function delete_book($book_id)
-{
- $status = TRUE;
- $root_path = textbook_companion_path();
- /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id);
- $preference_data = db_fetch_object($preference_q);*/
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('id', $book_id);
- $preference_q = $query->execute();
- $preference_data = $preference_q->fetchObject();
- if (!$preference_data)
- {
- drupal_set_message('Invalid book.', 'error');
- return FALSE;
- } //!$preference_data
- /* delete chapters */
- /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $preference_data->id);*/
- $query = db_select('textbook_companion_chapter');
- $query->fields('textbook_companion_chapter');
- $query->condition('preference_id', $preference_data->id);
- $chapter_q = $query->execute();
- while ($chapter_data = $chapter_q->fetchObject())
- {
- if (!delete_chapter($chapter_data->id))
- {
- $status = FALSE;
- } //!delete_chapter($chapter_data->id)
- } //$chapter_data = $chapter_q->fetchObject()
- return $status;
+
+function textbook_companion_samplecode_path() {
+ return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_sample_code/';
}
-function delete_file($file_id)
-{
- $root_path = textbook_companion_path();
- /*$file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d LIMIT 1", $file_id);*/
- $file_q = db_query("SELECT * FROM textbook_companion_preference tcp JOIN textbook_companion_chapter tcc ON tcp.id = tcc.preference_id JOIN textbook_companion_example tce ON tcc.id=tce.chapter_id JOIN textbook_companion_example_files tcef on tce.id = tcef.example_id WHERE tcef.id = :example_id", array(
- ':example_id' => $file_id
- ));
- /*$query = db_select('textbook_companion_example_files');
- $query->fields('textbook_companion_example_files');
- $query->condition('id', $file_id);
- $query->range(0, 1);
- $file_q = $query->execute();*/
- $file_data = $file_q->fetchObject();
- if (!$file_data)
- {
- drupal_set_message('Invalid file specified.', 'error');
- return FALSE;
- } //!$file_data
- if (!file_exists($root_path . $file_data->directory_name . '/' . $file_data->filepath))
- {
- drupal_set_message(t('Error deleting !file. File does not exists.', array(
- '!file' => $file_data->filepath
- )), 'error');
- return FALSE;
- } //!file_exists($root_path . $file_data->directory_name . '/' . $file_data->filepath)
- /* removing example file */
- if (!unlink($root_path . $file_data->directory_name . '/' . $file_data->filepath))
- {
- drupal_set_message(t('Error deleting !file', array(
- '!file' => $file_data->filepath
- )), 'error');
- /* sending email to admins */
- $email_to = variable_get('textbook_companion_bcc_emails', '');
- $params['standard']['subject'] = "[ERROR] Error deleting file";
- $params['standard']['body'] = "Error deleting file by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " :
- file id : " . $file_id . "
- file path : " . $file_data->directory_name . '/' . $file_data->filepath;
- if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- return FALSE;
- } //!unlink($root_path . $file_data->directory_name . '/' . $file_data->filepath)
- else
- {
- /* deleting example files database entries */
- /*db_query("DELETE FROM {textbook_companion_example_files} WHERE id = %d", $file_id);*/
- $query = db_delete('textbook_companion_example_files');
- $query->condition('id', $file_id);
- $num_deleted = $query->execute();
- return TRUE;
- }
+
+/**
+ * Format string names by capitalising.
+ */
+function tc_ucname($string) {
+ $string = ucwords(strtolower($string));
+ foreach (array('-', '\'') as $delimiter) {
+ if (strpos($string, $delimiter) !== false) {
+ $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
+ }
+ }
+ return $string;
}
-//Non aicte book proposal form
-function book_proposal_nonaicte_form($form_state)
-{
- global $user;
- $form = array();
- $form['imp_notice'] = array(
- '#type' => 'item',
- '#markup' => 'Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion and also follow the additional guidelines. '
- );
- $form['guidelines'] = array(
- '#type' => 'fieldset',
- '#title' => t('Guidelines'),
- '#attributes' => array(
- 'style' => 'font-weight: bold'
- ),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE
- );
- $form['guidelines']['book'] = array(
- '#type' => 'item',
- '#required' => TRUE,
- '#markup' => '
- All the fields are compulsory
- Proof (example: syllabus) to the usage/ popularity of the textbook must be provided in the references box below
- Please make sure that the book proposed by you has at least 80 examples which include numerical computations and which can be coded in DWSIM
- If the book has less than 80 examples the honorarium will be provided on a pro-rata basis
- Make sure the book you propose is not already an AICTE recommended book , completed book
- or a book in progress
- You will be intimated about the approval or rejection of your suggestion via e-mail
- '
- );
- $form['full_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Full Name'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- );
- $form['email_id'] = array(
- '#type' => 'textfield',
- '#title' => t('Email'),
- '#size' => 30,
- '#value' => $user->mail,
- '#disabled' => TRUE
- );
- $form['mobile'] = array(
- '#type' => 'textfield',
- '#title' => t('Mobile No.'),
- '#size' => 30,
- '#maxlength' => 15,
- '#required' => TRUE
- );
- $form['gender'] = array(
- '#type' => 'radios',
- '#title' => t('Gender'),
- '#options' => array(
- 'M' => 'Male',
- 'F' => 'Female'
- ),
- '#required' => TRUE
- );
- $form['how_project'] = array(
- '#type' => 'select',
- '#title' => t('How did you come to know about this project'),
- '#options' => array(
- 'DWSIM Website' => 'DWSIM Website',
- 'Friend' => 'Friend',
- 'Professor/Teacher' => 'Professor/Teacher',
- 'Mailing List' => 'Mailing List',
- 'Poster in my/other college' => 'Poster in my/other college',
- 'Others' => 'Others'
- ),
- '#required' => TRUE
- );
- $form['course'] = array(
- '#type' => 'textfield',
- '#title' => t('Course'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- );
- $form['department'] = array(
- '#type' => 'select',
- '#title' => t('Department/Branch'),
- '#options' => _list_of_departments(),
- '#required' => TRUE
- );
- $form['university'] = array(
- '#type' => 'textfield',
- '#title' => t('University/ Institute'),
- '#size' => 80,
- '#maxlength' => 200,
- '#required' => TRUE,
- '#attributes' => array(
- 'placeholder' => 'Insert full name of your institute/ university.... '
- )
- );
- $form['country'] = array(
- '#type' => 'select',
- '#title' => t('Country'),
- '#options' => array(
- 'India' => 'India',
- 'Others' => 'Others'
- ),
- '#required' => TRUE
- //'#tree' => TRUE,
- // '#validated' => TRUE,
- );
- $form['other_country'] = array(
- '#type' => 'textfield',
- '#title' => t('Other than India'),
- '#size' => 100,
- '#attributes' => array(
- 'placeholder' => t('Enter your country name')
- ),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'Others'
- )
- )
- )
- );
- $form['other_state'] = array(
- '#type' => 'textfield',
- '#title' => t('State other than India'),
- '#size' => 100,
- '#attributes' => array(
- 'placeholder' => t('Enter your state/region name')
- ),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'Others'
- )
- )
- )
- );
- $form['other_city'] = array(
- '#type' => 'textfield',
- '#title' => t('City other than India'),
- '#size' => 100,
- '#attributes' => array(
- 'placeholder' => t('Enter your city name')
- ),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'Others'
- )
- )
- )
- );
- $form['all_state'] = array(
- '#type' => 'select',
- '#title' => t('State'),
- '#options' => _list_of_states(),
- '#validated' => TRUE,
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'India'
- )
- )
- )
- );
- $form['city'] = array(
- '#type' => 'select',
- '#title' => t('City'),
- '#options' => _list_of_cities(),
- '#states' => array(
- 'visible' => array(
- ':input[name="country"]' => array(
- 'value' => 'India'
- )
- )
- )
- );
- $form['pincode'] = array(
- '#type' => 'textfield',
- '#title' => t('Pincode'),
- '#size' => 30,
- '#maxlength' => 6,
- '#required' => False,
- '#attributes' => array(
- 'placeholder' => 'Enter pincode....'
- )
- );
- /***************************************************************************/
- $form['hr'] = array(
- '#type' => 'item',
- '#markup' => ' '
- );
- $form['faculty'] = array(
- '#type' => 'hidden',
- '#value' => 'None',
- '#title' => t('College Teacher/Professor'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE
- );
- $form['faculty_email'] = array(
- '#type' => 'hidden',
- '#value' => 'None',
- '#title' => t('Teacher/Professor Email Id'),
- '#value' => '@email.com',
- '#size' => 30,
- '#maxlength' => 50
- );
- $form['reviewer'] = array(
- '#type' => 'hidden',
- '#value' => 'None',
- '#title' => t('Reviewer'),
- '#size' => 30,
- '#maxlength' => 50
- );
- $form['version'] = array(
- '#type' => 'hidden',
- '#default_value' => 'Not available'
- );
- $form['version'] = array(
- '#type' => 'select',
- '#title' => t('Version'),
- '#options' => _list_of_software_version(),
- '#required' => TRUE
- );
- $form['older'] = array(
- '#type' => 'textfield',
- '#size' => 30,
- '#maxlength' => 50,
- //'#required' => TRUE,
- '#description' => t('Specify the Older version used')
- );
- $form['completion_date'] = array(
- '#type' => 'textfield',
- '#title' => t('Expected Date of Completion'),
- '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'),
- '#size' => 10,
- '#maxlength' => 10,
- '#required' => TRUE
- );
- $form['operating_system'] = array(
- '#type' => 'textfield',
- '#title' => t('Operating System'),
- '#required' => TRUE,
- '#size' => 30,
- '#maxlength' => 50
- );
- $reason = array(
- 'Used in more than one University' => t('Used in more than one University'),
- 'The book has multiple editions' => t('The book has multiple editions'),
- 'Extremely useful' => t('Extremely useful'),
- 'Other reason' => t('Any other reason state below')
- );
- $form['reason'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Reasons'),
- '#options' => $reason,
- '#required' => TRUE
- );
- $form['other_reason'] = array(
- '#type' => 'textarea',
- '#size' => 300,
- '#maxlength' => 300
- //'#required' => FALSE,
- );
- $form['proposal_type'] = array(
- '#type' => 'hidden',
- '#value' => '1',
- '#required' => FALSE
- );
- $form['reference'] = array(
- '#type' => 'textarea',
- '#title' => t('Reference'),
- '#required' => TRUE,
- '#size' => 500,
- '#maxlength' => 500,
- '#attributes' => array(
- 'placeholder' => 'Links of the syllabus must be provided....'
- )
- );
- $form['preference1'] = array(
- '#type' => 'fieldset',
- '#title' => t('Book Preference'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE
- );
- $form['preference1']['book1'] = array(
- '#type' => 'textfield',
- '#title' => t('Title of the book'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#value' => $row1->book,
- '#disabled' => ($row1->book ? TRUE : FALSE)
- );
- $form['preference1']['author1'] = array(
- '#type' => 'textfield',
- '#title' => t('Author Name'),
- '#size' => 30,
- '#maxlength' => 100,
- '#required' => TRUE,
- '#value' => $row1->author,
- '#disabled' => ($row1->author ? TRUE : FALSE)
- );
- $form['preference1']['isbn1'] = array(
- '#type' => 'textfield',
- '#title' => t('ISBN No'),
- '#size' => 30,
- '#maxlength' => 25,
- '#required' => TRUE,
- '#value' => $row1->isbn,
- '#disabled' => ($row1->isbn ? TRUE : FALSE)
- );
- $form['preference1']['publisher1'] = array(
- '#type' => 'textfield',
- '#title' => t('Publisher & Place'),
- '#size' => 30,
- '#maxlength' => 50,
- '#required' => TRUE,
- '#value' => $row1->publisher
- );
- $form['preference1']['edition1'] = array(
- '#type' => 'textfield',
- '#title' => t('Edition'),
- '#size' => 4,
- '#maxlength' => 2,
- '#required' => TRUE,
- '#value' => $row1->edition
- );
- $form['preference1']['year1'] = array(
- '#type' => 'textfield',
- '#title' => t('Year of publication'),
- '#size' => 4,
- '#maxlength' => 4,
- '#required' => TRUE,
- '#value' => $row1->year
- );
- /*$form['termconditions'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Terms And Conditions'),
- '#options' => array(
- 'status' => t('I agree to the Terms and Conditions '),),
- '#required' => TRUE,
- );*/
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit')
- );
- /* #value fix for #default_value bug drupal6
- foreach(array("preference1") as $preference) {
- foreach($form[$preference] as $key => $value) {
- if(!$form[$preference][$key]["#value"]) {
- unset($form[$preference][$key]["#value"]);
- }
- }
- }*/
- return $form;
+/**
+ * Builds the unique directory name for books.
+ */
+function _dir_name($book, $author, $pref_id, $form_state = NULL) {
+ $book_title = tc_ucname($book);
+ $author = tc_ucname($author);
+ $dir_name = $book_title . " by " . $author;
+ $directory_name = str_replace("__", "_", str_replace(" ", "_", $dir_name));
+
+ if (!$pref_id) {
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('directory_name', $directory_name);
+ $query->condition('approval_status', 1);
+ $result = $query->execute()->rowCount();
+ if ($result > 0) {
+ tc_form_set_error('', t('Book is already allotted. Please try another book or contact to administrator'), $form_state);
+ return;
+ }
+ } else {
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('directory_name', $directory_name);
+ $query->condition('id', $pref_id);
+ $result = $query->execute()->rowCount();
+ if ($result > 1) {
+ tc_form_set_error('', t('Book is already present. Please try another book or contact to administrator'), $form_state);
+ return;
+ }
+ }
+ return $directory_name;
}
-function book_proposal_nonaicte_form_submit($form, &$form_state)
-{
- global $user;
- $selections = variable_get("aicte_" . $user->uid, "");
- $tbc_to_emails = variable_get("textbook_companion_emails_all");
- if (!$user->uid)
- {
- drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error');
- return;
- } //!$user->uid
- /* completion date to timestamp */
- list($d, $m, $y) = explode('-', $form_state['values']['completion_date']);
- $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y);
- /* Reasons for suggesting a book*/
- if (isset($_POST['reason']))
- {
- if (!($form_state['values']['other_reason']))
- {
- $my_reason = implode(", ", $_POST['reason']);
- } //!($form_state['values']['other_reason'])
- else
- {
- $my_reason = implode(", ", $_POST['reason']);
- $my_reason = $my_reason . "-" . " " . $form_state['values']['other_reason'];
- }
- $form_state['values']['other_reason'] = $my_reason;
- } //isset($_POST['reason'])
- /************************************/
- $dwsim_version = $form_state['values']['version'];
- if ($form_state['values']['version'] == 'olderversion')
- {
- $dwsim_version = $form_state['values']['older'];
- } //$form_state['values']['version'] == 'olderversion'
- $form_state['values']['version'] = $dwsim_version;
- //var_dump($form_state['values']);
- /*$query = "INSERT INTO {textbook_companion_proposal}
- (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university, faculty, reviewer, reference, completion_date, creation_date, approval_date, proposal_status, scilab_version, operating_system, teacher_email, proposal_type, reason ) VALUES (".$user->uid.", 0, '".ucwords(strtolower($form_state['values']['full_name']))."', '".$form_state['values']['mobile']."', '".$form_state['values']['gender']."', '".$form_state['values']['how_project']."', '".$form_state['values']['course']."', '".$form_state['values']['branch']."', '".$form_state['values']['university']."', '".ucwords(strtolower($form_state['values']['faculty']))."', '".ucwords(strtolower($form_state['values']['reviewer']))."', '".strtolower($form_state['values']['reference'])."', '".$completion_date_timestamp."', '".time()."', 0, 0, '".$scilab_version."', '".$form_state['values']['operating_system']."', '".$form_state['values']['faculty_email']."','".$form_state['values']['proposal_type']."','".$my_reason."')";*/
- $query = "INSERT INTO {textbook_companion_proposal}
- (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university,city,pincode,state,faculty, reviewer, reference, completion_date, creation_date,approval_date, proposal_status, version, operating_system, teacher_email, proposal_type, reason ) VALUES (:uid, :approver_uid, :full_name, :mobile, :gender, :how_project, :course, :branch, :university,:city,:pincode,:state, :faculty, :reviewer, :reference,
-:expected_completion_date, :actual_completion_date,:creation_date,:message, :approval_date, :proposal_status, :dwsim_version, :operating_system, :teacher_email,
-:proposal_type, :reason)";
- $args = array(
- "uid" => $user->uid,
- "approver_uid" => 0,
- "full_name" => ucwords(strtolower($form_state['values']['full_name'])),
- "mobile" => $form_state['values']['mobile'],
- "gender" => $form_state['values']['gender'],
- "how_project" => $form_state['values']['how_project'],
- "course" => $form_state['values']['course'],
- "branch" => $form_state['values']['branch'],
- "university" => $form_state['values']['university'],
- ":city" => $form_state['values']['city'],
- ":pincode" => $form_state['values']['pincode'],
- ":state" => $form_state['values']['all_state'],
- "faculty" => ucwords(strtolower($form_state['values']['faculty'])),
- "reviewer" => ucwords(strtolower($form_state['values']['reviewer'])),
- "reference" => strtolower($form_state['values']['reference']),
- "completion_date" => $completion_date_timestamp,
- "creation_date" => time(),
- "approval_date" => time(),
- "proposal_status" => 0,
- "dwsim_version" => $dwsim_version,
- "operating_system" => $form_state['values']['operating_system'],
- "teacher_email" => $form_state['values']['faculty_email'],
- "proposal_type" => $form_state['values']['proposal_type'],
- "reason" => $my_reason
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- if (!$result)
- {
- drupal_set_message(t('Error receiving your proposal. Please try again.'), 'error');
- return;
- } //!$result
- /* proposal id */
- $proposal_id = db_last_insert_id('textbook_companion_proposal', 'id');
- /* inserting first book preference */
- if ($form_state['values']['book1'])
- {
- /*$result = db_query("INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, nonaicte_book) VALUES
- (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d)",
- $proposal_id,
- 1,
- ucwords(strtolower($form_state['values']['book1'])),
- ucwords(strtolower($form_state['values']['author1'])),
- $form_state['values']['isbn1'],
- ucwords(strtolower($form_state['values']['publisher1'])),
- $form_state['values']['edition1'],
- $form_state['values']['year1'],
- 0,
- 0,
- 1
- );*/
- $query = "INSERT INTO {textbook_companion_preference}
- (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, nonaicte_book) VALUES
- (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :nonaicte_book)";
- $args = array(
- ":proposal_id" => $proposal_id,
- ":pref_number" => 1,
- ":book" => ucwords(strtolower($form_state['values']['book1'])),
- ":author" => ucwords(strtolower($form_state['values']['author1'])),
- ":isbn" => $form_state['values']['isbn1'],
- ":publisher" => ucwords(strtolower($form_state['values']['publisher1'])),
- ":edition" => $form_state['values']['edition1'],
- ":year" => $form_state['values']['year1'],
- ":category" => 0,
- ":approval_status" => 0,
- ":nonaicte_book" => 1
- );
- $result = db_query($query, $args, array(
- 'return' => Database::RETURN_INSERT_ID
- ));
- if (!$result)
- {
- drupal_set_message(t('Error receiving your first book preference.'), 'error');
- } //!$result
- } //$form_state['values']['book1']
- /* sending email */
- $email_to = $user->mail;
- $params['proposal_received']['proposal_id'] = $proposal_id;
- $params['proposal_received']['user_id'] = $user->uid;
- if (!drupal_mail('textbook_companion', 'nonaicte_proposal_received', $email_to, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- if (!drupal_mail('textbook_companion', 'nonaicte_proposal_to_pi', $tbc_to_emails, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE))
- drupal_set_message('Error sending email message.', 'error');
- drupal_set_message(t('We have received your book proposal. We will get back to you soon.'), 'status');
- drupal_goto('');
+
+/**
+ * Deletes an example from database and filesystem.
+ */
+function delete_example($example_id) {
+ $root_path = textbook_companion_path();
+ $status = TRUE;
+
+ $query = \Drupal::database()->select('textbook_companion_example');
+ $query->fields('textbook_companion_example');
+ $query->condition('id', $example_id);
+ $example_q = $query->execute();
+ $example_data = $example_q->fetchObject();
+
+ if (!$example_data) {
+ \Drupal::messenger()->addError(t('Invalid example.'));
+ return FALSE;
+ }
+
+ $chapter_q = \Drupal::database()->query("SELECT tcp.id as pref_id, tcp.directory_name, tcc.*
+ FROM {textbook_companion_preference} tcp
+ JOIN {textbook_companion_chapter} tcc ON tcp.id = tcc.preference_id
+ WHERE tcc.id = :chapter_id", [
+ ':chapter_id' => $example_data->chapter_id
+ ]);
+ $chapter_data = $chapter_q->fetchObject();
+
+ if (!$chapter_data) {
+ \Drupal::messenger()->addError(t('Invalid example chapter.'));
+ return FALSE;
+ }
+
+ $query = \Drupal::database()->select('textbook_companion_example_files');
+ $query->fields('textbook_companion_example_files');
+ $query->condition('example_id', $example_id);
+ $examples_files_q = $query->execute();
+
+ while ($examples_files_data = $examples_files_q->fetchObject()) {
+ $file_full_path = $root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath;
+ if (!file_exists($file_full_path)) {
+ $status = FALSE;
+ continue;
+ }
+
+ if (!unlink($file_full_path)) {
+ $status = FALSE;
+ \Drupal::messenger()->addError(t('Error deleting @file', ['@file' => $examples_files_data->filepath]));
+ $email_to = tc_variable_get('textbook_companion_bcc_emails', '');
+ $subject = "[ERROR] Error deleting example file";
+ $body = "Error deleting example files by " . \Drupal::currentUser()->id() . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " :\n" .
+ "example id : " . $example_id . "\n" .
+ "file id : " . $examples_files_data->id . "\n" .
+ "file path : " . $examples_files_data->filepath;
+
+ \Drupal::service('textbook_companion.mail_service')->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ $subject,
+ $body
+ );
+ } else {
+ \Drupal::database()->delete('textbook_companion_example_files')
+ ->condition('id', $examples_files_data->id)
+ ->execute();
+ }
+ }
+
+ if (!$status) {
+ return FALSE;
+ }
+
+ $ex_path = $chapter_data->directory_name . '/CH' . $chapter_data->number . '/EX' . $example_data->number;
+ $dir_path = $root_path . $ex_path;
+ if (is_dir($dir_path)) {
+ if (!rmdir($dir_path)) {
+ \Drupal::messenger()->addError(t('Error deleting folder @folder', ['@folder' => $dir_path]));
+ $email_to = tc_variable_get('textbook_companion_bcc_emails', '');
+ $subject = "[ERROR] Error deleting folder";
+ $body = "Error deleting folder " . $dir_path . " by " . \Drupal::currentUser()->id() . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
+
+ \Drupal::service('textbook_companion.mail_service')->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ $subject,
+ $body
+ );
+ return FALSE;
+ }
+ } else {
+ \Drupal::messenger()->addError(t('Cannot delete example folder. @folder does not exist.', ['@folder' => $dir_path]));
+ return FALSE;
+ }
+
+ \Drupal::database()->delete('textbook_companion_example')
+ ->condition('id', $example_id)
+ ->execute();
+
+ return $status;
}
-//
-function del_book_pdf($book_id)
-{
- $root_path = textbook_companion_path();
- $dir_path = $root_path . "latex/";
- $pdf_filename = "book_" . $book_id . ".pdf";
- if (file_exists($dir_path . $pdf_filename))
- unlink($dir_path . $pdf_filename);
+
+/**
+ * Deletes a chapter from database and filesystem.
+ */
+function delete_chapter($chapter_id) {
+ $status = TRUE;
+ $root_path = textbook_companion_path();
+
+ $chapter_q = \Drupal::database()->query("SELECT tcp.id as pref_id, tcp.directory_name, tcc.*
+ FROM {textbook_companion_preference} tcp
+ JOIN {textbook_companion_chapter} tcc ON tcp.id = tcc.preference_id
+ WHERE tcc.id = :chapter_id", [
+ ':chapter_id' => $chapter_id
+ ]);
+ $chapter_data = $chapter_q->fetchObject();
+
+ if (!$chapter_data) {
+ \Drupal::messenger()->addError(t('Invalid chapter.'));
+ return FALSE;
+ }
+
+ $query = \Drupal::database()->select('textbook_companion_example');
+ $query->fields('textbook_companion_example');
+ $query->condition('chapter_id', $chapter_id);
+ $example_q = $query->execute();
+
+ while ($example_data = $example_q->fetchObject()) {
+ if (!delete_example($example_data->id)) {
+ $status = FALSE;
+ }
+ }
+
+ if ($status) {
+ $dir_path = $root_path . $chapter_data->directory_name . '/CH' . $chapter_data->number;
+ if (is_dir($dir_path)) {
+ $res = rmdir($dir_path);
+ if (!$res) {
+ \Drupal::messenger()->addError(t('Error deleting chapter folder @folder', ['@folder' => $dir_path]));
+ $email_to = tc_variable_get('textbook_companion_bcc_emails', '');
+ $subject = "[ERROR] Error deleting folder";
+ $body = "Error deleting folder " . $dir_path;
+
+ \Drupal::service('textbook_companion.mail_service')->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ $subject,
+ $body
+ );
+ return FALSE;
+ } else {
+ \Drupal::database()->delete('textbook_companion_chapter')
+ ->condition('id', $chapter_id)
+ ->execute();
+ return TRUE;
+ }
+ } else {
+ \Drupal::messenger()->addError(t('Cannot delete chapter folder. @folder does not exist.', ['@folder' => $dir_path]));
+ return FALSE;
+ }
+ }
+ return FALSE;
}
-function _list_of_software_version()
-{
- $software_version = array();
- $query = db_select('dwsim_software_version');
- $query->fields('dwsim_software_version');
- $query->orderBy('dwsim_version', 'ASC');
- $software_version_list = $query->execute();
- while ($software_version_list_data = $software_version_list->fetchObject())
- {
- $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
- } //$software_version_list_data = $software_version_list->fetchObject()
- return $software_version;
+
+/**
+ * Deletes a book from database and filesystem.
+ */
+function delete_book($book_id) {
+ $status = TRUE;
+
+ $query = \Drupal::database()->select('textbook_companion_preference');
+ $query->fields('textbook_companion_preference');
+ $query->condition('id', $book_id);
+ $preference_q = $query->execute();
+ $preference_data = $preference_q->fetchObject();
+
+ if (!$preference_data) {
+ \Drupal::messenger()->addError(t('Invalid book.'));
+ return FALSE;
+ }
+
+ $query = \Drupal::database()->select('textbook_companion_chapter');
+ $query->fields('textbook_companion_chapter');
+ $query->condition('preference_id', $preference_data->id);
+ $chapter_q = $query->execute();
+
+ while ($chapter_data = $chapter_q->fetchObject()) {
+ if (!delete_chapter($chapter_data->id)) {
+ $status = FALSE;
+ }
+ }
+ return $status;
}
-function _list_of_departments()
-{
- $department = array();
- $query = db_select('list_of_departments');
- $query->fields('list_of_departments');
- $query->orderBy('id', 'DESC');
- $department_list = $query->execute();
- while ($department_list_data = $department_list->fetchObject())
- {
- $department[$department_list_data->department] = $department_list_data->department;
- } //$department_list_data = $department_list->fetchObject()
- return $department;
+
+/**
+ * Deletes a single uploaded file.
+ */
+function delete_file($file_id) {
+ $root_path = textbook_companion_path();
+
+ $file_q = \Drupal::database()->query("SELECT tcp.directory_name, tcef.filepath FROM {textbook_companion_preference} tcp JOIN {textbook_companion_chapter} tcc ON tcp.id = tcc.preference_id JOIN {textbook_companion_example} tce ON tcc.id=tce.chapter_id JOIN {textbook_companion_example_files} tcef on tce.id = tcef.example_id WHERE tcef.id = :file_id", [
+ ':file_id' => $file_id
+ ]);
+ $file_data = $file_q->fetchObject();
+
+ if (!$file_data) {
+ \Drupal::messenger()->addError(t('Invalid file specified.'));
+ return FALSE;
+ }
+
+ $file_full_path = $root_path . $file_data->directory_name . '/' . $file_data->filepath;
+ if (!file_exists($file_full_path)) {
+ \Drupal::messenger()->addError(t('Error deleting @file. File does not exist.', ['@file' => $file_data->filepath]));
+ return FALSE;
+ }
+
+ if (!unlink($file_full_path)) {
+ \Drupal::messenger()->addError(t('Error deleting @file', ['@file' => $file_data->filepath]));
+ $email_to = tc_variable_get('textbook_companion_bcc_emails', '');
+ $subject = "[ERROR] Error deleting file";
+ $body = "Error deleting file by " . \Drupal::currentUser()->id() . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " :\n" .
+ "file id : " . $file_id . "\n" .
+ "file path : " . $file_data->directory_name . '/' . $file_data->filepath;
+
+ \Drupal::service('textbook_companion.mail_service')->sendNotification(
+ 'textbook_companion',
+ 'standard',
+ $email_to,
+ $subject,
+ $body
+ );
+ return FALSE;
+ } else {
+ \Drupal::database()->delete('textbook_companion_example_files')
+ ->condition('id', $file_id)
+ ->execute();
+ return TRUE;
+ }
}
-function _list_of_states()
-{
- $states = array(
- '' => '-select-'
- );
- $query = db_select('list_states_of_india');
- $query->fields('list_states_of_india');
- //$query->orderBy('', '');
- $states_list = $query->execute();
- while ($states_list_data = $states_list->fetchObject())
- {
- $states[$states_list_data->state] = $states_list_data->state;
- } //$states_list_data = $states_list->fetchObject()
- return $states;
+
+/**
+ * Deletes generated book pdf.
+ */
+function del_book_pdf($book_id) {
+ $root_path = textbook_companion_path();
+ $dir_path = $root_path . "latex/";
+ $pdf_filename = "book_" . $book_id . ".pdf";
+ if (file_exists($dir_path . $pdf_filename)) {
+ unlink($dir_path . $pdf_filename);
+ }
}
-function _list_of_cities()
-{
- $city = array(
- '' => '-select-'
- );
- $query = db_select('list_cities_of_india');
- $query->fields('list_cities_of_india');
- $query->orderBy('city', 'ASC');
- $city_list = $query->execute();
- while ($city_list_data = $city_list->fetchObject())
- {
- $city[$city_list_data->city] = $city_list_data->city;
- } //$city_list_data = $city_list->fetchObject()
- return $city;
+
+/**
+ * Returns lists of software versions.
+ */
+function _list_of_software_version() {
+ $software_version = array();
+ $query = \Drupal::database()->select('dwsim_software_version');
+ $query->fields('dwsim_software_version');
+ $query->orderBy('dwsim_version', 'ASC');
+ $software_version_list = $query->execute();
+ while ($software_version_list_data = $software_version_list->fetchObject()) {
+ $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
+ }
+ return $software_version;
}
-/*************************************************************************/
-/***** Function To convert only first charater of string in uppercase ****/
-/*************************************************************************/
-/*function ucname($string) {
-$string =ucwords(strtolower($string));
-
-foreach (array('-', '\'') as $delimiter) {
-if (strpos($string, $delimiter)!==false) {
-$string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
+
+/**
+ * Returns lists of departments.
+ */
+function _list_of_departments() {
+ $department = array();
+ $query = \Drupal::database()->select('list_of_departments');
+ $query->fields('list_of_departments');
+ $query->orderBy('id', 'DESC');
+ $department_list = $query->execute();
+ while ($department_list_data = $department_list->fetchObject()) {
+ $department[$department_list_data->department] = $department_list_data->department;
+ }
+ return $department;
}
+
+/**
+ * Returns list of states.
+ */
+function _list_of_states() {
+ $states = array('' => '-select-');
+ $query = \Drupal::database()->select('list_states_of_india');
+ $query->fields('list_states_of_india');
+ $states_list = $query->execute();
+ while ($states_list_data = $states_list->fetchObject()) {
+ $states[$states_list_data->state] = $states_list_data->state;
+ }
+ return $states;
}
-return $string;
-}*/
-function _dir_name($book, $author, $pref_id)
-{
- if (!$pref_id)
- {
- $book_title = ucname($book);
- $author = ucname($author);
- $dir_name = $book_title . " " . "by" . " " . $author;
- $directory_name = str_replace("__", "_", str_replace(" ", "_", $dir_name));
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('directory_name', $directory_name);
- $query->condition('approval_status', 1);
- $result = $query->execute()->rowCount();
- if ($result > 0)
- {
- //var_dump('this');die;
- form_set_error('', t('Book is already allotted. Please try another book or contact to administrator'));
- return;
- } //$result > 0
- } //!$pref_id
- else
- {
- $book_title = ucname($book);
- $author = ucname($author);
- $dir_name = $book_title . " " . "by" . " " . $author;
- $directory_name = str_replace("__", "_", str_replace(" ", "_", $dir_name));
- $query = db_select('textbook_companion_preference');
- $query->fields('textbook_companion_preference');
- $query->condition('directory_name', $directory_name);
- $query->condition('id', $pref_id);
- $result = $query->execute()->rowCount();
- if ($result > 1)
- {
- form_set_error('', t('Book is already present. Please try another book or contact to administrator'));
- return;
- } //$result > 1
- }
- return $directory_name;
+
+/**
+ * Returns list of cities.
+ */
+function _list_of_cities() {
+ $city = array('' => '-select-');
+ $query = \Drupal::database()->select('list_cities_of_india');
+ $query->fields('list_cities_of_india');
+ $query->orderBy('city', 'ASC');
+ $city_list = $query->execute();
+ while ($city_list_data = $city_list->fetchObject()) {
+ $city[$city_list_data->city] = $city_list_data->city;
+ }
+ return $city;
}
diff --git a/modules/custom/DWSIM_textbook_companion/textbook_companion.routing.yml b/modules/custom/DWSIM_textbook_companion/textbook_companion.routing.yml
index 3f976da..ec35af0 100755
--- a/modules/custom/DWSIM_textbook_companion/textbook_companion.routing.yml
+++ b/modules/custom/DWSIM_textbook_companion/textbook_companion.routing.yml
@@ -139,17 +139,19 @@ textbook_companion.search_form:
requirements:
_permission: 'access content'
textbook_companion.browse_book:
- path: /textbook-companion/textbook-search/book
+ path: /textbook-companion/textbook-search/book/{character}
defaults:
_title: 'By Book Title'
_controller: '\Drupal\textbook_companion\Controller\DefaultController::textbook_companion_browse_book'
+ character: ''
requirements:
_permission: 'access content'
textbook_companion.browse_author:
- path: /textbook-companion/textbook-search/author
+ path: /textbook-companion/textbook-search/author/{character}
defaults:
_title: 'By Author'
_controller: '\Drupal\textbook_companion\Controller\DefaultController::textbook_companion_browse_author'
+ character: ''
requirements:
_permission: 'access content'
textbook_companion.browse_college_form:
@@ -160,10 +162,11 @@ textbook_companion.browse_college_form:
requirements:
_permission: 'access content'
textbook_companion.browse_student:
- path: /textbook-companion/textbook-search/student
+ path: /textbook-companion/textbook-search/student/{character}
defaults:
_title: 'By Student'
_controller: '\Drupal\textbook_companion\Controller\DefaultController::textbook_companion_browse_student'
+ character: ''
requirements:
_permission: 'access content'
textbook_companion.completed_books:
@@ -230,10 +233,11 @@ textbook_companion.download_full_book:
requirements:
_permission: 'download books to review'
textbook_companion.delete_book:
- path: /textbook-companion/delete-book
+ path: /textbook-companion/delete-book/{book_id}
defaults:
_title: 'Delete Book PDF'
_controller: '\Drupal\textbook_companion\Controller\DefaultController::textbook_companion_delete_book'
+ book_id: ''
requirements:
_permission: 'approve code'
textbook_companion.ajax:
@@ -258,10 +262,11 @@ textbook_companion._data_entry_proposal_all:
requirements:
_permission: 'dataentry book proposal'
textbook_companion.dataentry_edit:
- path: /textbook-companion/dataentry-edit
+ path: /textbook-companion/dataentry-edit/{id}
defaults:
_title: 'Edit book details'
_controller: '\Drupal\textbook_companion\Controller\DefaultController::dataentry_edit'
+ id: ''
requirements:
_permission: 'dataentry book proposal'
textbook_companion.cheque_proposal_all:
@@ -286,12 +291,14 @@ textbook_companion.cheque_contct_form:
requirements:
_permission: 'cheque contct form'
textbook_companion.cheque_status_form:
- path: /textbook-companion/cheque-contact/status
+ path: '/textbook-companion/cheque-contact/status/{proposal_id}'
defaults:
_title: 'Cheque Status'
_form: \Drupal\textbook_companion\Form\ChequeStatusForm
+ proposal_id: null
requirements:
_permission: 'cheque status form'
+ proposal_id: '\d+'
textbook_companion.cheque_report_form:
path: /textbook-companion/cheque-contct/report
defaults:
@@ -307,12 +314,14 @@ textbook_companion.cheque_report_form:
# requirements:
# _permission: 'list all certificates'
textbook_companion.generate_pdf:
- path: /textbook-companion/certificates/generate_pdf
+ path: '/textbook-companion/certificates/generate_pdf/{proposal_id}'
defaults:
_title: 'Download Certificate'
_form: \Drupal\textbook_companion\Form\GeneratePdf
+ proposal_id: null
requirements:
_permission: 'generate pdf'
+ proposal_id: '\d+'
# textbook_companion.verify_certificates:
# path: /textbook-companion/certificates/verify
# defaults:
@@ -321,12 +330,14 @@ textbook_companion.generate_pdf:
# requirements:
# _permission: 'verify certificates'
textbook_companion.paper_submission_form:
- path: /textbook-companion/manage-proposal/paper-submission
+ path: '/textbook-companion/manage-proposal/paper-submission/{proposal_id}'
defaults:
_title: 'Application Submission'
_form: \Drupal\textbook_companion\Form\PaperSubmissionForm
+ proposal_id: null
requirements:
_permission: 'paper submission form'
+ proposal_id: '\d+'
# textbook_companion.nonaicte_proposal_all:
# path: /textbook-companion/nonaicte-proposal
# defaults:
@@ -334,3 +345,12 @@ textbook_companion.paper_submission_form:
# _controller: '\Drupal\textbook_companion\Controller\DefaultController::textbook_companion_nonaicte_proposal_all'
# requirements:
# _permission: 'create book proposal'
+
+textbook_companion.edit_code_submission_form:
+ path: /textbook-companion/code-approval/edit-code-submission/{preference_id}
+ defaults:
+ _title: 'Edit Code Submission'
+ _form: \Drupal\textbook_companion\Form\EditCodeSubmissionForm
+ requirements:
+ _permission: 'approve code'
+
diff --git a/modules/custom/DWSIM_textbook_companion/textbook_companion.services.yml b/modules/custom/DWSIM_textbook_companion/textbook_companion.services.yml
index c6e6635..5f74c0b 100755
--- a/modules/custom/DWSIM_textbook_companion/textbook_companion.services.yml
+++ b/modules/custom/DWSIM_textbook_companion/textbook_companion.services.yml
@@ -1,3 +1,18 @@
services:
textbook_companion_global:
- class: '\Drupal\textbook_companion\Services\TextbookCompanionGlobalFunction'
\ No newline at end of file
+ class: '\Drupal\textbook_companion\Services\TextbookCompanionGlobalFunction'
+ arguments:
+ - '@database'
+ - '@messenger'
+ - '@current_user'
+ - '@module_handler'
+ - '@file_system'
+ - '@textbook_companion.mail_service'
+
+ textbook_companion.mail_service:
+ class: '\Drupal\textbook_companion\Services\MailService'
+ arguments: ['@plugin.manager.mail', '@logger.factory', '@config.factory', '@language_manager']
+
+ textbook_companion.ajax_helper:
+ class: '\Drupal\textbook_companion\Services\AjaxHelper'
+ arguments: ['@renderer']
\ No newline at end of file
diff --git a/modules/custom/dwsim_custom_model/custom_model.module b/modules/custom/dwsim_custom_model/custom_model.module
index 6302b7c..9745ef0 100755
--- a/modules/custom/dwsim_custom_model/custom_model.module
+++ b/modules/custom/dwsim_custom_model/custom_model.module
@@ -598,11 +598,12 @@ function custom_model_permission()
/* AJAX CALLS */
function custom_model_ajax()
{
- $query_type = arg(2);
+ $path_parts = explode('/', trim(\Drupal::request()->getPathInfo(), '/'));
+ $query_type = $path_parts[2] ?? '';
if ($query_type == 'chapter_title')
{
- $chapter_number = arg(3);
- $preference_id = arg(4);
+ $chapter_number = $path_parts[3] ?? '';
+ $preference_id = $path_parts[4] ?? '';
//$chapter_q = \Drupal::database()->query("SELECT * FROM {custom_model_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);
$query = \Drupal::database()->select('custom_model_chapter');
$query->fields('custom_model_chapter');
@@ -618,9 +619,9 @@ function custom_model_ajax()
}
else if ($query_type == 'example_exists')
{
- $chapter_number = arg(3);
- $preference_id = arg(4);
- $example_number = arg(5);
+ $chapter_number = $path_parts[3] ?? '';
+ $preference_id = $path_parts[4] ?? '';
+ $example_number = $path_parts[5] ?? '';
$chapter_id = 0;
$query = \Drupal::database()->select('custom_model_chapter');
$query->fields('custom_model_chapter');
@@ -761,8 +762,8 @@ function _cm_list_of_pincodes()
function _cm_dir_name($project, $proposar_name)
{
- $project_title = ucname($project);
- $proposar_name = ucname($proposar_name);
+ $project_title = custom_model_ucname($project);
+ $proposar_name = custom_model_ucname($proposar_name);
$dir_name = $project_title . ' By ' . $proposar_name;
$directory_name = str_replace("__", "_", str_replace(" ", "_", str_replace("/", " ", $dir_name)));
return $directory_name;
@@ -793,13 +794,13 @@ function cm_RenameDir($proposal_id, $dir_name)
} //is_dir($files_id_dir)
else
{
- \Drupal::messenger()->addMessage('Directory not available for rename.');
+ \Drupal::messenger()->addStatus('Directory not available for rename.');
return;
}
} //$result != NULL
else
{
- \Drupal::messenger()->addMessage('Project directory name not present in databse');
+ \Drupal::messenger()->addError('Project directory name not present in database.');
return;
}
//var_dump($files);die;
@@ -865,10 +866,10 @@ function cm_rrmdir_project($prop_id)
} //$objects as $object
reset($objects);
rmdir($dir);
- $msg = \Drupal::messenger()->addMessage("Directory deleted successfully");
+ $msg = \Drupal::messenger()->addStatus("Directory deleted successfully");
return $msg;
} //is_dir($dir)
- $msg = \Drupal::messenger()->addMessage("Directory not present");
+ $msg = \Drupal::messenger()->addStatus("Directory not present");
return $msg;
} //$proposal_data->id == $prop_id
else
@@ -909,8 +910,8 @@ function custom_model_get_proposal()
$proposal_data = $proposal_q->fetchObject();
if (!$proposal_data)
{
- \Drupal::messenger()->addMessage("You do not have any approved custom model proposal. Please check the ");
- drupal_goto('');
+ \Drupal::messenger()->addError("You do not have any approved custom model proposal.");
+ return FALSE;
}
switch ($proposal_data->approval_status)
{
diff --git a/modules/custom/dwsim_custom_model/custom_model.services.yml b/modules/custom/dwsim_custom_model/custom_model.services.yml
index 6e9eb2a..6dbee79 100755
--- a/modules/custom/dwsim_custom_model/custom_model.services.yml
+++ b/modules/custom/dwsim_custom_model/custom_model.services.yml
@@ -1,10 +1,12 @@
services:
custom_model_global:
class: '\Drupal\custom_model\Services\CustomModelGlobalfunction'
+ arguments: ['@database', '@messenger', '@current_user']
- # lab_migration_email:
- # class: '\Drupal\lab_migration\Services\LabMigrationEmailFunction'
+ custom_model.mail_helper:
+ class: '\Drupal\custom_model\Services\MailService'
+ arguments: ['@plugin.manager.mail', '@logger.factory', '@config.factory', '@language_manager']
- # lab_migration.form.lab_migration_proposal_approval:
- # class: Drupal\lab_migration\Form\LabMigrationProposalApprovalForm
- # arguments: ['@plugin.manager.mail']
+ custom_model.ajax_helper:
+ class: '\Drupal\custom_model\Services\AjaxHelper'
+ arguments: ['@renderer']
diff --git a/modules/custom/dwsim_custom_model/src/Controller/DefaultController.php b/modules/custom/dwsim_custom_model/src/Controller/DefaultController.php
index d41e116..6409aa8 100755
--- a/modules/custom/dwsim_custom_model/src/Controller/DefaultController.php
+++ b/modules/custom/dwsim_custom_model/src/Controller/DefaultController.php
@@ -1,130 +1,133 @@
-connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $routeMatch;
+ $this->globalFunction = $globalFunction;
+ $this->renderer = $renderer;
+ $this->formBuilder = $formBuilder;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match'),
+ $container->get('custom_model_global'),
+ $container->get('renderer'),
+ $container->get('form_builder')
+ );
+ }
+
public function custom_model_proposal_pending() {
- /* get pending proposals to be approved */
$pending_rows = [];
- $query = \Drupal::database()->select('custom_model_proposal');
+ $query = $this->connection->select('custom_model_proposal');
$query->fields('custom_model_proposal');
$query->condition('approval_status', 0);
$query->orderBy('id', 'DESC');
$pending_q = $query->execute();
- // var_dump($pending_data);die;
-// while ($pending_data = $pending_q->fetchObject()) {
-
-// $approval_url = Link::fromTextAndUrl('Approve', Url::fromRoute('custom_model.proposal_approval_form',['id'=>$pending_data->id]))->toString();
-// //
-// $edit_url = Link::fromTextAndUrl('Edit', Url::fromRoute('custom_model.proposal_edit_form',['id'=>$pending_data->id]))->toString();
-
-// $mainLink = t('@linkApprove | @linkReject', array('@linkApprove' => $approval_url, '@linkReject' => $edit_url));
-
-// $pending_rows[$pending_data->id] = [
-// date('d-m-Y', $pending_data->creation_date),
-
-// // l($pending_data->name_title . ' ' . $pending_data->contributor_name, 'user/' . $pending_data->uid),
-// // $pending_data->project_title,
-
-// Link::fromTextAndUrl($pending_data->name_title . ' ' . $pending_data->contributor_name,
-// Url::fromUri('internal:/user/' . $pending_data->uid)
-// )->toString(),
-// $pending_data->project_title,
-// // l('Approve', 'custom-model/manage-proposal/approve/' . $pending_data->id) . ' | ' . l('Edit', 'custom-model/manage-proposal/edit/' . $pending_data->id),
-
-// $pending_data->department,
-// $mainLink
-
-
-
-// // @linkApprove' => $approval_url, @linkReject' => $edit_url;
-// // $mainLink = t('$approval_url | $edit_url'),
-// ];
-// }
-// // var_dump($pending_data);die;
-// //$pending_data = $pending_q->fetchObject()
-// /* check if there are any pending proposals */
-// // if (!$pending_rows) {
-// // \Drupal::messenger()->addMessage(t('There are no pending proposals.'), 'status');
-// // return '';
-// // }
-while ($pending_data = $pending_q->fetchObject()) {
- $name = isset($pending_data->name_title) ? (string) $pending_data->name_title : '';
- $contributor = isset($pending_data->contributor_name) ? (string) $pending_data->contributor_name : '';
- $title = isset($pending_data->project_title) ? (string) $pending_data->project_title : '';
- $department = isset($pending_data->department) ? (string) $pending_data->department : '';
-
- $approval_url = Link::fromTextAndUrl('Approve', Url::fromRoute('custom_model.proposal_approval_form', ['id' => $pending_data->id]))->toString();
- $edit_url = Link::fromTextAndUrl('Edit', Url::fromRoute('custom_model.proposal_edit_form', ['id' => $pending_data->id]))->toString();
-
- $mainLink = t('@linkApprove | @linkReject', ['@linkApprove' => $approval_url, '@linkReject' => $edit_url]);
+ while ($pending_data = $pending_q->fetchObject()) {
+ $name = isset($pending_data->name_title) ? (string) $pending_data->name_title : '';
+ $contributor = isset($pending_data->contributor_name) ? (string) $pending_data->contributor_name : '';
+ $title = isset($pending_data->project_title) ? (string) $pending_data->project_title : '';
+ $department = isset($pending_data->department) ? (string) $pending_data->department : '';
+
+ $approval_url = Link::fromTextAndUrl('Approve', Url::fromRoute('custom_model.proposal_approval_form', ['id' => $pending_data->id]))->toString();
+ $edit_url = Link::fromTextAndUrl('Edit', Url::fromRoute('custom_model.proposal_edit_form', ['id' => $pending_data->id]))->toString();
+ $mainLink = t('@linkApprove | @linkReject', ['@linkApprove' => $approval_url, '@linkReject' => $edit_url]);
+
+ $pending_rows[$pending_data->id] = [
+ date('d-m-Y', $pending_data->creation_date),
+ Link::fromTextAndUrl($name . ' ' . $contributor, Url::fromUri('internal:/user/' . $pending_data->uid))->toString(),
+ $title,
+ $department,
+ $mainLink,
+ ];
+ }
- $pending_rows[$pending_data->id] = [
- date('d-m-Y', $pending_data->creation_date),
- Link::fromTextAndUrl($name . ' ' . $contributor, Url::fromUri('internal:/user/' . $pending_data->uid))->toString(),
- $title,
- $department,
- $mainLink,
- ];
-}
+ $pending_header = [
+ 'Date of Submission',
+ 'Contributor Name',
+ 'Title of the Custom Model',
+ 'Department',
+ 'Action',
+ ];
-// //!$pending_rows
-$pending_header = [
- 'Date of Submission',
- 'Contributor Name',
- 'Title of the Custom Model',
- 'Department',
- 'Action',
-];
-
-//$output = theme_table($pending_header, $pending_rows);
- $output = [
+ return [
'#type' => 'table',
'#header' => $pending_header,
'#rows' => $pending_rows,
];
- // var_dump($output);die;
- return $output;
}
-
-public function custom_model_proposal_all()
-{
- /* get pending proposals to be approved */
- $proposal_rows = array();
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->orderBy('id', 'DESC');
- $proposal_q = $query->execute();
- while ($proposal_data = $proposal_q->fetchObject())
- {
+ public function custom_model_proposal_all() {
+ $proposal_rows = [];
+ $query = $this->connection->select('custom_model_proposal');
+ $query->fields('custom_model_proposal');
+ $query->orderBy('id', 'DESC');
+ $proposal_q = $query->execute();
+ while ($proposal_data = $proposal_q->fetchObject()) {
$approval_status = '';
switch ($proposal_data->approval_status)
{
@@ -166,246 +169,143 @@ public function custom_model_proposal_all()
];
} //$proposal_data = $proposal_q->fetchObject()
/* check if there are any pending proposals */
- if (!$proposal_rows)
- {
- \Drupal::messenger()->addMessage(t('There are no proposals.'), 'status');
- return '';
- } //!$proposal_rows
- $proposal_header = [
- 'Date of Submission',
- 'Contributor Name',
- 'Title of the Custom Model',
- 'Date of Completion',
- 'Status',
- 'Action'
- ];
- $output = [
- '#theme' => 'table',
- '#header' => $proposal_header,
- '#rows' => $proposal_rows
- ];
- return $output;
-}
- public function custom_model_idea_proposal_all() {
- /* get pending proposals to be approved */
+ if (!$proposal_rows) {
+ $this->messenger->addStatus(t('There are no proposals.'));
+ return '';
+ }
+ $proposal_header = [
+ 'Date of Submission',
+ 'Contributor Name',
+ 'Title of the Custom Model',
+ 'Date of Completion',
+ 'Status',
+ 'Action',
+ ];
+ $output = [
+ '#theme' => 'table',
+ '#header' => $proposal_header,
+ '#rows' => $proposal_rows,
+ ];
+ return $output;
+ }
+ public function custom_model_idea_proposal_all() {
$proposal_rows = [];
- $query = \Drupal::database()->select('custom_model_idea_proposal');
+ $query = $this->connection->select('custom_model_idea_proposal');
$query->fields('custom_model_idea_proposal');
$query->orderBy('id', 'DESC');
$proposal_q = $query->execute();
while ($proposal_data = $proposal_q->fetchObject()) {
$approval_status = '';
switch ($proposal_data->approval_status) {
- case 0:
- $approval_status = 'Pending';
- break;
- case 1:
- $approval_status = 'Approved';
- break;
- case 2:
- $approval_status = 'Dis-approved';
- break;
- case 3:
- $approval_status = 'Completed';
- break;
- default:
- $approval_status = 'Unknown';
- break;
- } //$proposal_data->approval_status
- if ($proposal_data->actual_completion_date == 0) {
- $actual_completion_date = "Not Completed";
- } //$proposal_data->actual_completion_date == 0
- else {
- $actual_completion_date = date('d-m-Y', $proposal_data->actual_completion_date);
+ case 0: $approval_status = 'Pending'; break;
+ case 1: $approval_status = 'Approved'; break;
+ case 2: $approval_status = 'Dis-approved'; break;
+ case 3: $approval_status = 'Completed'; break;
+ default: $approval_status = 'Unknown'; break;
}
- // $idea_proposer_link =
- Link::fromTextAndUrl(
- $proposal_data->idea_proposar_name,
- Url::fromUri('internal:/user/' . $proposal_data->uid)
- )->toString();
-
+ $actual_completion_date = ($proposal_data->actual_completion_date == 0)
+ ? 'Not Completed'
+ : date('d-m-Y', $proposal_data->actual_completion_date);
+
$proposal_rows[] = [
date('d-m-Y', $proposal_data->creation_date),
- // l($proposal_data->idea_proposar_name, 'user/' . $proposal_data->uid),
- // $proposal_data->project_title,
- // Generate the link for the idea proposer name.
- Link::fromTextAndUrl($proposal_data->idea_proposar_name . ' ' . $pending_data->contributor_name,Url::fromUri('internal:/user/' . $proposal_data->uid)
+ Link::fromTextAndUrl(
+ $proposal_data->idea_proposar_name,
+ Url::fromUri('internal:/user/' . $proposal_data->uid)
+ )->toString(),
+ $proposal_data->project_title,
+ Link::fromTextAndUrl(
+ 'View',
+ Url::fromUri('internal:/custom-model/manage-proposal/view-ideas/' . $proposal_data->id)
)->toString(),
-
-
-// Assign the project title (no changes required for plain text).
-$project_title = $proposal_data->project_title,
-
-
-
- // Generate the "View" link.
- Link::fromTextAndUrl(
- 'View',
- Url::fromUri('internal:/custom-model/manage-proposal/view-ideas/' . $proposal_data->id)
-)->toString(),
];
- } //$proposal_data = $proposal_q->fetchObject()
- /* check if there are any pending proposals */
- // if (!$proposal_rows) {
- // \Drupal::messenger()->addMessage(t('There are no proposals.'), 'status');
- // return '';
- // }
- //!$proposal_rows
+ }
$proposal_header = [
'Date of Submission',
'Contributor Name',
'Title of the Custom Model',
'Action',
];
- $output = [
+ return [
'#type' => 'table',
'#header' => $proposal_header,
'#rows' => $proposal_rows,
];
- return $output;
}
public function dwsim_custom_model_approved_tab() {
- $page_content = [];
- $connection = \Drupal::database();
-
- // Query to fetch approved proposals.
- // $query = $connection->query("
- // SELECT *
- // FROM custom_model_proposal
- // WHERE id NOT IN (SELECT proposal_id FROM custom_model_submitted_abstracts)
- // AND approval_status = 1
- // ORDER BY approval_date DESC
- // ");
- $query = $connection->query("
- SELECT *
- FROM custom_model_proposal
- WHERE approval_status = 1
- ORDER BY approval_date DESC
-");
-
- $result = $query->fetchAll();
-
- // Check if any results are returned.
- if (empty($result)) {
- // No proposals found.
- $page_content['message'] = [
- '#markup' => 'Approved Proposals under Custom Model Project: 0
',
- ];
- }
- else {
- // Proposals found.
- $page_content['message'] = [
- '#markup' => 'Approved Proposals under Custom Model Project: ' . count($result) . '
',
- ];
-
- $proposal_rows = [];
- $i = 1;
-
- // Loop through the results to build table rows.
- foreach ($result as $row) {
- $approval_date = date("d-M-Y", $row->approval_date); // Convert timestamp to human-readable format.
-
- $proposal_rows[] = [
- $i,
- $row->project_title,
- $row->contributor_name,
- $row->university,
- $approval_date,
- ];
- $i++;
- }
-
- // Define table headers.
- $proposal_header = [
- 'No',
- 'Custom Model Project',
- 'Contributor Name',
- 'University / Institute',
- 'Year of Completion',
- ];
-
- // Define the table render array.
- $page_content = [
- '#type' => 'table',
- '#header' => $proposal_header,
- '#rows' => $proposal_rows,
+ $page_content = [];
+ $query = $this->connection->query("
+ SELECT * FROM custom_model_proposal
+ WHERE approval_status = 1
+ ORDER BY approval_date DESC
+ ");
+ $result = $query->fetchAll();
+ if (empty($result)) {
+ $page_content['message'] = [
+ '#markup' => 'Approved Proposals under Custom Model Project: 0
',
+ ];
+ }
+ else {
+ $page_content['message'] = [
+ '#markup' => 'Approved Proposals under Custom Model Project: ' . count($result) . '
',
+ ];
+ $proposal_rows = [];
+ $i = 1;
+ foreach ($result as $row) {
+ $approval_date = date("d-M-Y", $row->approval_date);
+ $proposal_rows[] = [
+ $i,
+ $row->project_title,
+ $row->contributor_name,
+ $row->university,
+ $approval_date,
];
+ $i++;
}
-
- return $page_content;
-
+ $proposal_header = ['No', 'Custom Model Project', 'Contributor Name', 'University / Institute', 'Year of Completion'];
+ $page_content = [
+ '#type' => 'table',
+ '#header' => $proposal_header,
+ '#rows' => $proposal_rows,
+ ];
+ }
+ return $page_content;
}
public function dwsim_custom_model_uploaded_tab() {
$page_content = [];
- // $connection = \Drupal::database();
- $result = \Drupal::database()->query("SELECT dfp.project_title, dfp.contributor_name, dfp.id, dfp.university, dfa.abstract_upload_date, dfa.abstract_approval_status from custom_model_proposal as dfp JOIN custom_model_submitted_abstracts as dfa on dfa.proposal_id = dfp.id where dfp.id in (select proposal_id from custom_model_submitted_abstracts) AND approval_status = 1");
- // Query to fetch approved proposals.
- // $query = $connection->query("
- // SELECT *
- // FROM custom_model_proposal
- // WHERE id NOT IN (SELECT proposal_id FROM custom_model_submitted_abstracts)
- // AND approval_status = 1
- // ORDER BY approval_date DESC
- // ");
-
-
- // Execute the query and fetch the results.
-
- // $result = $query->fetchAll();
-
- // Check if any results are returned.
- if (empty($result)) {
- // No proposals found.
- $page_content['message'] = [
- '#markup' => 'Uploaded Proposals under Custom Model Project :2
',
- $page_content .= "Uploaded Proposals under Custom Model Project:2"
- ];
- }
- else {
- // Proposals found.
- $page_content['message'] = [
- '#markup' => 'Uploaded Proposals under Custom Model Project :2 . count($result) .
',
- ];
-
- $proposal_rows = [];
- $i = 1;
-
- // Loop through the results to build table rows.
- foreach ($result as $row) {
- $approval_date = date("d-M-Y", $row->approval_date); // Convert timestamp to human-readable format.
-
- $proposal_rows[] = [
- $i,
- $row->project_title,
- $row->contributor_name,
- $row->university,
- $approval_date,
- ];
- $i++;
- }
-
- // Define table headers.
- $proposal_header = [
- 'No',
- 'Custom Model Project',
- 'Contributor Name',
- 'University / Institute',
- 'Year of Completion',
- ];
-
- // Define the table render array.
- $page_content = [
- '#type' => 'table',
- '#header' => $proposal_header,
- '#rows' => $proposal_rows,
+ $result = $this->connection->query("SELECT dfp.project_title, dfp.contributor_name, dfp.id, dfp.university, dfa.abstract_upload_date, dfa.abstract_approval_status from custom_model_proposal as dfp JOIN custom_model_submitted_abstracts as dfa on dfa.proposal_id = dfp.id where dfp.id in (select proposal_id from custom_model_submitted_abstracts) AND approval_status = 1");
+ if (empty($result)) {
+ $page_content['message'] = [
+ '#markup' => 'Uploaded Proposals under Custom Model Project: 0
',
+ ];
+ }
+ else {
+ $proposal_rows = [];
+ $i = 1;
+ foreach ($result as $row) {
+ $approval_date = date("d-M-Y", $row->abstract_upload_date);
+ $proposal_rows[] = [
+ $i,
+ $row->project_title,
+ $row->contributor_name,
+ $row->university,
+ $approval_date,
];
+ $i++;
}
- return $page_content;
+ $proposal_header = ['No', 'Custom Model Project', 'Contributor Name', 'University / Institute', 'Year of Completion'];
+ $page_content = [
+ '#type' => 'table',
+ '#header' => $proposal_header,
+ '#rows' => $proposal_rows,
+ ];
}
+ return $page_content;
+ }
// public function custom_model_abstract() {
@@ -537,82 +437,60 @@ public function dwsim_custom_model_uploaded_tab() {
public function custom_model_abstract() {
- $user = \Drupal::currentUser();
$return_html = "";
-
- // Fetch proposal.
- $proposal_data = \Drupal::service('custom_model_global')->custom_model_get_proposal();
+ $proposal_data = $this->globalFunction->custom_model_get_proposal();
if (!$proposal_data) {
return [];
}
-
- $db = \Drupal::database();
-
// Fetch submission status.
- $abstracts_q = $db->select('custom_model_submitted_abstracts')
+ $abstracts_q = $this->connection->select('custom_model_submitted_abstracts')
->fields('custom_model_submitted_abstracts')
->condition('proposal_id', $proposal_data->id)
->execute()
->fetchObject();
-
// Abstract file (type A).
- $abstracts_pdf = $db->select('custom_model_submitted_abstracts_file')
+ $abstracts_pdf = $this->connection->select('custom_model_submitted_abstracts_file')
->fields('custom_model_submitted_abstracts_file')
->condition('proposal_id', $proposal_data->id)
->condition('filetype', 'A')
->execute()
->fetchObject();
-
- if (!empty($abstracts_pdf->filename) && $abstracts_pdf->filename !== "NULL") {
- $abstract_filename = Link::fromTextAndUrl(
- $abstracts_pdf->filename,
- Url::fromUri('internal:/custom-model/download/project-file/' . $proposal_data->id)
- )->toString();
- } else {
- $abstract_filename = "File not uploaded";
- }
-
+ $abstract_filename = (!empty($abstracts_pdf->filename) && $abstracts_pdf->filename !== "NULL")
+ ? Link::fromTextAndUrl($abstracts_pdf->filename, Url::fromUri('internal:/custom-model/download/project-file/' . $proposal_data->id))->toString()
+ : "File not uploaded";
// Simulation file (type S).
- $abstracts_query_process = $db->select('custom_model_submitted_abstracts_file')
+ $abstracts_query_process = $this->connection->select('custom_model_submitted_abstracts_file')
->fields('custom_model_submitted_abstracts_file')
->condition('proposal_id', $proposal_data->id)
->condition('filetype', 'S')
->execute()
->fetchObject();
-
- if (!empty($abstracts_query_process->filename) && $abstracts_query_process->filename !== "NULL") {
- $abstracts_query_process_filename = $abstracts_query_process->filename;
- } else {
- $abstracts_query_process_filename = "File not uploaded";
- }
-
+ $abstracts_query_process_filename = (!empty($abstracts_query_process->filename) && $abstracts_query_process->filename !== "NULL")
+ ? $abstracts_query_process->filename
+ : "File not uploaded";
// Script file (type P).
- $abstracts_query_sc = $db->select('custom_model_submitted_abstracts_file')
+ $abstracts_query_sc = $this->connection->select('custom_model_submitted_abstracts_file')
->fields('custom_model_submitted_abstracts_file')
->condition('proposal_id', $proposal_data->id)
->condition('filetype', 'P')
->execute()
->fetchObject();
-
- if (!empty($abstracts_query_sc->filename) && $abstracts_query_sc->filename !== "NULL") {
- $abstracts_query_sc_filename = $abstracts_query_sc->filename;
- } else {
- $abstracts_query_sc_filename = "File not uploaded";
- }
-
- // Upload/Edit link based on submission status.
+ $abstracts_query_sc_filename = (!empty($abstracts_query_sc->filename) && $abstracts_query_sc->filename !== "NULL")
+ ? $abstracts_query_sc->filename
+ : "File not uploaded";
+ // Upload/Edit link.
$url = '';
if (isset($abstracts_q->is_submitted)) {
if ($abstracts_q->is_submitted === '') {
$url = Link::fromTextAndUrl('Upload abstract', Url::fromUri('internal:/custom-model/abstract-code/upload'))->toString();
- } elseif ($abstracts_q->is_submitted == 0) {
+ }
+ elseif ($abstracts_q->is_submitted == 0) {
$url = Link::fromTextAndUrl('Edit', Url::fromUri('internal:/custom-model/abstract-code/upload'))->toString();
}
- } else {
+ }
+ else {
$url = Link::fromTextAndUrl('Upload abstract', Url::fromUri('internal:/custom-model/abstract-code/upload'))->toString();
}
-
- // Build HTML.
$return_html .= 'Contributor Name: ' . $proposal_data->name_title . ' ' . $proposal_data->contributor_name . ' ';
$return_html .= 'Title of the Circuit Simulation Project: ' . $proposal_data->project_title . ' ';
$return_html .= 'DWSIM version used: ' . $proposal_data->version . ' ';
@@ -620,8 +498,6 @@ public function custom_model_abstract() {
$return_html .= 'Uploaded scilab/ironpython script for the custom model: ' . $abstracts_query_sc_filename . ' ';
$return_html .= 'Uploaded abstract of the project: ' . $abstract_filename . ' ';
$return_html .= $url . ' ';
-
- // Return render array with allowed tags.
return [
'#type' => 'markup',
'#markup' => $return_html,
@@ -629,452 +505,264 @@ public function custom_model_abstract() {
];
}
-
public function custom_model_download_completed_project() {
- $user = \Drupal::currentUser();
- // $id = arg(3);
- $root_path = \Drupal::service("custom_model_global")->custom_model_path();
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $id);
- $custom_model_q = $query->execute();
- $custom_model_data = $custom_model_q->fetchObject();
- $CIRCUITSIMULATION_PATH = $custom_model_data->directory_name . '/';
- /* zip filename */
+ $id = $this->routeMatch->getParameter('id');
+ $root_path = $this->globalFunction->custom_model_path();
+ $custom_model_data = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('id', $id)
+ ->execute()
+ ->fetchObject();
+ if (!$custom_model_data) {
+ $this->messenger->addError(t('Invalid proposal ID.'));
+ return new RedirectResponse('/custom-model/full-download/project');
+ }
$zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
- /* creating zip archive on the server */
$zip = new \ZipArchive();
$zip->open($zip_filename, \ZipArchive::CREATE);
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $id);
- $custom_model_udc_q = $query->execute();
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $id);
- $query = \Drupal::database()->select('custom_model_submitted_abstracts_file');
- $query->fields('custom_model_submitted_abstracts_file');
- $query->condition('proposal_id', $id);
- $project_files = $query->execute();
- //var_dump($root_path . $CIRCUITSIMULATION_PATH . 'project_files/');die;
- while ($project_files = $project_files->fetchObject()) {
- $zip->addFile($root_path . $CIRCUITSIMULATION_PATH . 'project_files/' . $project_files->filepath, $CIRCUITSIMULATION_PATH . str_replace(' ', '_', basename($project_files->filename)));
+ $project_files = $this->connection->select('custom_model_submitted_abstracts_file')
+ ->fields('custom_model_submitted_abstracts_file')
+ ->condition('proposal_id', $id)
+ ->execute();
+ $CIRCUITSIMULATION_PATH = $custom_model_data->directory_name . '/';
+ while ($file = $project_files->fetchObject()) {
+ $zip->addFile(
+ $root_path . $CIRCUITSIMULATION_PATH . 'project_files/' . $file->filepath,
+ $CIRCUITSIMULATION_PATH . str_replace(' ', '_', basename($file->filename))
+ );
}
$zip_file_count = $zip->numFiles;
$zip->close();
- if ($zip_file_count > 0) {
- if ($user->uid) {
- /* download zip file */
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . str_replace(' ', '_', $custom_model_data->project_title) . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- //ob_end_flush();
- ob_clean();
- //flush();
- readfile($zip_filename);
- unlink($zip_filename);
- } //$user->uid
- else {
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . str_replace(' ', '_', $custom_model_data->project_title) . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- //ob_end_flush();
- ob_clean();
- //flush();
- readfile($zip_filename);
- unlink($zip_filename);
- }
- } //$zip_file_count > 0
- else {
- \Drupal::messenger()->addMessage("There are circuit simulation project in this proposal to download", 'error');
- // drupal_goto('circuit-simulation-project/full-download/project');
+ if ($zip_file_count > 0 && file_exists($zip_filename)) {
+ $response = new BinaryFileResponse($zip_filename);
+ $response->setContentDisposition(
+ ResponseHeaderBag::DISPOSITION_ATTACHMENT,
+ str_replace(' ', '_', $custom_model_data->project_title) . '.zip'
+ );
+ $response->deleteFileAfterSend(true);
+ return $response;
}
+ $this->messenger->addError(t('There are no files in this proposal to download.'));
+ return new RedirectResponse('/custom-model/full-download/project');
}
-
public function custom_model_download_full_project() {
- $user = \Drupal::currentUser();
- $route_match = \Drupal::routeMatch();
- $id = $route_match->getParameter('id');
- $root_path = \Drupal::service("custom_model_global")->custom_model_path(); // Assuming this is a global helper
-
- // Fetch proposal data
- $query = \Drupal::database()->select('custom_model_proposal', 'cmp');
- $query->fields('cmp');
- $query->condition('id', $id);
- $custom_model_data = $query->execute()->fetchObject();
-
+ $id = $this->routeMatch->getParameter('id');
+ $root_path = $this->globalFunction->custom_model_path();
+ $custom_model_data = $this->connection->select('custom_model_proposal', 'cmp')
+ ->fields('cmp')
+ ->condition('id', $id)
+ ->execute()
+ ->fetchObject();
if (!$custom_model_data) {
- \Drupal::messenger()->addError(t('Invalid proposal ID.'));
+ $this->messenger->addError(t('Invalid proposal ID.'));
return new RedirectResponse('/circuit-simulation-project/full-download/project');
}
-
- $project_dir = $custom_model_data->directory_name . '/project_files/';
$zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip';
-
$zip = new \ZipArchive();
if ($zip->open($zip_filename, \ZipArchive::CREATE) !== true) {
- \Drupal::messenger()->addError(t('Unable to create zip file.'));
+ $this->messenger->addError(t('Unable to create zip file.'));
return new RedirectResponse('/circuit-simulation-project/full-download/project');
}
-
- // Add project files to zip
- $query = \Drupal::database()->select('custom_model_submitted_abstracts_file', 'f');
- $query->fields('f');
- $query->condition('proposal_id', $id);
- $result = $query->execute();
-
+ $result = $this->connection->select('custom_model_submitted_abstracts_file', 'f')
+ ->fields('f')
+ ->condition('proposal_id', $id)
+ ->execute();
while ($file = $result->fetchObject()) {
$file_path = $root_path . $custom_model_data->directory_name . '/project_files/' . $file->filepath;
if (file_exists($file_path)) {
$zip->addFile($file_path, str_replace(' ', '_', basename($file->filename)));
}
}
-
$zip_file_count = $zip->numFiles;
$zip->close();
-
if ($zip_file_count > 0 && file_exists($zip_filename)) {
$response = new BinaryFileResponse($zip_filename);
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
str_replace(' ', '_', $custom_model_data->project_title) . '.zip'
);
-
- // Delete the zip file after it's sent
$response->deleteFileAfterSend(true);
return $response;
}
- else {
- \Drupal::messenger()->addError(t('There are no circuit simulation files in this proposal to download.'));
- return new RedirectResponse('/circuit-simulation-project/full-download/project/');
- }
+ $this->messenger->addError(t('There are no circuit simulation files in this proposal to download.'));
+ return new RedirectResponse('/circuit-simulation-project/full-download/project/');
}
public function custom_model_completed_proposals_all() {
$output = [];
- $query = \Drupal::database()->select('custom_model_proposal');
+ $query = $this->connection->select('custom_model_proposal');
$query->fields('custom_model_proposal');
$query->condition('approval_status', 3);
$query->orderBy('actual_completion_date', 'DESC');
- //$query->condition('is_completed', 1);
$result = $query->execute();
-
-
- //var_dump($custom_model_abstract);die;
- if (empty($result)) {
- $output ['message']= [
- '#markup' => 'Work has been completed for the following custom model. We welcome your contributions. .
'
- ];
-
- }
- else{
- $output ['message']= [ '#markup' => 'Work has been completed for the following custom model. We welcome your contributions.
'];
-
-
-
- //$result->rowCount() == 0
-
- $preference_rows = [];
- $i = 1;
- while ($row = $result->fetchObject()) {
- $proposal_id = $row->id;
- $completion_date = date("Y", $row->actual_completion_date);
- $preference_rows[] = [
- $i,
- // l($row->project_title, "custom-model/custom-model-run/" . $row->id) . t("(Script used: ") . $row->script_used . t(") "),
- Link::fromTextAndUrl(
- $row->project_title,
- Url::fromUri('internal:/custom-model/custom-model-run/' . $row->id)
- )->toString(),
-
- // $markup = $link . $this->t('(Script used: @script) ', ['@script' => $row->script_used]),
- $row->contributor_name,
- $row->university,
- $completion_date,
- ];
- $i++;
- } //$row = $result->fetchObject()
- $preference_header = [
- 'No',
- 'Custom Model Project',
- 'Contributor Name',
- 'University / Institute',
- 'Year of Completion',
- ];
- $output =[
- '#type' => 'table',
- '#header' => $preference_header,
- '#rows' => $preference_rows,
- ];
- }
- return $output;
- }
-
-
-
-
-
-/**
- * Custom function to show progress of custom model proposals.
- */
-public function custom_model_progress_all() {
- $page_content = [];
-
- // Get the database connection
- $connection = Database::getConnection();
-
- // Create the select query
- $query = $connection->select('custom_model_proposal', 'cmp');
- $query->fields('cmp');
- $query->condition('approval_status', 1);
- $query->condition('is_completed', 0);
- $query->orderBy('approval_date', 'DESC');
-
- // Execute the query and get the results
- $result = $query->execute();
-
- // Check if no rows are returned
- // if ($result->fetchAll()) {
- // $page_content ['#markup']= "Work is in progress for the following custom model under DWSIM Custom Model Project";
- // } else {
- // // If results exist, start building the table
- // $page_content ['#markup ']= "Work is in progress for the following custom model under DWSIM Custom Model Project";
-
- if (empty($result)) {
- $output['message'] = [
- '#type' => 'container',
- 'text' => [
- '#markup' => t('Work has been completed for the following custom model. We welcome your contributions.'),
- ],
- 'divider' => [
- '#markup' => ' ',
- ],
- ];
- } else {
- $output['message'] = [
- '#type' => 'container',
- 'text' => [
- '#markup' => t('Work has been completed for the following custom model. We welcome your contributions.'),
- ],
- ];
-
- }
+ $output['message'] = ['#markup' => 'Work has been completed for the following custom model. We welcome your contributions.
'];
$preference_rows = [];
- $i = 1; // Counter for row numbers
-
- // Iterate over each row of results
- foreach ($result as $row) {
- $approval_date = date("Y", $row->approval_date);
+ $i = 1;
+ while ($row = $result->fetchObject()) {
+ $completion_date = date("Y", $row->actual_completion_date);
$preference_rows[] = [
$i,
- $row->project_title,
+ Link::fromTextAndUrl($row->project_title, Url::fromUri('internal:/custom-model/custom-model-run/' . $row->id))->toString(),
$row->contributor_name,
$row->university,
- $approval_date,
+ $completion_date,
];
$i++;
- // }
-
- // Define table headers
- $preference_header = [
- 'No',
- 'Custom Model Project',
- 'Contributor Name',
- 'University / Institute',
- 'Year',
- ];
-
- // Render the table
- $page_content = [
- '#type' =>'table',
+ }
+ $preference_header = ['No', 'Custom Model Project', 'Contributor Name', 'University / Institute', 'Year of Completion'];
+ $output = [
+ '#type' => 'table',
'#header' => $preference_header,
'#rows' => $preference_rows,
];
+ return $output;
}
-
- return $page_content;
-}
-
-
- public function custom_model_download_uploaded_file() {
- // $proposal_id = arg(3);
- $route_match = \Drupal::routeMatch();
- $proposal_id = (int) $route_match->getParameter('proposal_id');
- // var_dump($proposal_id);die;
- $root_path = \Drupal::service("custom_model_global")->custom_model_path();
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $proposal_id);
- $query->range(0, 1);
+ public function custom_model_progress_all() {
+ $query = $this->connection->select('custom_model_proposal', 'cmp');
+ $query->fields('cmp');
+ $query->condition('approval_status', 1);
+ $query->condition('is_completed', 0);
+ $query->orderBy('approval_date', 'DESC');
$result = $query->execute();
- $custom_model_uploaded_file = $result->fetchObject();
- $samplecodename = $custom_model_uploaded_file->samplefilepath;
- //var_dump($root_path . $samplecodename);die;
- ob_clean();
- header("Pragma: public");
- header("Expires: 0");
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header("Cache-Control: public");
- header("Content-Description: File Transfer");
- header('Content-Type: application/pdf');
- header('Content-disposition: attachment; filename="' . $samplecodename . '"');
- header('Content-Length: ' . filesize($root_path . $samplecodename));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- ob_clean();
- readfile($root_path . $samplecodename);
- //ob_end_flush();
- // var_dump($root_path . $custom_model_uploaded_file);die;
-
- //flush();
+ $preference_rows = [];
+ $i = 1;
+ foreach ($result as $row) {
+ $approval_date = date("Y", $row->approval_date);
+ $preference_rows[] = [$i, $row->project_title, $row->contributor_name, $row->university, $approval_date];
+ $i++;
+ }
+ $preference_header = ['No', 'Custom Model Project', 'Contributor Name', 'University / Institute', 'Year'];
+ $page_content = [
+ '#markup' => 'Work is in progress for the following custom models.
',
+ ];
+ if ($preference_rows) {
+ $page_content = [
+ '#type' => 'table',
+ '#header' => $preference_header,
+ '#rows' => $preference_rows,
+ ];
+ }
+ return $page_content;
}
-
-
+ public function custom_model_download_uploaded_file() {
+ $proposal_id = (int) $this->routeMatch->getParameter('proposal_id');
+ $root_path = $this->globalFunction->custom_model_path();
+ $custom_model_uploaded_file = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
+ $samplecodename = $custom_model_uploaded_file->samplefilepath;
+ $file_path = $root_path . $samplecodename;
+ if (!file_exists($file_path)) {
+ $this->messenger->addError(t('File not found.'));
+ return new RedirectResponse('/');
+ }
+ $response = new BinaryFileResponse($file_path);
+ $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $samplecodename);
+ return $response;
+ }
public function custom_model_download_idea_reference_file() {
- // $proposal_id = arg(3);
- $route_match = \Drupal::routeMatch();
- $proposal_id = $route_match->getParameter('proposal_id');
-
- $root_path = custom_model_ideas_files_path();
- $query = \Drupal::database()->select('custom_model_idea_proposal');
- $query->fields('custom_model_idea_proposal');
- $query->condition('id', $proposal_id);
- $query->range(0, 1);
- $result = $query->execute();
- $uploaded_idea_reference_file = $result->fetchObject();
+ $proposal_id = $this->routeMatch->getParameter('proposal_id');
+ $root_path = $this->globalFunction->custom_model_ideas_files_path();
+ $uploaded_idea_reference_file = $this->connection->select('custom_model_idea_proposal')
+ ->fields('custom_model_idea_proposal')
+ ->condition('id', $proposal_id)
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
$samplecodename = $uploaded_idea_reference_file->reference_file;
- //var_dump($root_path . $custom_model_uploaded_file->directory_name . '/' . $samplecodename);die;
- ob_clean();
- header("Pragma: public");
- header("Expires: 0");
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header("Cache-Control: public");
- header("Content-Description: File Transfer");
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . $samplecodename . '"');
- header('Content-Length: ' . filesize($root_path . $uploaded_idea_reference_file->directory_name . '/' . $samplecodename));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- ob_clean();
- readfile($root_path . $uploaded_idea_reference_file->directory_name . '/' . $samplecodename);
- //ob_end_flush();
- //flush();
+ $file_path = $root_path . $uploaded_idea_reference_file->directory_name . '/' . $samplecodename;
+ if (!file_exists($file_path)) {
+ $this->messenger->addError(t('File not found.'));
+ return new RedirectResponse('/');
+ }
+ $response = new BinaryFileResponse($file_path);
+ $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $samplecodename);
+ return $response;
}
public function custom_model_project_files() {
- // $proposal_id = arg(3);
- $route_match = \Drupal::routeMatch();
- $proposal_id = $route_match->getParameter('proposal_id');
-
- $root_path = \Drupal::service('custom_model_global')->custom_model_path();
- //var_dump($proposal_id);die;
- $query = \Drupal::database()->select('custom_model_submitted_abstracts_file');
- $query->fields('custom_model_submitted_abstracts_file');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('filetype', 'A');
- $result = $query->execute();
- $custom_model_project_files = $result->fetchObject();
- //var_dump($custom_model_project_files);die;
- $query1 = \Drupal::database()->select('custom_model_proposal');
- $query1->fields('custom_model_proposal');
- $query1->condition('id', $proposal_id);
- $result1 = $query1->execute();
- $custom_model = $result1->fetchObject();
+ $proposal_id = $this->routeMatch->getParameter('proposal_id');
+ $root_path = $this->globalFunction->custom_model_path();
+ $custom_model_project_files = $this->connection->select('custom_model_submitted_abstracts_file')
+ ->fields('custom_model_submitted_abstracts_file')
+ ->condition('proposal_id', $proposal_id)
+ ->condition('filetype', 'A')
+ ->execute()
+ ->fetchObject();
+ $custom_model = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
$directory_name = $custom_model->directory_name . '/project_files/';
$samplecodename = $custom_model_project_files->filename;
- ob_clean();
- header("Pragma: public");
- header("Expires: 0");
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header("Cache-Control: public");
- header("Content-Description: File Transfer");
- header("Content-Type: application/pdf");
- header('Content-disposition: attachment; filename="' . $samplecodename . '"');
- header("Content-Length: " . filesize($root_path . $directory_name . $samplecodename));
- header("Content-Transfer-Encoding: binary");
- header("Expires: 0");
- header("Pragma: no-cache");
- ob_clean();
- readfile($root_path . $directory_name . $samplecodename);
- //ob_end_flush();
- //ob_clean();
+ $file_path = $root_path . $directory_name . $samplecodename;
+ if (!file_exists($file_path)) {
+ $this->messenger->addError(t('File not found.'));
+ return new RedirectResponse('/');
+ }
+ $response = new BinaryFileResponse($file_path);
+ $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $samplecodename);
+ return $response;
}
public function _list_custom_model_certificates() {
- $user = \Drupal::currentUser();
- $query_id = \Drupal::database()->query("SELECT id FROM custom_model_proposal WHERE approval_status=3 AND uid= :uid", [
- ':uid' => $user->uid
- ]);
+ $user = $this->currentUser;
+ $query_id = $this->connection->query("SELECT id FROM custom_model_proposal WHERE approval_status=3 AND uid= :uid", [
+ ':uid' => $user->id(),
+ ]);
$exist_id = $query_id->fetchObject();
- if ($exist_id) {
- if ($exist_id->id) {
- if ($exist_id->id < 3) {
- \Drupal::messenger()->addMessage('You need to propose a Custom Model Project . If you have already proposed then you Custom Model is under reviewing process', 'status');
- return '';
- } //$exist_id->id < 3
- else {
- $search_rows = [];
- global $output;
- $output = '';
- $query3 = \Drupal::database()->query("SELECT id,project_title,contributor_name FROM custom_model_proposal WHERE approval_status=3 AND uid= :uid", [
- ':uid' => $user->uid
- ]);
- while ($search_data3 = $query3->fetchObject()) {
- if ($search_data3->id) {
- $search_rows[] = [
- $search_data3->project_title,
- $search_data3->contributor_name,
- l('Download Certificate', 'custom-model/certificates/generate-pdf/' . $search_data3->id),
- ];
- } //$search_data3->id
- } //$search_data3 = $query3->fetchObject()
- if ($search_rows) {
- $search_header = [
- 'Project Title',
- 'Contributor Name',
- 'Download Certificates',
- ];
- $output = theme('table', [
- 'header' => $search_header,
- 'rows' => $search_rows,
- ]);
- return $output;
- } //$search_rows
- else {
- echo ("Error");
- return '';
- }
+ if ($exist_id && $exist_id->id) {
+ if ($exist_id->id < 3) {
+ $this->messenger->addStatus('You need to propose a Custom Model Project . If you have already proposed then your Custom Model is under the reviewing process');
+ return '';
+ }
+ $search_rows = [];
+ $query3 = $this->connection->query("SELECT id,project_title,contributor_name FROM custom_model_proposal WHERE approval_status=3 AND uid= :uid", [
+ ':uid' => $user->id(),
+ ]);
+ while ($search_data3 = $query3->fetchObject()) {
+ if ($search_data3->id) {
+ $search_rows[] = [
+ $search_data3->project_title,
+ $search_data3->contributor_name,
+ Link::fromTextAndUrl(
+ 'Download Certificate',
+ Url::fromUri('internal:/custom-model/certificates/generate-pdf/' . $search_data3->id)
+ )->toString(),
+ ];
}
}
- } //$exist_id->id
- else {
- \Drupal::messenger()->addMessage('You need to propose a Custom Model Project . If you have already proposed then you Custom Model is under reviewing process', 'status');
- $page_content = " No certificate available ";
- return $page_content;
+ if ($search_rows) {
+ $search_header = ['Project Title', 'Contributor Name', 'Download Certificates'];
+ return [
+ '#type' => 'table',
+ '#header' => $search_header,
+ '#rows' => $search_rows,
+ ];
+ }
+ return '';
}
+ $this->messenger->addStatus('You need to propose a Custom Model Project . If you have already proposed then your Custom Model is under the reviewing process');
+ return " No certificate available ";
}
public function verify_certificates($qr_code = 0) {
- $qr_code = arg(3);
- $route_match = \Drupal::routeMatch();
- $qr_code = $route_match->getParameter('qr_code');
-
+ $qr_code = $this->routeMatch->getParameter('qr_code');
$page_content = "";
if ($qr_code) {
$page_content = verify_qrcode_fromdb($qr_code);
- } //$qr_code
+ }
else {
- $verify_certificates_form = \Drupal::formBuilder()->getForm("verify_certificates_form");
- $page_content = \Drupal::service("renderer")->render($verify_certificates_form);
+ $verify_certificates_form = $this->formBuilder->getForm("verify_certificates_form");
+ $page_content = $this->renderer->render($verify_certificates_form);
}
return $page_content;
}
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelAbstractSubmissionBulkApprovalForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelAbstractSubmissionBulkApprovalForm.php
index 65167ca..57a70b4 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelAbstractSubmissionBulkApprovalForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelAbstractSubmissionBulkApprovalForm.php
@@ -4,22 +4,85 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Ajax\AjaxResponse;
-use Drupal\Core\Ajax\HtmlCommand;
-use Drupal\Core\Ajax\ReplaceCommand;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
- use Drupal\user\Entity\User;
-use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\Messenger\MessengerInterface;
-use Drupal\Core\Language\LanguageManagerInterface;
-
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\custom_model\Services\MailService;
/**
- * Provides a form for bulk abstract approval in the Custom Model module.
+ * Bulk approval form for custom model abstract submissions.
*/
class CustomModelAbstractSubmissionBulkApprovalForm extends FormBase {
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $connection;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityTypeManager;
+
+ /**
+ * The mail service.
+ *
+ * @var \Drupal\custom_model\Services\MailService
+ */
+ protected $mailService;
+
+ /**
+ * Constructs the form with injected services.
+ */
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ EntityTypeManagerInterface $entityTypeManager,
+ MailService $mailService
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->entityTypeManager = $entityTypeManager;
+ $this->mailService = $mailService;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('entity_type.manager'),
+ $container->get('custom_model.mail_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -34,78 +97,64 @@ public function buildForm(array $form, FormStateInterface $form_state) {
$options = $this->_bulk_list_of_custom_model_proposals();
$selected = $form_state->getValue('custom_model_proposals') ?? key($options);
- // $form['custom_model_proposals'] = [
- // '#type' => 'select',
- // '#title' => $this->t('Title of the Custom Model'),
- // '#options' => $options,
- // '#default_value' => $selected,
- // '#ajax' => [
- // 'callback' => [$this, 'ajaxCustomModelDetailsCallback'],
- // 'wrapper' => 'ajax-selected-custom-model-wrapper',
- // ],
- // '#suffix' => '',
- // ];
-
$form['custom_model_proposals'] = [
'#type' => 'select',
- '#title' => t('Title of the custom model'),
- '#options' => $this->_bulk_list_of_custom_model_proposals(),
+ '#title' => $this->t('Title of the custom model'),
+ '#options' => $options,
'#default_value' => $selected,
'#ajax' => [
'callback' => '::ajax_bulk_custom_model_abstract_details_callback',
- 'wrapper' => 'ajax_selected_custom_model'
- ],
+ 'wrapper' => 'ajax_selected_custom_model',
+ ],
];
+
$form['update_custom_model'] = [
'#type' => 'container',
'#attributes' => ['id' => 'ajax_selected_custom_model'],
'#states' => [
'invisible' => [
':input[name="custom_model_proposals"]' => [
- 'value' => 0
- ]
- ]
+ 'value' => 0,
+ ],
],
+ ],
];
+
$form['update_custom_model']['cm_details'] = [
'#type' => 'markup',
'#markup' => $this->_custom_model_details($form_state->getValue('custom_model_proposals')),
'#states' => [
'invisible' => [
':input[name="custom_model_proposals"]' => [
- 'value' => 0
- ]
- ]
+ 'value' => 0,
+ ],
],
+ ],
];
+
$form['custom_model_actions'] = [
'#type' => 'select',
- '#title' => t('Please select action for Custom Model project'),
+ '#title' => $this->t('Please select action for Custom Model project'),
'#options' => $this->_bulk_list_custom_model_actions(),
'#default_value' => 0,
'#states' => [
'invisible' => [
':input[name="custom_model_proposals"]' => [
- 'value' => 0
- ]
- ]
+ 'value' => 0,
+ ],
],
+ ],
];
-
-
+
$form['message'] = [
'#type' => 'textarea',
'#title' => $this->t('Please specify the reason for marking resubmit/disapproval'),
'#prefix' => '',
'#states' => [
'visible' => [
- [
- ':input[name="custom_model_actions"]' => ['value' => 2],
- ],
+ [':input[name="custom_model_actions"]' => ['value' => 2]],
'or',
- [
- ':input[name="custom_model_actions"]' => ['value' => 3],
- ],
+ [':input[name="custom_model_actions"]' => ['value' => 3]],
],
],
];
@@ -117,319 +166,270 @@ public function buildForm(array $form, FormStateInterface $form_state) {
return $form;
}
- public function ajaxProposalCallback(array &$form, FormStateInterface $form_state) {
- return $form['proposal_wrapper'];
- }
-
- function ajax_bulk_custom_model_abstract_details_callback(array &$form, FormStateInterface $form_state) {
- return $form['update_custom_model'];
- }
-
-
-/**
- * Returns the custom model proposal details HTML.
- */
-function _custom_model_details($custom_model_proposal_id) {
- $database = \Drupal::database();
- $return_html = '';
-
- // Fetch proposal data.
- $abstracts_pro = $database->select('custom_model_proposal', 'cmp')
- ->fields('cmp')
- ->condition('id', $custom_model_proposal_id)
- ->execute()
- ->fetchObject();
-
- // Abstract file (filetype A).
- $abstracts_pdf = $database->select('custom_model_submitted_abstracts_file', 'pdf')
- ->fields('pdf')
- ->condition('proposal_id', $custom_model_proposal_id)
- ->condition('filetype', 'A')
- ->execute()
- ->fetchObject();
-
- $abstract_filename = (!empty($abstracts_pdf) && !empty($abstracts_pdf->filename) && $abstracts_pdf->filename !== "NULL")
- ? $abstracts_pdf->filename
- : 'File not uploaded';
-
- // DWSIM Simulation file (filetype S).
- $abstracts_process = $database->select('custom_model_submitted_abstracts_file', 'proc')
- ->fields('proc')
- ->condition('proposal_id', $custom_model_proposal_id)
- ->condition('filetype', 'S')
- ->execute()
- ->fetchObject();
-
- $process_filename = (!empty($abstracts_process) && !empty($abstracts_process->filename) && $abstracts_process->filename !== "NULL")
- ? $abstracts_process->filename
- : 'File not uploaded';
-
- // Script file (filetype P).
- $abstracts_script = $database->select('custom_model_submitted_abstracts_file', 'script')
- ->fields('script')
- ->condition('proposal_id', $custom_model_proposal_id)
- ->condition('filetype', 'P')
- ->execute()
- ->fetchObject();
-
- $script_filename = (!empty($abstracts_script) && !empty($abstracts_script->filename) && $abstracts_script->filename !== "NULL")
- ? $abstracts_script->filename
- : 'File not uploaded';
-
- // Download link for full project.
- $download_url = Url::fromUserInput('/custom-model/full-download/project/' . $custom_model_proposal_id);
- $download_link = Link::fromTextAndUrl('Download Custom Model', $download_url)->toString();
-
- // Compose output.
- $return_html .= '
Proposer Name: ' . $abstracts_pro->name_title . ' ' . $abstracts_pro->contributor_name . '
';
- $return_html .= '
Title of the Custom Model: ' . $abstracts_pro->project_title . '
';
- $return_html .= '
Uploaded an abstract (brief outline) of the project: ' . $abstract_filename . '
';
- $return_html .= '
Uploaded Custom Model as DWSIM Simulation File: ' . $process_filename . '
';
- $return_html .= '
Uploaded script file: ' . $script_filename . '
';
- $return_html .= $download_link;
-
- return $return_html;
-}
/**
- * AJAX callback for updating details.
+ * AJAX callback: returns the detail wrapper to update on proposal selection.
*/
- public function ajaxCustomModelDetailsCallback(array &$form, FormStateInterface $form_state) {
- return $form['ajax-selected-custom-model-wrapper'];
- // $response = new AjaxResponse();
- // $proposal_id = $form_state->getValue('custom_model_proposals');
-
- // if ($proposal_id != 0) {
- // $html = _custom_model_details($proposal_id);
- // $response->addCommand(new HtmlCommand('#ajax_selected_custom_model', $html));
-
- // // Re-render action select box with updated options if needed.
- // $form['custom_model_actions']['#options'] = this->_bulk_list_custom_model_actions();
- // $actions_rendered = \Drupal::service('renderer')->render($form['custom_model_actions']);
- // $response->addCommand(new ReplaceCommand('#ajax_selected_custom_model_action', $actions_rendered));
- // }
- // else {
- // $response->addCommand(new HtmlCommand('#ajax_selected_custom_model', ''));
- // }
-
- // return $response;
+ public function ajax_bulk_custom_model_abstract_details_callback(array &$form, FormStateInterface $form_state) {
+ return $form['update_custom_model'];
}
-
- function _bulk_list_custom_model_actions() {
- return [
- 0 => 'Please select...',
- 1 => 'Approve Entire Custom Model',
- 2 => 'Resubmit Project files',
- 3 => 'Dis-Approve Entire Custom Model (This will delete Custom Model)',
- ];
- }
-
-
-
-function _bulk_list_of_custom_model_proposals() {
- $project_titles = [
- '0' => 'Please select...',
- ];
-
- $database = \Drupal::database();
-
- $query = $database->select('custom_model_proposal', 'cmp')
- ->fields('cmp')
- ->condition('is_submitted', 1)
- ->condition('approval_status', 1)
- ->orderBy('project_title', 'ASC');
-
- $results = $query->execute()->fetchAll();
-
- foreach ($results as $record) {
- $project_titles[$record->id] = $record->project_title . ' (Proposed by ' . $record->contributor_name . ')';
- }
-
- return $project_titles;
- }
/**
* {@inheritdoc}
*/
-
-public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $current_user = \Drupal::currentUser();
- $database = \Drupal::database();
- $messenger = \Drupal::messenger();
- $mailManager = \Drupal::service('plugin.manager.mail');
- $language = \Drupal::languageManager()->getDefaultLanguage();
-
- $proposal_id = $form_state->getValue('custom_model_proposals');
- $action = $form_state->getValue('custom_model_actions');
- $message_text = trim($form_state->getValue('message'));
-
- if (!$proposal_id || !$current_user->hasPermission('custom model bulk manage submission')) {
- $messenger->addError(t('Access denied or invalid proposal.'));
- return;
- }
-
- // Load proposal and user.
- $proposal = $database->select('custom_model_proposal', 'cmp')
- ->fields('cmp')
- ->condition('id', $proposal_id)
- ->execute()
- ->fetchObject();
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ $action = $form_state->getValue('custom_model_actions');
+ $message_text = trim($form_state->getValue('message') ?? '');
- if (!$proposal) {
- $messenger->addError(t('Proposal not found.'));
- return;
+ if (in_array($action, [2, 3]) && strlen($message_text) < 30) {
+ $form_state->setErrorByName('message', $this->t('Please provide a reason of at least 30 characters.'));
+ }
}
- $user = User::load($proposal->uid);
-
- if ($action == 1) {
- // Approve
- $abstracts = $database->select('custom_model_submitted_abstracts', 'a')
- ->fields('a')
- ->condition('proposal_id', $proposal_id)
- ->execute();
-
- foreach ($abstracts as $abstract) {
- $database->update('custom_model_submitted_abstracts')
- ->fields([
- 'abstract_approval_status' => 1,
- 'is_submitted' => 1,
- 'approver_uid' => $current_user->id(),
- ])
- ->condition('id', $abstract->id)
- ->execute();
-
- $database->update('custom_model_submitted_abstracts_file')
- ->fields([
- 'file_approval_status' => 1,
- 'approvar_uid' => $current_user->id(),
- ])
- ->condition('submitted_abstract_id', $abstract->id)
- ->execute();
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $proposal_id = $form_state->getValue('custom_model_proposals');
+ $action = $form_state->getValue('custom_model_actions');
+ $message_text = trim($form_state->getValue('message') ?? '');
+
+ // Access check.
+ if (!$proposal_id || !$this->currentUser->hasPermission('custom model bulk manage submission')) {
+ $this->messenger->addError($this->t('Access denied or invalid proposal.'));
+ return;
}
- $messenger->addStatus(t('Approved Custom Model project.'));
-
- // Email
- $params['subject'] = t('[!site_name][Custom Model] Your uploaded Custom Model has been approved', ['!site_name' => \Drupal::config('system.site')->get('name')]);
- $params['body'][] = t("
-Dear @name,
-
-Your uploaded abstract for the Custom Model has been approved:
-
-Title of Custom Model: @title
-
-Best Wishes,
-@site Team,
-FOSSEE, IIT Bombay", [
- '@name' => $proposal->contributor_name,
- '@title' => $proposal->project_title,
- '@site' => \Drupal::config('system.site')->get('name'),
- ]);
+ // Load proposal.
+ $proposal = $this->connection->select('custom_model_proposal', 'cmp')
+ ->fields('cmp')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
- } elseif ($action == 2) {
- // Resubmit (Pending)
- if (strlen($message_text) < 30) {
- $form_state->setErrorByName('message', t('Please mention the reason for resubmission. Minimum 30 characters required.'));
+ if (!$proposal) {
+ $this->messenger->addError($this->t('Proposal not found.'));
return;
}
- $abstracts = $database->select('custom_model_submitted_abstracts', 'a')
- ->fields('a')
- ->condition('proposal_id', $proposal_id)
- ->execute();
-
- foreach ($abstracts as $abstract) {
- $database->update('custom_model_submitted_abstracts')
- ->fields([
- 'abstract_approval_status' => 0,
- 'is_submitted' => 0,
- 'approver_uid' => $current_user->id(),
- ])
- ->condition('id', $abstract->id)
- ->execute();
-
- $database->update('custom_model_proposal')
- ->fields([
- 'is_submitted' => 0,
- 'approver_uid' => $current_user->id(),
- ])
- ->condition('id', $abstract->proposal_id)
- ->execute();
+ // Load user.
+ $user = $this->entityTypeManager->getStorage('user')->load($proposal->uid);
+ $email_to = $user ? $user->getEmail() : '';
- $database->update('custom_model_submitted_abstracts_file')
- ->fields([
- 'file_approval_status' => 0,
- 'approvar_uid' => $current_user->id(),
- ])
- ->condition('submitted_abstract_id', $abstract->id)
+ if ($action == 1) {
+ // Approve all submitted abstracts and their files.
+ $abstracts = $this->connection->select('custom_model_submitted_abstracts', 'a')
+ ->fields('a')
+ ->condition('proposal_id', $proposal_id)
->execute();
- }
-
- $messenger->addStatus(t('Resubmit the project files'));
-
- $params['subject'] = t('[!site_name][Custom Model] Your uploaded Custom Model has been marked as pending', ['!site_name' => \Drupal::config('system.site')->get('name')]);
- $params['body'][] = t("
-Dear @name,
-Kindly resubmit the project files for the project: @title.
+ foreach ($abstracts as $abstract) {
+ $this->connection->update('custom_model_submitted_abstracts')
+ ->fields([
+ 'abstract_approval_status' => 1,
+ 'is_submitted' => 1,
+ 'approver_uid' => $this->currentUser->id(),
+ ])
+ ->condition('id', $abstract->id)
+ ->execute();
+
+ $this->connection->update('custom_model_submitted_abstracts_file')
+ ->fields([
+ 'file_approval_status' => 1,
+ 'approvar_uid' => $this->currentUser->id(),
+ ])
+ ->condition('submitted_abstract_id', $abstract->id)
+ ->execute();
+ }
+
+ $this->messenger->addStatus($this->t('Approved Custom Model project.'));
+
+ // Send approval email using MailService.
+ if ($email_to) {
+ $subject = $this->t('[Custom Model] Your uploaded Custom Model has been approved');
+ $body = $this->t("Dear @name,\n\nYour uploaded abstract for the Custom Model has been approved:\n\nTitle of Custom Model: @title\n\nBest Wishes,\nFOSSEE, IIT Bombay", [
+ '@name' => $proposal->contributor_name,
+ '@title' => $proposal->project_title,
+ ]);
+ $this->mailService->sendNotification('custom_model', 'custom_model_abstract_approved', $email_to, $subject, [$body]);
+ }
-Reason for dis-approval: @reason
+ }
+ elseif ($action == 2) {
+ // Resubmit: mark abstracts and files as pending.
+ $abstracts = $this->connection->select('custom_model_submitted_abstracts', 'a')
+ ->fields('a')
+ ->condition('proposal_id', $proposal_id)
+ ->execute();
-Best Wishes,
-@site Team,
-FOSSEE, IIT Bombay", [
- '@name' => $proposal->contributor_name,
- '@title' => $proposal->project_title,
- '@reason' => $message_text,
- '@site' => \Drupal::config('system.site')->get('name'),
- ]);
+ foreach ($abstracts as $abstract) {
+ $this->connection->update('custom_model_submitted_abstracts')
+ ->fields([
+ 'abstract_approval_status' => 0,
+ 'is_submitted' => 0,
+ 'approver_uid' => $this->currentUser->id(),
+ ])
+ ->condition('id', $abstract->id)
+ ->execute();
+
+ $this->connection->update('custom_model_proposal')
+ ->fields([
+ 'is_submitted' => 0,
+ 'approver_uid' => $this->currentUser->id(),
+ ])
+ ->condition('id', $abstract->proposal_id)
+ ->execute();
+
+ $this->connection->update('custom_model_submitted_abstracts_file')
+ ->fields([
+ 'file_approval_status' => 0,
+ 'approvar_uid' => $this->currentUser->id(),
+ ])
+ ->condition('submitted_abstract_id', $abstract->id)
+ ->execute();
+ }
+
+ $this->messenger->addStatus($this->t('Resubmit the project files'));
+
+ // Send resubmit email.
+ if ($email_to) {
+ $subject = $this->t('[Custom Model] Your uploaded Custom Model has been marked as pending');
+ $body = $this->t("Dear @name,\n\nKindly resubmit the project files for the project: @title.\n\nReason: @reason\n\nBest Wishes,\nFOSSEE, IIT Bombay", [
+ '@name' => $proposal->contributor_name,
+ '@title' => $proposal->project_title,
+ '@reason' => $message_text,
+ ]);
+ $this->mailService->sendNotification('custom_model', 'custom_model_abstract_resubmit', $email_to, $subject, [$body]);
+ }
- } elseif ($action == 3) {
- // Disapprove/Delete
- if (strlen($message_text) < 30) {
- $form_state->setErrorByName('message', t('Please mention the reason for disapproval. Minimum 30 characters required.'));
- return;
}
+ elseif ($action == 3) {
+ // Disapprove and delete.
+ if (!$this->currentUser->hasPermission('custom model bulk delete abstract')) {
+ $this->messenger->addError($this->t('You do not have permission to delete this Custom Model project.'));
+ return;
+ }
+
+ if (custom_model_abstract_delete_project($proposal_id)) {
+ $this->messenger->addStatus($this->t('Disapproved and Deleted Entire Custom Model project.'));
+
+ // Send disapproval email.
+ if ($email_to) {
+ $subject = $this->t('[Custom Model] Your uploaded Custom Model has been marked as dis-approved');
+ $body = $this->t("Dear @name,\n\nYour uploaded Custom Model files for the Custom Model Title: @title have been marked as dis-approved.\n\nReason: @reason\n\nBest Wishes,\nFOSSEE, IIT Bombay", [
+ '@name' => $proposal->contributor_name,
+ '@title' => $proposal->project_title,
+ '@reason' => $message_text,
+ ]);
+ $this->mailService->sendNotification('custom_model', 'custom_model_abstract_disapproved', $email_to, $subject, [$body]);
+ }
+ }
+ else {
+ $this->messenger->addError($this->t('Error deleting the Custom Model project.'));
+ }
+ }
+ }
- if (!$current_user->hasPermission('custom model bulk delete abstract')) {
- $messenger->addError(t('You do not have permission to delete this Custom Model project.'));
- return;
+ /**
+ * Returns the proposal detail HTML for AJAX rendering.
+ */
+ private function _custom_model_details($custom_model_proposal_id) {
+ if (!$custom_model_proposal_id) {
+ return '';
}
- if (custom_model_abstract_delete_project($proposal_id)) {
- $messenger->addStatus(t('Disapproved and Deleted Entire Custom Model project.'));
+ $abstracts_pro = $this->connection->select('custom_model_proposal', 'cmp')
+ ->fields('cmp')
+ ->condition('id', $custom_model_proposal_id)
+ ->execute()
+ ->fetchObject();
- $params['subject'] = t('[!site_name][Custom Model] Your uploaded Custom Model has been marked as dis-approved', ['!site_name' => \Drupal::config('system.site')->get('name')]);
- $params['body'][] = t("
-Dear @name,
+ if (!$abstracts_pro) {
+ return '';
+ }
-Your uploaded Custom Model files for the Custom Model Title: @title have been marked as dis-approved.
+ // Abstract file (type A).
+ $abstracts_pdf = $this->connection->select('custom_model_submitted_abstracts_file', 'pdf')
+ ->fields('pdf')
+ ->condition('proposal_id', $custom_model_proposal_id)
+ ->condition('filetype', 'A')
+ ->execute()
+ ->fetchObject();
+
+ $abstract_filename = (!empty($abstracts_pdf) && !empty($abstracts_pdf->filename) && $abstracts_pdf->filename !== "NULL")
+ ? $abstracts_pdf->filename
+ : 'File not uploaded';
+
+ // Simulation file (type S).
+ $abstracts_process = $this->connection->select('custom_model_submitted_abstracts_file', 'proc')
+ ->fields('proc')
+ ->condition('proposal_id', $custom_model_proposal_id)
+ ->condition('filetype', 'S')
+ ->execute()
+ ->fetchObject();
+
+ $process_filename = (!empty($abstracts_process) && !empty($abstracts_process->filename) && $abstracts_process->filename !== "NULL")
+ ? $abstracts_process->filename
+ : 'File not uploaded';
+
+ // Script file (type P).
+ $abstracts_script = $this->connection->select('custom_model_submitted_abstracts_file', 'script')
+ ->fields('script')
+ ->condition('proposal_id', $custom_model_proposal_id)
+ ->condition('filetype', 'P')
+ ->execute()
+ ->fetchObject();
+
+ $script_filename = (!empty($abstracts_script) && !empty($abstracts_script->filename) && $abstracts_script->filename !== "NULL")
+ ? $abstracts_script->filename
+ : 'File not uploaded';
+
+ $download_link = Link::fromTextAndUrl(
+ $this->t('Download Custom Model'),
+ Url::fromUserInput('/custom-model/full-download/project/' . $custom_model_proposal_id)
+ )->toString();
+
+ $html = '
Proposer Name: ' . $abstracts_pro->name_title . ' ' . $abstracts_pro->contributor_name . '
';
+ $html .= '
Title of the Custom Model: ' . $abstracts_pro->project_title . '
';
+ $html .= '
Uploaded an abstract (brief outline) of the project: ' . $abstract_filename . '
';
+ $html .= '
Uploaded Custom Model as DWSIM Simulation File: ' . $process_filename . '
';
+ $html .= '
Uploaded script file: ' . $script_filename . '
';
+ $html .= $download_link;
+
+ return $html;
+ }
+
+ /**
+ * Returns the list of proposals eligible for bulk review.
+ */
+ private function _bulk_list_of_custom_model_proposals() {
+ $project_titles = ['0' => $this->t('Please select...')];
-Reason for dis-approval: @reason
+ $results = $this->connection->select('custom_model_proposal', 'cmp')
+ ->fields('cmp')
+ ->condition('is_submitted', 1)
+ ->condition('approval_status', 1)
+ ->orderBy('project_title', 'ASC')
+ ->execute()
+ ->fetchAll();
-Best Wishes,
-@site Team,
-FOSSEE, IIT Bombay", [
- '@name' => $proposal->contributor_name,
- '@title' => $proposal->project_title,
- '@reason' => $message_text,
- '@site' => \Drupal::config('system.site')->get('name'),
- ]);
- } else {
- $messenger->addError(t('Error deleting the Custom Model project.'));
+ foreach ($results as $record) {
+ $project_titles[$record->id] = $record->project_title . ' (Proposed by ' . $record->contributor_name . ')';
}
- }
- // Send email
- if (!empty($params)) {
- $mailManager->mail('custom_model', 'standard', $user->getEmail(), $language->getId(), [
- 'subject' => $params['subject'],
- 'body' => $params['body'],
- ], NULL, TRUE);
+ return $project_titles;
}
-}
+ /**
+ * Returns the available bulk actions.
+ */
+ private function _bulk_list_custom_model_actions() {
+ return [
+ 0 => $this->t('Please select...'),
+ 1 => $this->t('Approve Entire Custom Model'),
+ 2 => $this->t('Resubmit Project files'),
+ 3 => $this->t('Dis-Approve Entire Custom Model (This will delete Custom Model)'),
+ ];
}
-
+}
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelIdeaProposalForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelIdeaProposalForm.php
index 4a9e329..8a10e35 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelIdeaProposalForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelIdeaProposalForm.php
@@ -12,19 +12,46 @@
use Drupal\Core\Render\Element;
use Drupal\Core\Link;
use Drupal\Core\Url;
-use Drupal\Core\Routing\TrustedRedirectResponse;
-use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\StringTranslation\StringTranslationTrait;
-use Drupal\Core\Database\Database;
+use Drupal\Core\Database\Connection;
use Drupal\Core\Messenger\MessengerInterface;
-use Drupal\Core\Mail\MailManager;
-use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\DependencyInjection\ContainerInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\custom_model\Services\CustomModelGlobalfunction;
class CustomModelIdeaProposalForm extends FormBase {
+ protected $connection;
+ protected $messenger;
+ protected $currentUser;
+ protected $configFactory;
+ protected $globalFunction;
+
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ ConfigFactoryInterface $configFactory,
+ CustomModelGlobalfunction $globalFunction
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->configFactory = $configFactory;
+ $this->globalFunction = $globalFunction;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('config.factory'),
+ $container->get('custom_model_global')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -33,29 +60,12 @@ public function getFormId() {
}
public function buildForm(array $form,FormStateInterface $form_state, $no_js_use = NULL) {
- $user = \Drupal::currentUser();
- /************************ start approve book details ************************/
- // if ($user->uid == 0) {
- // $msg = \Drupal::messenger()->addMessage(t('It is mandatory to ' . l('login', 'user') . ' on this website to access the custom model idea proposal form. If you are new user please create a new account first.'), 'error');
- // drupal_goto('user');
- // return $msg;
+ $user = $this->currentUser;
if ($user->isAnonymous()) {
- // $msg = \Drupal::messenger()->addError(t('This is an error message, red in color'));
- $url = Link::fromTextAndUrl(t('login'), Url::fromRoute('user.page'))->toString();
-
- $msg = \Drupal::messenger()->addmessage(t('It is mandatory to ' . Link::fromTextAndUrl(t('login'), Url::fromRoute('user.page'))->toString() . ' on this website to access the lab proposal form. If you are new user please create a new account first.'));
-
- // RedirectResponse('lab-migration-project');
- // \Drupal::RedirectResponse('user');
- // $redirect = new RedirectResponse($url);
- // $redirect->send();
- // return $msg;
- // Redirect to the login page
- $response = new RedirectResponse(Url::fromRoute('user.page')->toString());
-
- $response->send();
- return $msg;
- } //$user->uid == 0
+ $this->messenger->addError($this->t('Please login to access the idea proposal form.'));
+ $form_state->setRedirectUrl(Url::fromRoute('user.page'));
+ return [];
+ }
/*$query = \Drupal::database()->select('custom_model_idea_proposal');
$query->fields('custom_model_idea_proposal');
$query->condition('uid', $user->uid);
@@ -122,7 +132,7 @@ public function buildForm(array $form,FormStateInterface $form_state, $no_js_use
'#type' => 'textfield',
'#title' => $this->t('Email'),
'#size' => 30,
- '#value' => $user ? $user->getEmail() : '',
+ '#value' => $user ? $user->getEmail() : '',
'#disabled' => TRUE,
];
$form['university'] = [
@@ -252,7 +262,7 @@ public function buildForm(array $form,FormStateInterface $form_state, $no_js_use
$form['samplefile']['reference_file'] = [
'#type' => 'file',
'#size' => 48,
- '#description' => $this->t('Any file/document to be used as a reference to understand and create the custom model. Multiple files can be zipped together as a single file.') . '
' . $this->t('
Allowed file extensions: ') .\Drupal::config('custom_model.settings') ->get('idea_proposal_resource_upload_extensions', '') . ' ',
+ '#description' => $this->t('Any file/document to be used as a reference to understand and create the custom model. Multiple files can be zipped together as a single file.') . '
' . $this->t('
Allowed file extensions: ') . $this->configFactory->get('custom_model.settings')->get('idea_proposal_resource_upload_extensions', '') . ' ',
];
$form['term_condition'] = [
'#type' => 'checkboxes',
@@ -381,7 +391,7 @@ public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface
$allowed_extensions_str = '';
switch ($file_type) {
case 'S':
- $allowed_extensions_str = \Drupal::config('custom_model.settings')->get('lab_migration_syllabus_file_extensions');
+ $allowed_extensions_str = $this->configFactory->get('custom_model.settings')->get('lab_migration_syllabus_file_extensions');
break;
} //$file_type
$allowed_extensions = explode(',', $allowed_extensions_str);
@@ -402,13 +412,6 @@ public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface
}
public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- // $root_path = \Drupal::service("custom_model_global")->custom_model_ideas_files_path();
- // if (!$user->uid) {
- // \Drupal::messenger()->addMessage('It is mandatory to login on this website to access the proposal form', 'error');
- // return;
- // } //!$user->uid
- /* inserting the user proposal */
if ($form_state->getValue(['department']) == 'Others') {
$form_state->setValue(['department'], $form_state->getValue(['other_department']));
}
@@ -460,7 +463,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
)";
$args = [
// 'uid' => $user->get('uid')->value,
- 'uid' => \Drupal::currentUser()->id(),
+ 'uid' => $this->currentUser->id(),
":approver_uid" => 0,
":name_title" => $v['name_title'],
@@ -477,14 +480,8 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":directory_name" => $directory_name,
":creation_date" => time(),
];
- // $proposal_id = \Drupal::database()->query($result, $args, [
- // 'return' => Database::RETURN_INSERT_ID
- $result1 = \Drupal::database()->query($result, $args, [
- 'return' => Database::RETURN_INSERT_ID
- ]);
- // ]);
- //var_dump($args);die;
- $root_path = \Drupal::service('custom_model_global')->custom_model_path();
+ $result1 = $this->connection->query($result, $args);
+ $root_path = $this->globalFunction->custom_model_path();
$dest_path = $directory_name . '/';
$dest_path1 = $root_path . $dest_path;
@@ -498,9 +495,9 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
/* checking file type */
//$file_type = 'S';
if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- \Drupal::messenger()->addMessage(t("Error uploading file. File !filename already exists.", [
- '!filename' => $_FILES['files']['name'][$file_form_name]
- ]), 'error');
+ $this->messenger->addError($this->t('Error uploading file. File @filename already exists.', [
+ '@filename' => $_FILES['files']['name'][$file_form_name],
+ ]));
//unlink($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]);
} //file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
/* uploading file */
@@ -510,18 +507,18 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":reference_file" => $_FILES['files']['name'][$file_form_name],
":id" => $proposal_id,
];
- $updateresult = \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' uploaded successfully.', 'status');
- } //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
+ $updateresult = $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' uploaded successfully.');
+ }
else {
- \Drupal::messenger()->addMessage('Error uploading file : ' . $dest_path . $file_name, 'error');
+ $this->messenger->addError($this->t('Error uploading file: @path', ['@path' => $dest_path . $file_name]));
}
} //$file_name
} //$_FILES['files']['name'] as $file_form_name => $file_name
- if (!$proposal_id) {
- \Drupal::messenger()->addMessage(t('Error receiving your proposal. Please try again.'), 'error');
+ if (!$result1) {
+ $this->messenger->addError($this->t('Error receiving your proposal. Please try again.'));
return;
- } //!$proposal_id
+ }
/* sending email */
// $email_to = $user->mail;
// $form = variable_get('custom_model_from_email', '');
@@ -541,12 +538,8 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
// if (!drupal_mail('custom_model', 'custom_model_idea_proposal_received', $email_to, user_preferred_language($user), $params, $form, TRUE)) {
// \Drupal::messenger()->addMessage('Error sending email message.', 'error');
// }
- \Drupal::messenger()->addMessage(t('We have received your DWSIM Custom Model proposal.'), 'status');
- // drupal_goto('');
- $response = new RedirectResponse(Url::fromRoute('
')->toString());
-
- // Send the redirect response
- $response->send();
+ $this->messenger->addStatus($this->t('We have received your DWSIM Custom Model proposal.'));
+ $form_state->setRedirectUrl(Url::fromRoute(''));
}
}
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalApprovalForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalApprovalForm.php
index cf2ac4c..70b897e 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalApprovalForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalApprovalForm.php
@@ -1,28 +1,100 @@
connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $route_match;
+ $this->entityTypeManager = $entity_type_manager;
+ $this->mailService = $mail_service;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match'),
+ $container->get('entity_type.manager'),
+ $container->get('custom_model.mail_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -30,134 +102,117 @@ public function getFormId() {
return 'custom_model_proposal_approval_form';
}
- public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-$proposal_id = (int) $route_match->getParameter('id');
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
- $query = \Drupal::database()->select('custom_model_proposal');
+ $query = $this->connection->select('custom_model_proposal');
$query->fields('custom_model_proposal');
$query->condition('id', $proposal_id);
$proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- } //$proposal_data = $proposal_q->fetchObject()
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- $url = Url::fromUri('internal:/custom-model/manage-proposal/approve/')->toString();
- // \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
- return;
- }
- } //$proposal_q
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- $url = Url::fromUri('internal:/custom-model/manage-proposal/approve/')->toString();
+
+ $proposal_data = $proposal_q ? $proposal_q->fetchObject() : FALSE;
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
return;
}
+
if ($proposal_data->contact_no == "NULL" || $proposal_data->contact_no == "") {
$contact_no = "Not Entered";
- } //$proposal_data->project_guide_email_id == NULL
- else {
+ } else {
$contact_no = $proposal_data->contact_no;
}
$form['contributor_name'] = [
'#type' => 'item',
- // '#markup' => l($proposal_data->name_title . ' ' . $proposal_data->contributor_name, 'user/' . $proposal_data->uid),
- '#markup' => Link::fromTextAndUrl($proposal_data->name_title . ' ' . $proposal_data->contributor_name,Url::fromUri('internal:/user/' . $proposal_data->uid)
- )->toString(),
- '#title' => t('Student name'),
+ '#markup' => Link::fromTextAndUrl(
+ $proposal_data->name_title . ' ' . $proposal_data->contributor_name,
+ Url::fromUri('internal:/user/' . $proposal_data->uid)
+ )->toString(),
+ '#title' => $this->t('Student name'),
];
+
+ $user_entity = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
$form['student_email_id'] = [
- '#title' => t('Student Email'),
'#type' => 'item',
- // '#markup' => User::load($proposal_data->uid)->mail,
- '#markup' => User::load($proposal_data->uid)->getEmail(),
-
- '#title' => t('Email'),
+ '#markup' => $user_entity ? $user_entity->getEmail() : '',
+ '#title' => $this->t('Email'),
];
-
+
$form['contributor_contact_no'] = [
- '#title' => t('Contact No.'),
+ '#title' => $this->t('Contact No.'),
'#type' => 'item',
'#markup' => $contact_no,
];
$form['university'] = [
'#type' => 'item',
'#markup' => $proposal_data->university,
- '#title' => t('University/Institute'),
+ '#title' => $this->t('University/Institute'),
];
$form['department'] = [
'#type' => 'item',
'#markup' => $proposal_data->department,
- '#title' => t('Department/Branch'),
+ '#title' => $this->t('Department/Branch'),
];
$form['country'] = [
'#type' => 'item',
'#markup' => $proposal_data->country,
- '#title' => t('Country'),
+ '#title' => $this->t('Country'),
];
$form['all_state'] = [
'#type' => 'item',
'#markup' => $proposal_data->state,
- '#title' => t('State'),
+ '#title' => $this->t('State'),
];
$form['city'] = [
'#type' => 'item',
'#markup' => $proposal_data->city,
- '#title' => t('City'),
+ '#title' => $this->t('City'),
];
$form['pincode'] = [
'#type' => 'item',
'#markup' => $proposal_data->pincode,
- '#title' => t('Pincode/Postal code'),
+ '#title' => $this->t('Pincode/Postal code'),
];
$form['version'] = [
'#type' => 'item',
'#markup' => $proposal_data->version,
- '#title' => t('DWSIM Version used'),
+ '#title' => $this->t('DWSIM Version used'),
];
$form['project_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->project_title,
- '#title' => t('Title of the Custom Model'),
+ '#title' => $this->t('Title of the Custom Model'),
];
$form['script_used'] = [
'#type' => 'item',
'#markup' => $proposal_data->script_used,
- '#title' => t('Script used to create the Custom Model'),
+ '#title' => $this->t('Script used to create the Custom Model'),
];
-if (!empty($proposal_data->samplefilepath) && $proposal_data->samplefilepath !== 'NULL') {
- $str = substr($proposal_data->samplefilepath, strrpos($proposal_data->samplefilepath, '/'));
- $resource_file = ltrim($str, '/');
-
- $form['samplefilepath'] = [
- '#type' => 'item',
- '#title' => $this->t('Uploaded Abstract of Custom Model'),
- '#markup' => Link::fromTextAndUrl(
- $resource_file,
- Url::fromUri('internal:/custom-model/download/resource-file/' . $proposal_id)
- )->toString(),
-
- ];
-} else {
- $form['samplefilepath'] = [
- '#type' => 'item',
- '#title' => $this->t('Uploaded Abstract of Custom Model'),
- '#markup' => "Not uploaded ",
- ];
-}
+ if (!empty($proposal_data->samplefilepath) && $proposal_data->samplefilepath !== 'NULL') {
+ $str = substr($proposal_data->samplefilepath, strrpos($proposal_data->samplefilepath, '/'));
+ $resource_file = ltrim($str, '/');
+
+ $form['samplefilepath'] = [
+ '#type' => 'item',
+ '#title' => $this->t('Uploaded Abstract of Custom Model'),
+ '#markup' => Link::fromTextAndUrl(
+ $resource_file,
+ Url::fromUri('internal:/custom-model/download/resource-file/' . $proposal_id)
+ )->toString(),
+ ];
+ } else {
+ $form['samplefilepath'] = [
+ '#type' => 'item',
+ '#title' => $this->t('Uploaded Abstract of Custom Model'),
+ '#markup' => "Not uploaded ",
+ ];
+ }
$form['approval'] = [
'#type' => 'radios',
- '#title' => t('Select an action on the Custom model proposal'),
+ '#title' => $this->t('Select an action on the Custom model proposal'),
'#options' => [
'1' => 'Approve',
'2' => 'Disapprove',
@@ -166,9 +221,9 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['message'] = [
'#type' => 'textarea',
- '#title' => t('Reason for disapproval'),
+ '#title' => $this->t('Reason for disapproval'),
'#attributes' => [
- 'placeholder' => t('Enter reason for disapproval in minimum 30 characters '),
+ 'placeholder' => $this->t('Enter reason for disapproval in minimum 30 characters '),
'cols' => 50,
'rows' => 4,
],
@@ -176,137 +231,86 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'visible' => [
':input[name="approval"]' => [
'value' => '2'
- ]
]
- ],
+ ]
+ ],
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
+ '#value' => $this->t('Submit'),
];
$form['cancel'] = [
'#type' => 'item',
- // '#markup' => l(t('Cancel'), 'custom-model/manage-proposal'),
'#markup' => Link::fromTextAndUrl(
- $this->t('Cancel'),
- Url::fromUri('internal:/custom-model/manage-proposal/pending'))->toString(),
+ $this->t('Cancel'),
+ Url::fromUri('internal:/custom-model/manage-proposal/pending')
+ )->toString(),
];
return $form;
}
- public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- if ($form_state->getValue(['approval']) == 2) {
- if ($form_state->getValue(['message']) == '') {
- $form_state->setErrorByName('message', t('Reason for disapproval could not be empty'));
- } //$form_state['values']['message'] == ''
- } //$form_state['values']['approval'] == 2
+ public function validateForm(array &$form, FormStateInterface $form_state) {
+ if ($form_state->getValue('approval') == 2) {
+ if (empty($form_state->getValue('message'))) {
+ $form_state->setErrorByName('message', $this->t('Reason for disapproval could not be empty'));
+ }
+ }
}
- public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
- $proposal_id = (int) $route_match->getParameter('id');
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
- $query = \Drupal::database()->select('custom_model_proposal');
+ $query = $this->connection->select('custom_model_proposal');
$query->fields('custom_model_proposal');
$query->condition('id', $proposal_id);
$proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- } //$proposal_data = $proposal_q->fetchObject()
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- $url = Url::fromRoute('custom_model.proposal_pending')->toString();
-
- return;
- }
- } //$proposal_q
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- $url = Url::fromRoute('custom_model.proposal_pending')->toString();
- // \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
+
+ $proposal_data = $proposal_q ? $proposal_q->fetchObject() : FALSE;
+
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirectUrl(Url::fromRoute('custom_model.proposal_pending'));
return;
}
- if ($form_state->getValue(['approval']) == 1) {
+
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
+ $email_to = $user_data ? $user_data->getEmail() : '';
+
+ if ($form_state->getValue('approval') == 1) {
$query = "UPDATE {custom_model_proposal} SET approver_uid = :uid, approval_date = :date, approval_status = 1 WHERE id = :proposal_id";
$args = [
- ":uid" => $user->id(),
+ ":uid" => $this->currentUser->id(),
+ ":date" => time(),
+ ":proposal_id" => $proposal_id,
+ ];
+ $this->connection->query($query, $args);
+
+ /* sending email using MailService */
+ if ($email_to) {
+ $this->mailService->sendApprovalMail('custom_model', $proposal_id, $proposal_data->uid, $email_to);
+ }
+
+ $this->messenger->addStatus($this->t('Custom Model proposal No. @id approved. User has been notified of the approval.', ['@id' => $proposal_id]));
+ $form_state->setRedirectUrl(Url::fromRoute('custom_model.proposal_pending'));
+
+ } elseif ($form_state->getValue('approval') == 2) {
+ $query = "UPDATE {custom_model_proposal} SET approver_uid = :uid, approval_date = :date, approval_status = 2, dissapproval_reason = :dissapproval_reason WHERE id = :proposal_id";
+ $args = [
+ ":uid" => $this->currentUser->id(),
":date" => time(),
+ ":dissapproval_reason" => $form_state->getValue('message'),
":proposal_id" => $proposal_id,
];
- \Drupal::database()->query($query, $args);
- /* sending email */
- // $user_data = user_load($proposal_data->uid);
- // $email_to = $user_data->mail;
- // $from = variable_get('custom_model_from_email', '');
- // $bcc = $user->mail . ', ' . variable_get('custom_model_emails', '');
- // $cc = variable_get('custom_model_cc_emails', '');
- // $params['custom_model_proposal_approved']['proposal_id'] = $proposal_id;
- // $params['custom_model_proposal_approved']['user_id'] = $proposal_data->uid;
- // $params['custom_model_proposal_approved']['headers'] = [
- // 'From' => $from,
- // 'MIME-Version' => '1.0',
- // 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- // 'Content-Transfer-Encoding' => '8Bit',
- // 'X-Mailer' => 'Drupal',
- // 'Cc' => $cc,
- // 'Bcc' => $bcc,
- // ];
- // if (!drupal_mail('custom_mmodel', 'custom_model_proposal_approved', $email_to, language_default(), $params, $from, TRUE)) {
- // \Drupal::messenger()->addMessage('Error sending email message.', 'error');
- // }
- \Drupal::messenger()->addMessage('Custom Model proposal No. ' . $proposal_id . ' approved. User has been notified of the approval.', 'status');
- // drupal_goto('custom-model/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('custom_model.proposal_pending')->toString());
-$response->send();
-
-
- // return;
- } //$form_state['values']['approval'] == 1
- else {
- if ($form_state->getValue(['approval']) == 2) {
- $query = "UPDATE {custom_model_proposal} SET approver_uid = :uid, approval_date = :date, approval_status = 2, dissapproval_reason = :dissapproval_reason WHERE id = :proposal_id";
- $args = [
- ":uid" => $user->uid,
- ":date" => time(),
- ":dissapproval_reason" => $form_state->getValue(['message']),
- ":proposal_id" => $proposal_id,
- ];
- $result = \Drupal::database()->query($query, $args);
- /* sending email */
- // $user_data = user_load($proposal_data->uid);
- // $email_to = $user_data->mail;
- // $from = variable_get('custom_model_from_email', '');
- // $bcc = $user->mail . ', ' . variable_get('custom_model_emails', '');
- // $cc = variable_get('custom_model_cc_emails', '');
- // $params['custom_model_proposal_disapproved']['proposal_id'] = $proposal_id;
- // $params['custom_model_proposal_disapproved']['user_id'] = $proposal_data->uid;
- // $params['custom_model_proposal_disapproved']['headers'] = [
- // 'From' => $from,
- // 'MIME-Version' => '1.0',
- // 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- // 'Content-Transfer-Encoding' => '8Bit',
- // 'X-Mailer' => 'Drupal',
- // 'Cc' => $cc,
- // 'Bcc' => $bcc,
- // ];
- // if (!drupal_mail('custom_model', 'custom_model_proposal_disapproved', $email_to, language_default(), $params, $from, TRUE)) {
- // \Drupal::messenger()->addMessage('Error sending email message.', 'error');
- // }
- \Drupal::messenger()->addMessage('Custom Model proposal No. ' . $proposal_id . ' dis-approved. User has been notified of the dis-approval.', 'error');
- // drupal_goto('custom-model/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('custom_model.proposal_pending')->toString());
-$response->send();
-
- // return;
+ $this->connection->query($query, $args);
+
+ /* sending email using MailService */
+ if ($email_to) {
+ $this->mailService->sendRejectionMail('custom_model', $proposal_id, $proposal_data->uid, $email_to, $form_state->getValue('message'));
}
- } //$form_state['values']['approval'] == 2
+
+ $this->messenger->addError($this->t('Custom Model proposal No. @id dis-approved. User has been notified of the dis-approval.', ['@id' => $proposal_id]));
+ $form_state->setRedirectUrl(Url::fromRoute('custom_model.proposal_pending'));
+ }
}
}
-
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalEditForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalEditForm.php
index e75b803..124fabf 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalEditForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalEditForm.php
@@ -13,17 +13,45 @@
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;
use Drupal\Core\Link;
-use Drupal\user\Entity\User;
-use Symfony\Component\HttpFoundation\Response;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\Config\ConfigFactoryInterface;
-use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\DependencyInjection\ContainerInterface;
-use Drupal\Core\Mail\MailManager;
-use Drupal\Core\Session\AccountProxy;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class CustomModelProposalEditForm extends FormBase {
+ protected $connection;
+ protected $messenger;
+ protected $currentUser;
+ protected $routeMatch;
+ protected $entityTypeManager;
+
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ RouteMatchInterface $routeMatch,
+ EntityTypeManagerInterface $entityTypeManager
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $routeMatch;
+ $this->entityTypeManager = $entityTypeManager;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match'),
+ $container->get('entity_type.manager')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -32,36 +60,17 @@ public function getFormId() {
}
public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-$proposal_id = (int) $route_match->getParameter('id');
-
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {custom_model_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- } //$proposal_data = $proposal_q->fetchObject()
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- $url = Url::fromUri('internal:/custom-model/manage-proposal/edit/')->toString();
-
- return;
- }
- } //$proposal_q
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- $url = Url::fromUri('internal:/custom-model/manage-proposal/edit/')->toString();
- return;
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
+ $proposal_data = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ return [];
}
- $user_data = User::load($proposal_data->uid);
+ $user_data = $this->entityTypeManager->getStorage('user')->load($proposal_data->uid);
$form['name_title'] = [
'#type' => 'select',
'#title' => t('Title'),
@@ -305,32 +314,15 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
}
public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
- $proposal_id = (int) $route_match->getParameter('id');
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- } //$proposal_data = $proposal_q->fetchObject()
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- return new RedirectResponse('/custom-model/manage-proposal/all');
- // return;
- }
- } //$proposal_q
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
+ $proposal_data = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
return new RedirectResponse('/custom-model/manage-proposal/all');
-
- return;
}
/* delete proposal */
if ($form_state->getValue(['delete_proposal']) == 1) {
@@ -354,17 +346,14 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
// if (!drupal_mail('custom_model', 'custom_model_proposal_deleted', $email_to, user_preferred_language($user), $params, $from, TRUE)) {
// \Drupal::messenger()->addMessage('Error sending email message.', 'error');
// }
- \Drupal::messenger()->addMessage(t('Custom model proposal has been deleted.'), 'status');
+ $this->messenger->addStatus($this->t('Custom model proposal has been deleted.'));
if (\Drupal::service("custom_model_global")->cm_rrmdir_project($proposal_id) == TRUE) {
- $query = \Drupal::database()->delete('custom_model_proposal');
- $query->condition('id', $proposal_id);
- $num_deleted = $query->execute();
- \Drupal::messenger()->addMessage(t('Proposal Deleted'), 'status');
- // drupal_goto('custom-model/manage-proposal');
+ $this->connection->delete('custom_model_proposal')
+ ->condition('id', $proposal_id)
+ ->execute();
+ $this->messenger->addStatus($this->t('Proposal Deleted'));
return new RedirectResponse('/custom-model/manage-proposal/all');
-
- return;
- } //rrmdir_project($proposal_id) == TRUE
+ }
} //$form_state['values']['delete_proposal'] == 1
/* update proposal */
$v = $form_state->getValues();
@@ -404,14 +393,9 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
':samplefilepath' => $samplefilepath,
':proposal_id' => $proposal_id,
];
- $result = \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage(t('Proposal Updated'), 'status');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('custom_model.proposal_all')->toString());
-
- // // // Send the redirect response
- $response->send();
-
+ $result = $this->connection->query($query, $args);
+ $this->messenger->addStatus($this->t('Proposal Updated'));
+ $form_state->setRedirectUrl(Url::fromRoute('custom_model.proposal_all'));
}
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalForm.php
index 5491df9..ad281c8 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalForm.php
@@ -12,20 +12,42 @@
use Drupal\Core\Render\Element;
use Drupal\Core\Link;
use Drupal\Core\Url;
-use Drupal\Core\Routing\TrustedRedirectResponse;
-use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\StringTranslation\StringTranslationTrait;
-use Drupal\Core\Database\Database;
+use Drupal\Core\Database\Connection;
use Drupal\Core\Messenger\MessengerInterface;
-use Drupal\Core\Mail\MailManager;
-use Drupal\user\Entity\User;
-use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CustomModelProposalForm extends FormBase {
+ protected $connection;
+ protected $messenger;
+ protected $currentUser;
+ protected $configFactory;
+
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ ConfigFactoryInterface $configFactory
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->configFactory = $configFactory;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('config.factory')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -34,34 +56,25 @@ public function getFormId() {
}
public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
- /************************ start approve book details ************************/
+ $user = $this->currentUser;
if ($user->isAnonymous()) {
- // $msg = \Drupal::messenger()->addError(t('This is an error message, red in color'));
- $url = Link::fromTextAndUrl(t('login'), Url::fromRoute('user.page'))->toString();
- $msg = \Drupal::messenger()->addmessage(t('It is mandatory to ' . Link::fromTextAndUrl(t('login'), Url::fromRoute('user.page'))->toString() . ' on this website to access the lab proposal form. If you are new user please create a new account first.'));
- // return $msg;
-
- $response = new RedirectResponse(Url::fromRoute('user.page')->toString());
-
- $response->send();
- return $msg;
- } //$user->uid == 0
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('uid', $user->id());
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
+ $this->messenger->addError($this->t('Please login to access the proposal form.'));
+ $form_state->setRedirectUrl(Url::fromRoute('user.page'));
+ return [];
+ }
+ $proposal_data = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('uid', $user->id())
+ ->orderBy('id', 'DESC')
+ ->range(0, 1)
+ ->execute()
+ ->fetchObject();
if ($proposal_data) {
if ($proposal_data->approval_status == 0 || $proposal_data->approval_status == 1) {
- \Drupal::messenger()->addMessage(t('We have already received your proposal.'), 'status');
- // drupal_goto('');
- return;
- } //$proposal_data->approval_status == 0 || $proposal_data->approval_status == 1
- } //$proposal_data
+ $this->messenger->addStatus($this->t('We have already received your proposal.'));
+ return [];
+ }
+ }
$form['#attributes'] = [
'enctype' => "multipart/form-data"
];
@@ -268,8 +281,8 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#type' => 'file',
//'#title' => t('Upload circuit diagram'),
'#size' => 48,
- '#description' => $this->t('Upload a document of about 1-2 pages explaining
- the custom model you intend to create') . ' ' . $this->t('Allowed file extensions : ') . \Drupal::config('custom_model.settings')->get('resource_upload_extensions', '') . ' ',
+ '#description' => $this->t('Upload a document of about 1-2 pages explaining
+ the custom model you intend to create') . ' ' . $this->t('Allowed file extensions : ') . $this->configFactory->get('custom_model.settings')->get('resource_upload_extensions', '') . ' ',
];
@@ -407,7 +420,7 @@ public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface
$allowed_extensions_str = '';
switch ($file_type) {
case 'S':
- $allowed_extensions_str = \Drupal::config('custom_model.settings')->get('lab_migration_syllabus_file_extensions');
+ $allowed_extensions_str = $this->configFactory->get('custom_model.settings')->get('lab_migration_syllabus_file_extensions');
break;
} //$file_type
$allowed_extensions = explode(',', $allowed_extensions_str);
@@ -427,19 +440,10 @@ public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface
}
public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
-
- if (!$user->id()) {
- \Drupal::messenger()->addmessage('It is mandatory to login on this website to access the proposal form');
+ if (!$this->currentUser->id()) {
+ $this->messenger->addError($this->t('It is mandatory to login on this website to access the proposal form.'));
return;
}
-
-
- /*if ($form_state['values']['version'] == 'Old version')
- {
- $form_state['values']['version'] = trim($form_state['values']['older']);
- } *///$form_state['values']['version'] == 'Old version'
- /* inserting the user proposal */
if ($form_state->getValue(['department']) == 'Others') {
$form_state->setValue(['department'], $form_state->getValue(['other_department']));
}
@@ -507,7 +511,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
)";
$args = [
// 'uid' => $user->get('uid')->value,
- 'uid' => \Drupal::currentUser()->id(),
+ 'uid' => $this->currentUser->id(),
'approver_uid' => 0,
'name_title' => $v['name_title'],
@@ -534,11 +538,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
//var_dump($result);die;
// var_dump($root_path);die;
- $result1 = \Drupal::database()->query($result, $args, [
- 'return' => Database::RETURN_INSERT_ID
- ]);
- //var_dump($args);die;
-
+ $result1 = $this->connection->query($result, $args);
$root_path = \Drupal::service('custom_model_global')->custom_model_path();
$dest_path = $directory_name . '/';
$dest_path1 = $root_path . $dest_path;
@@ -552,9 +552,9 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
/* checking file type */
//$file_type = 'S';
if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) {
- \Drupal::messenger()->addMessage(t("Error uploading file. File !filename already exists.", [
- '!filename' => $_FILES['files']['name'][$file_form_name]
- ]), 'error');
+ $this->messenger->addError($this->t('Error uploading file. File @filename already exists.', [
+ '@filename' => $_FILES['files']['name'][$file_form_name],
+ ]));
//unlink($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]);
} //file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
/* uploading file */
@@ -565,20 +565,18 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":id" => $result1,
];
- $updateresult = \Drupal::database()->query($query, $args);
- //var_dump($args);die;
-
- \Drupal::messenger()->addMessage($file_name . ' uploaded successfully.', 'status');
+ $updateresult = $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' uploaded successfully.');
} //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
else {
- \Drupal::messenger()->addMessage('Error uploading file : ' . $dest_path . '/' . $file_name, 'error');
+ $this->messenger->addError($this->t('Error uploading file: @path', ['@path' => $dest_path . '/' . $file_name]));
}
} //$file_name
} //$_FILES['files']['name'] as $file_form_name => $file_name
if (!$result1) {
- \Drupal::messenger()->addMessage(t('Error receiving your proposal. Please try again.'), 'error');
+ $this->messenger->addError($this->t('Error receiving your proposal. Please try again.'));
return;
- }
+ }
//!$proposal_id
/* sending email */
// $email_to = $user->mail;
@@ -599,12 +597,8 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
// if (!drupal_mail('custom_model', 'custom_model_proposal_received', $email_to, user_preferred_language($user), $params, $form, TRUE)) {
// \Drupal::messenger()->addMessage('Error sending email message.', 'error');
// }
- \Drupal::messenger()->addMessage(t('We have received your DWSIM Custom Model proposal. We will get back to you soon.'), 'status');
- // drupal_goto('');
- $response = new RedirectResponse(Url::fromRoute('')->toString());
-
- // Send the redirect response
- $response->send();
+ $this->messenger->addStatus($this->t('We have received your DWSIM Custom Model proposal. We will get back to you soon.'));
+ $form_state->setRedirectUrl(Url::fromRoute(''));
}
}
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalStatusForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalStatusForm.php
index 68a30af..7a8a52e 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalStatusForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelProposalStatusForm.php
@@ -9,20 +9,42 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;
use Drupal\Core\Link;
-use Drupal\user\Entity\User;
-use Symfony\Component\HttpFoundation\Response;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\Config\ConfigFactoryInterface;
-use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\DependencyInjection\ContainerInterface;
-use Drupal\Core\Mail\MailManager;
-use Drupal\Core\Session\AccountProxy;
+use Drupal\Core\Session\AccountInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class CustomModelProposalStatusForm extends FormBase {
+ protected $connection;
+ protected $messenger;
+ protected $currentUser;
+ protected $routeMatch;
+
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ RouteMatchInterface $routeMatch
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $routeMatch;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -31,30 +53,15 @@ public function getFormId() {
}
public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
- $proposal_id = (int) $route_match->getParameter('id');
-
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- } //$proposal_data = $proposal_q->fetchObject()
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- return;
- }
- } //$proposal_q
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- return;
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
+ $proposal_data = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ return [];
}
$form['contributor_name'] = [
'#type' => 'item',
@@ -188,14 +195,12 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
// $user = \Drupal::currentUser();
/* get current proposal */
// $proposal_id = (int) arg(3);
- $proposal_id = (int) \Drupal::routeMatch()->getParameter('id'); // ✅ Needed!
- $user = \Drupal::currentUser();
-
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {custom_model_proposal} WHERE id = %d", $proposal_id);
- $query = \Drupal::database()->select('custom_model_proposal');
- $query->fields('custom_model_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
+ $proposal_data = $this->connection->select('custom_model_proposal')
+ ->fields('custom_model_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
// if ($proposal_q) {
// if ($proposal_data = $proposal_q->fetchObject()) {
// /* everything ok */
@@ -219,44 +224,10 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":proposal_id" => $proposal_id,
":expected_completion_date" => time(),
];
- $result = \Drupal::database()->query($up_query, $args);
- // CreateReadmeFileCustomModel($proposal_id);
- // if (!$result) {
- // \Drupal::messenger()->addMessage('Error in update status', 'error');
- // return;
- // } //!$result
- /* sending email */
- // $user_data = User::load($proposal_data->uid);
- // $email_to = $user_data->mail;
- // $from = variable_get('custom_model_from_email', '');
- // $bcc = $user->mail . ', ' . variable_get('custom_model_emails', '');
- // $cc = variable_get('custom_model_cc_emails', '');
- // $params['custom_model_proposal_completed']['proposal_id'] = $proposal_id;
- // $params['custom_model_proposal_completed']['user_id'] = $proposal_data->uid;
- // $params['custom_model_proposal_completed']['headers'] = [
- // 'From' => $from,
- // 'MIME-Version' => '1.0',
- // 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- // 'Content-Transfer-Encoding' => '8Bit',
- // 'X-Mailer' => 'Drupal',
- // 'Cc' => $cc,
- // 'Bcc' => $bcc,
- // ];
- // if (!drupal_mail('custom_model', 'custom_model_proposal_completed', $email_to, language_default(), $params, $from, TRUE)) {
- // \Drupal::messenger()->addMessage('Error sending email message.', 'error');
- // }
- \Drupal::messenger()->addMessage('Congratulations! Custom Model proposal has been marked as completed. User has been notified of the completion.', 'status');
+ $result = $this->connection->query($up_query, $args);
+ $this->messenger->addStatus($this->t('Congratulations! Custom Model proposal has been marked as completed. User has been notified of the completion.'));
}
- // drupal_goto('custom-model/manage-proposal');
- // RedirectResponse('lab-migration/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('custom_model.proposal_all')->toString());
-
- // // // Send the redirect response
- $response->send();
-
-
- return;
-
+ $form_state->setRedirectUrl(Url::fromRoute('custom_model.proposal_all'));
}
}
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelRunForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelRunForm.php
index 54b3bbd..6ae12f7 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelRunForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelRunForm.php
@@ -5,123 +5,173 @@
* Contains \Drupal\custom_model\Form\CustomModelRunForm.
*/
- namespace Drupal\custom_model\Form;
-
- use Drupal\Core\Form\FormBase;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Ajax\AjaxResponse;
- use Drupal\Core\Ajax\HtmlCommand;
- use Drupal\Core\Url;
- use Drupal\Core\Link;
- use Drupal\Core\Database\Database;
- use Drupal\user\Entity\User;
-
- class CustomModelRunForm extends FormBase {
-
- public function getFormId() {
- return 'custom_model_run_form';
- }
-
- public function buildForm(array $form, FormStateInterface $form_state) {
- $route_match = \Drupal::routeMatch();
- $url_custom_model_id = (int) $route_match->getParameter('url_custom_model_id');
- $custom_model_data = $this->_custom_model_information($url_custom_model_id);
- if ($custom_model_data == 'Not found') {
- $url_custom_model_id = 0;
- }
-
- $selected = $form_state->getValue('custom_model') ?? $url_custom_model_id;
-
- $form['custom_model'] = [
- '#type' => 'select',
- '#title' => $this->t('Title of the Custom Model'),
- '#options' => $this->_list_of_custom_model(),
- '#default_value' => $selected,
- '#ajax' => [
- 'callback' => '::custom_model_project_details_callback',
- 'wrapper' => 'custom-model-details-wrapper',
- ],
- ];
-
- $form['custom_model_details_wrapper'] = [
- '#type' => 'container',
- '#attributes' => ['id' => 'custom-model-details-wrapper'],
- ];
-
- if ($selected && $selected != 0) {
- $form['custom_model_details_wrapper']['details'] = [
- '#type' => 'markup',
- '#markup' => $this->_custom_model_details($selected),
- ];
-
- $form['custom_model_details_wrapper']['links'] = [
- '#type' => 'markup',
- '#markup' => '' .
- Link::fromTextAndUrl(
- $this->t('Download Abstract'),
- Url::fromUri('internal:/custom-model/download/project-file/' . $selected)
- )->toString() .
- ' ' .
- Link::fromTextAndUrl(
- $this->t('Download Custom Model'),
- Url::fromUri('internal:/custom-model/full-download/project/' . $selected)
- )->toString() .
- '
',
- ];
- }
-
- return $form;
- }
-
- public function custom_model_project_details_callback(array &$form, FormStateInterface $form_state) {
- return $form['custom_model_details_wrapper'];
- }
-
- public function _custom_model_details($custom_model_id) {
- $details = $this->_custom_model_information($custom_model_id);
- if (!$details) {
- return '';
- }
-
- return 'About the Custom Model ' .
- '
' .
- 'Proposer Name: ' . $details->name_title . ' ' . $details->contributor_name . ' ' .
- 'Title of the Custom Model: ' . $details->project_title . ' ' .
- 'University: ' . $details->university . ' ' .
- ' ';
- }
-
- public function _custom_model_information($proposal_id) {
- if (!$proposal_id) return 'Not found';
- $query = \Drupal::database()->select('custom_model_proposal', 'cmp')
- ->fields('cmp')
- ->condition('id', $proposal_id)
- ->condition('approval_status', 3);
- $result = $query->execute()->fetchObject();
- return $result ?: 'Not found';
- }
-
- public function _list_of_custom_model() {
- $options = ['0' => $this->t('Please select...')];
-
- $results = \Drupal::database()->select('custom_model_proposal', 'cmp')
- ->fields('cmp', ['id', 'project_title', 'name_title', 'contributor_name'])
- ->condition('approval_status', 3)
- ->orderBy('project_title', 'ASC')
- ->execute();
-
- foreach ($results as $row) {
- $options[$row->id] = $row->project_title . ' (' . $this->t('Proposed by @title @name', [
- '@title' => $row->name_title,
- '@name' => $row->contributor_name,
- ]) . ')';
- }
-
- return $options;
- }
-
- public function submitForm(array &$form, FormStateInterface $form_state) {
- // No submit handling required for this form.
- }
- }
-
\ No newline at end of file
+namespace Drupal\custom_model\Form;
+
+use Drupal\Core\Form\FormBase;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Drupal\Core\Routing\RouteMatchInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+class CustomModelRunForm extends FormBase {
+
+ /**
+ * The database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
+ */
+ protected $connection;
+
+ /**
+ * The route match service.
+ *
+ * @var \Drupal\Core\Routing\RouteMatchInterface
+ */
+ protected $routeMatch;
+
+ /**
+ * Constructs the form with injected services.
+ */
+ public function __construct(Connection $connection, RouteMatchInterface $routeMatch) {
+ $this->connection = $connection;
+ $this->routeMatch = $routeMatch;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('current_route_match')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'custom_model_run_form';
+ }
+
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $url_custom_model_id = (int) $this->routeMatch->getParameter('url_custom_model_id');
+ $custom_model_data = $this->_custom_model_information($url_custom_model_id);
+ if ($custom_model_data == 'Not found') {
+ $url_custom_model_id = 0;
+ }
+
+ $selected = $form_state->getValue('custom_model') ?? $url_custom_model_id;
+
+ $form['custom_model'] = [
+ '#type' => 'select',
+ '#title' => $this->t('Title of the Custom Model'),
+ '#options' => $this->_list_of_custom_model(),
+ '#default_value' => $selected,
+ '#ajax' => [
+ 'callback' => '::custom_model_project_details_callback',
+ 'wrapper' => 'custom-model-details-wrapper',
+ ],
+ ];
+
+ $form['custom_model_details_wrapper'] = [
+ '#type' => 'container',
+ '#attributes' => ['id' => 'custom-model-details-wrapper'],
+ ];
+
+ if ($selected && $selected != 0) {
+ $form['custom_model_details_wrapper']['details'] = [
+ '#type' => 'markup',
+ '#markup' => $this->_custom_model_details($selected),
+ ];
+
+ $form['custom_model_details_wrapper']['links'] = [
+ '#type' => 'markup',
+ '#markup' => '' .
+ Link::fromTextAndUrl(
+ $this->t('Download Abstract'),
+ Url::fromUri('internal:/custom-model/download/project-file/' . $selected)
+ )->toString() .
+ ' ' .
+ Link::fromTextAndUrl(
+ $this->t('Download Custom Model'),
+ Url::fromUri('internal:/custom-model/full-download/project/' . $selected)
+ )->toString() .
+ '
',
+ ];
+ }
+
+ return $form;
+ }
+
+ /**
+ * AJAX callback: returns the details wrapper container to be re-rendered.
+ */
+ public function custom_model_project_details_callback(array &$form, FormStateInterface $form_state) {
+ return $form['custom_model_details_wrapper'];
+ }
+
+ /**
+ * Returns the HTML detail block for a given custom model proposal.
+ */
+ public function _custom_model_details($custom_model_id) {
+ $details = $this->_custom_model_information($custom_model_id);
+ if (!$details) {
+ return '';
+ }
+
+ return 'About the Custom Model ' .
+ '
' .
+ 'Proposer Name: ' . $details->name_title . ' ' . $details->contributor_name . ' ' .
+ 'Title of the Custom Model: ' . $details->project_title . ' ' .
+ 'University: ' . $details->university . ' ' .
+ ' ';
+ }
+
+ /**
+ * Returns a single completed proposal record or 'Not found'.
+ */
+ public function _custom_model_information($proposal_id) {
+ if (!$proposal_id) {
+ return 'Not found';
+ }
+ $query = $this->connection->select('custom_model_proposal', 'cmp')
+ ->fields('cmp')
+ ->condition('id', $proposal_id)
+ ->condition('approval_status', 3);
+ $result = $query->execute()->fetchObject();
+ return $result ?: 'Not found';
+ }
+
+ /**
+ * Returns all completed custom model proposals as a select list.
+ */
+ public function _list_of_custom_model() {
+ $options = ['0' => $this->t('Please select...')];
+
+ $results = $this->connection->select('custom_model_proposal', 'cmp')
+ ->fields('cmp', ['id', 'project_title', 'name_title', 'contributor_name'])
+ ->condition('approval_status', 3)
+ ->orderBy('project_title', 'ASC')
+ ->execute();
+
+ foreach ($results as $row) {
+ $options[$row->id] = $row->project_title . ' (' . $this->t('Proposed by @title @name', [
+ '@title' => $row->name_title,
+ '@name' => $row->contributor_name,
+ ]) . ')';
+ }
+
+ return $options;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ // No submit handling required for this form.
+ }
+
+}
\ No newline at end of file
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelSettingsForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelSettingsForm.php
index d5eb990..63b944d 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelSettingsForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelSettingsForm.php
@@ -124,7 +124,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
->set('custom_model_simulation_file', $form_state->getValue(['custom_model_upload']))
->set('custom_model_script_file', $form_state->getValue(['custom_model_script_upload']))
->save();
- \Drupal::messenger()->addMessage(t('Settings updated'), 'status');
+ $this->messenger()->addStatus($this->t('Settings updated'));
}
}
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelUploadAbstractCodeForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelUploadAbstractCodeForm.php
index 9495462..ad1a271 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelUploadAbstractCodeForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelUploadAbstractCodeForm.php
@@ -13,11 +13,50 @@
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;
use Drupal\Core\Link;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Routing\RouteMatchInterface;
+use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
-use Drupal\Core\Database\Database;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\custom_model\Services\CustomModelGlobalfunction;
class CustomModelUploadAbstractCodeForm extends FormBase {
+ protected $connection;
+ protected $messenger;
+ protected $currentUser;
+ protected $routeMatch;
+ protected $globalFunction;
+ protected $configFactory;
+
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ RouteMatchInterface $routeMatch,
+ CustomModelGlobalfunction $globalFunction,
+ ConfigFactoryInterface $configFactory
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $routeMatch;
+ $this->globalFunction = $globalFunction;
+ $this->configFactory = $configFactory;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match'),
+ $container->get('custom_model_global'),
+ $container->get('config.factory')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -26,17 +65,13 @@ public function getFormId() {
}
public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
+ $user = $this->currentUser;
$form['#attributes'] = ['enctype' => "multipart/form-data"];
- /* get current proposal */
- //$proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
- $proposal_id = (int) $route_match->getParameter('id');
- $proposal_data = custom_model_get_proposal($proposal_id);
-if (!$proposal_data) {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- return new RedirectResponse('/custom-model/abstract-code/upload');
-}
+ $proposal_data = $this->globalFunction->custom_model_get_proposal();
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ return new RedirectResponse('/custom-model/abstract-code/upload');
+ }
// $uid = $user->uid;
// $query = \Drupal::database()->select('custom_model_proposal');
@@ -63,18 +98,15 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
// return new RedirectResponse('/custom-model/abstract-code/upload');
// return;
// }
- $query = \Drupal::database()->select('custom_model_submitted_abstracts');
- $query->fields('custom_model_submitted_abstracts');
- $query->condition('proposal_id', $proposal_data->id);
- $abstracts_q = $query->execute()->fetchObject();
- if ($abstracts_q) {
- if ($abstracts_q->is_submitted == 1) {
- \Drupal::messenger()->addMessage(t('You have already submited your project files, hence you can not upload more code, for any query please write to us.'), 'error', $repeat = FALSE);
- // drupal_goto('custom-model/abstract-code');
- return new RedirectResponse('/custom-model/abstract-code/upload');
- return;
- } //$abstracts_q->is_submitted == 1
- } //$abstracts_q->is_submitted == 1
+ $abstracts_q = $this->connection->select('custom_model_submitted_abstracts')
+ ->fields('custom_model_submitted_abstracts')
+ ->condition('proposal_id', $proposal_data->id)
+ ->execute()
+ ->fetchObject();
+ if ($abstracts_q && $abstracts_q->is_submitted == 1) {
+ $this->messenger->addError($this->t('You have already submitted your project files. For any query please write to us.'));
+ return new RedirectResponse('/custom-model/abstract-code/upload');
+ }
$form['project_title'] = [
'#type' => 'item',
'#markup' => $proposal_data->project_title,
@@ -91,36 +123,35 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#title' => t('DWSIM version used'),
];
// var_dump($proposal_data);die;
- $existing_uploaded_S_file = \Drupal::service("custom_model_global")->default_value_for_uploaded_files("S", $proposal_data->id);
+ $existing_uploaded_S_file = $this->globalFunction->default_value_for_uploaded_files('S', $proposal_data->id);
if (!$existing_uploaded_S_file) {
$existing_uploaded_S_file = new \stdClass();
- $existing_uploaded_S_file->filename = "No file uploaded";
- } //!$existing_uploaded_S_file
+ $existing_uploaded_S_file->filename = 'No file uploaded';
+ }
$form['upload_custom_model_simulation_file'] = [
'#type' => 'file',
- '#title' => t('Upload the Custom Model as DWSIM Simulation File'),
- '#description' => t('Current File : ' . $existing_uploaded_S_file->filename . ' Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . \Drupal::config('custom_model.settings')->get('custom_model_simulation_file', '') . ' ',
- ];// Upload simulation file
- $existing_uploaded_P_file = \Drupal::service("custom_model_global")->default_value_for_uploaded_files("P", $proposal_data->id);
+ '#title' => $this->t('Upload the Custom Model as DWSIM Simulation File'),
+ '#description' => $this->t('Current File : ' . $existing_uploaded_S_file->filename . ' Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . $this->t('Allowed file extensions : ') . $this->configFactory->get('custom_model.settings')->get('custom_model_simulation_file', '') . ' ',
+ ];
+ $existing_uploaded_P_file = $this->globalFunction->default_value_for_uploaded_files('P', $proposal_data->id);
if (!$existing_uploaded_P_file) {
$existing_uploaded_P_file = new \stdClass();
- $existing_uploaded_P_file->filename = "No file uploaded";
- } //!$existing_uploaded_P_file
+ $existing_uploaded_P_file->filename = 'No file uploaded';
+ }
$form['upload_custom_model_script_file'] = [
'#type' => 'file',
- '#title' => t('Upload the scilab/ironpython script for the custom model'),
- '#description' => t('Current File : '. $existing_uploaded_P_file->filename . ' Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . \Drupal::config('custom_model.settings')->get('custom_model_script_file', '') . ' ',
+ '#title' => $this->t('Upload the scilab/ironpython script for the custom model'),
+ '#description' => $this->t('Current File : ' . $existing_uploaded_P_file->filename . ' Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . $this->t('Allowed file extensions : ') . $this->configFactory->get('custom_model.settings')->get('custom_model_script_file', '') . ' ',
];
- $existing_uploaded_A_file = \Drupal::service("custom_model_global")
- ->default_value_for_uploaded_files("A", $proposal_data->id);
+ $existing_uploaded_A_file = $this->globalFunction->default_value_for_uploaded_files('A', $proposal_data->id);
if (!$existing_uploaded_A_file) {
$existing_uploaded_A_file = new \stdClass();
- $existing_uploaded_A_file->filename = "No file uploaded";
- } //!$existing_uploaded_A_file
+ $existing_uploaded_A_file->filename = 'No file uploaded';
+ }
$form['upload_an_abstract'] = [
'#type' => 'file',
- '#title' => t('Upload an abstract of the project.'),
- '#description' => t('Current File : ' . $existing_uploaded_A_file->filename . ' Separate filenames with underscore. No spaces or any special characters allowed in filename. ' . t('Allowed file extensions : ') . \Drupal::config('custom_model.settings')->get('custom_model_abstract_upload_extensions', '') . ' '),
+ '#title' => $this->t('Upload an abstract of the project.'),
+ '#description' => $this->t('Current File : ' . $existing_uploaded_A_file->filename . ' Separate filenames with underscore. No spaces or any special characters allowed in filename. ' . $this->t('Allowed file extensions : ') . $this->configFactory->get('custom_model.settings')->get('custom_model_abstract_upload_extensions', '') . ' '),
];
$form['prop_id'] = [
@@ -129,19 +160,14 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
];
$form['submit'] = [
'#type' => 'submit',
- '#value' => t('Submit'),
- // '#value' => $this->t('Submit'),
- '#submit' => [
- // 'custom_model_upload_abstract_code_form_submit'
- 'custom_model.upload_abstract_code_form'
- ],
+ '#value' => $this->t('Submit'),
];
$form['cancel'] = [
'#type' => 'item',
- // '#markup' => l(t('Cancel'), 'custom-model/abstract-code'),
- '#markup' => \Drupal\Core\Link::fromTextAndUrl(
- t('Cancel'),\Drupal\Core\Url::fromUserInput('/custom-model/abstract-code/circuit simulation-project-list')
-)->toString(),
+ '#markup' => Link::fromTextAndUrl(
+ $this->t('Cancel'),
+ Url::fromUserInput('/custom-model/abstract-code/circuit simulation-project-list')
+ )->toString(),
];
return $form;
}
@@ -149,15 +175,9 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
if (isset($_FILES['files'])) {
/* check if file is uploaded */
- $existing_uploaded_A_file = \Drupal::service("custom_model_global")->default_value_for_uploaded_files("A", $form_state->getValue([
- 'prop_id'
- ]));
- $existing_uploaded_S_file = \Drupal::service("custom_model_global")->default_value_for_uploaded_files("S", $form_state->getValue([
- 'prop_id'
- ]));
- $existing_uploaded_P_file = \Drupal::service("custom_model_global")->default_value_for_uploaded_files("P", $form_state->getValue([
- 'prop_id'
- ]));
+ $existing_uploaded_A_file = $this->globalFunction->default_value_for_uploaded_files('A', $form_state->getValue(['prop_id']));
+ $existing_uploaded_S_file = $this->globalFunction->default_value_for_uploaded_files('S', $form_state->getValue(['prop_id']));
+ $existing_uploaded_P_file = $this->globalFunction->default_value_for_uploaded_files('P', $form_state->getValue(['prop_id']));
if (!$existing_uploaded_S_file) {
if (!($_FILES['files']['name']['upload_custom_model_simulation_file'])) {
$form_state->setErrorByName('upload_custom_model_simulation_file', t('Please upload the file.'));
@@ -229,15 +249,13 @@ public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface
}
public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
+ $user = $this->currentUser;
$v = $form_state->getValues();
- $root_path = \Drupal::service("custom_model_global")->custom_model_path();
- $proposal_data = custom_model_get_proposal();
- $proposal_id = $proposal_data->id;
+ $root_path = $this->globalFunction->custom_model_path();
+ $proposal_data = $this->globalFunction->custom_model_get_proposal();
if (!$proposal_data) {
- // drupal_goto('');
return;
- } //!$proposal_data
+ }
$proposal_id = $proposal_data->id;
$proposal_directory = $proposal_data->directory_name;
/* create proposal folder if not present */
@@ -249,34 +267,11 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$proposal_id = $proposal_data->id;
$query_s = "SELECT * FROM {custom_model_submitted_abstracts} WHERE proposal_id = :proposal_id";
$args_s = [":proposal_id" => $proposal_id];
- $query_s_result = \Drupal::database()->query($query_s, $args_s)->fetchObject();
+ $query_s_result = $this->connection->query($query_s, $args_s)->fetchObject();
if (!$query_s_result) {
- /* creating solution database entry */
- $query = "INSERT INTO {custom_model_submitted_abstracts} (
- proposal_id,
- approver_uid,
- abstract_approval_status,
- abstract_upload_date,
- abstract_approval_date,
- is_submitted) VALUES (:proposal_id, :approver_uid, :abstract_approval_status,:abstract_upload_date, :abstract_approval_date, :is_submitted)";
- $args = [
- ":proposal_id" => $proposal_id,
- ":approver_uid" => 0,
- ":abstract_approval_status" => 0,
- ":abstract_upload_date" => time(),
- ":abstract_approval_date" => 0,
- ":is_submitted" => 1,
- ];
- $submitted_abstract_id = \Drupal::database()->query($query, $args, [
- 'return' => Database::RETURN_INSERT_ID
- ]);
- $query1 = "UPDATE {custom_model_proposal} SET is_submitted = :is_submitted WHERE id = :id";
- $args1 = [
- ":is_submitted" => 1,
- ":id" => $proposal_id,
- ];
- \Drupal::database()->query($query1, $args1);
- \Drupal::messenger()->addMessage('Abstract uploaded successfully.', 'status');
+ $submitted_abstract_id = $this->connection->query($query, $args);
+ $this->connection->query($query1, $args1);
+ $this->messenger->addStatus($this->t('Abstract uploaded successfully.'));
} //!$query_s_result
else {
$query = "UPDATE {custom_model_submitted_abstracts} SET
@@ -291,16 +286,9 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":is_submitted" => 1,
":proposal_id" => $proposal_id,
];
- $submitted_abstract_id = \Drupal::database()->query($query, $args, [
- 'return' => Database::RETURN_INSERT_ID
- ]);
- $query1 = "UPDATE {custom_model_proposal} SET is_submitted = :is_submitted WHERE id = :id";
- $args1 = [
- ":is_submitted" => 1,
- ":id" => $proposal_id,
- ];
- \Drupal::database()->query($query1, $args1);
- \Drupal::messenger()->addMessage('Abstract updated successfully.', 'status');
+ $submitted_abstract_id = $this->connection->query($query, $args);
+ $this->connection->query($query1, $args1);
+ $this->messenger->addStatus($this->t('Abstract updated successfully.'));
}
foreach ($_FILES['files']['name'] as $file_form_name => $file_name) {
if ($file_name) {
@@ -325,9 +313,9 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
case 'S':
if (file_exists($root_path . $dest_path_project_files . $_FILES['files']['name'][$file_form_name])) {
//unlink($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]);
- \Drupal::messenger()->addMessage(t("File !filename already exists hence overwirtten the exisitng file ", [
- '!filename' => $_FILES['files']['name'][$file_form_name]
- ]), 'error');
+ $this->messenger->addError($this->t('File @filename already exists and has been overwritten.', [
+ '@filename' => $_FILES['files']['name'][$file_form_name],
+ ]));
} //file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
/* uploading file */
else {
@@ -346,7 +334,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$args = [
":submitted_abstract_id" => $submitted_abstract_id,
":proposal_id" => $proposal_id,
- ":uid" => $user->uid,
+ ":uid" => $this->currentUser->id(),
":approvar_uid" => 0,
":filename" => $_FILES['files']['name'][$file_form_name],
":filepath" => $_FILES['files']['name'][$file_form_name],
@@ -355,8 +343,8 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":filetype" => $file_type,
":timestamp" => time(),
];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' uploaded successfully.', 'status');
+ $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' uploaded successfully.');
} //!$query_ab_f_result
else {
unlink($root_path . $dest_path_project_files . $query_ab_f_result->filename);
@@ -370,12 +358,12 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":proposal_id" => $proposal_id,
":filetype" => $file_type,
];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' file updated successfully.', 'status');
+ $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' file updated successfully.');
}
} //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
else {
- \Drupal::messenger()->addMessage('Error uploading file : ' . $dest_path_project_files . $file_name, 'error');
+ $this->messenger->addError($this->t('Error uploading file: @path', ['@path' => $dest_path_project_files . $file_name]));
}
}
break;
@@ -403,7 +391,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$args = [
":submitted_abstract_id" => $submitted_abstract_id,
":proposal_id" => $proposal_id,
- ":uid" => $user->uid,
+ ":uid" => $this->currentUser->id(),
":approvar_uid" => 0,
":filename" => $_FILES['files']['name'][$file_form_name],
":filepath" => $_FILES['files']['name'][$file_form_name],
@@ -412,8 +400,8 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":filetype" => $file_type,
":timestamp" => time(),
];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' uploaded successfully.', 'status');
+ $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' uploaded successfully.');
} //!$query_ab_f_result
else {
unlink($root_path . $dest_path_project_files . $query_ab_f_result->filename);
@@ -427,12 +415,12 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":proposal_id" => $proposal_id,
":filetype" => $file_type,
];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' file updated successfully.', 'status');
+ $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' file updated successfully.');
}
} //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
else {
- \Drupal::messenger()->addMessage('Error uploading file : ' . $dest_path_project_files . $file_name, 'error');
+ $this->messenger->addError($this->t('Error uploading file: @path', ['@path' => $dest_path_project_files . $file_name]));
}
}
break;
@@ -460,7 +448,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$args = [
":submitted_abstract_id" => $submitted_abstract_id,
":proposal_id" => $proposal_id,
- ":uid" => $user->uid,
+ ":uid" => $this->currentUser->id(),
":approvar_uid" => 0,
":filename" => $_FILES['files']['name'][$file_form_name],
":filepath" => $_FILES['files']['name'][$file_form_name],
@@ -469,8 +457,8 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":filetype" => $file_type,
":timestamp" => time(),
];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' uploaded successfully.', 'status');
+ $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' uploaded successfully.');
} //!$query_ab_f_result
else {
unlink($root_path . $dest_path_project_files . $query_ab_f_result->filename);
@@ -484,12 +472,12 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
":proposal_id" => $proposal_id,
":filetype" => $file_type,
];
- \Drupal::database()->query($query, $args);
- \Drupal::messenger()->addMessage($file_name . ' file updated successfully.', 'status');
+ $this->connection->query($query, $args);
+ $this->messenger->addStatus($file_name . ' file updated successfully.');
}
} //move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])
else {
- \Drupal::messenger()->addMessage('Error uploading file : ' . $dest_path_project_files . $file_name, 'error');
+ $this->messenger->addError($this->t('Error uploading file: @path', ['@path' => $dest_path_project_files . $file_name]));
}
}
break;
diff --git a/modules/custom/dwsim_custom_model/src/Form/CustomModelViewIdeaProposalForm.php b/modules/custom/dwsim_custom_model/src/Form/CustomModelViewIdeaProposalForm.php
index a789909..2b37e51 100755
--- a/modules/custom/dwsim_custom_model/src/Form/CustomModelViewIdeaProposalForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/CustomModelViewIdeaProposalForm.php
@@ -9,21 +9,43 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;
use Drupal\Core\Link;
-use Drupal\user\Entity\User;
-use Symfony\Component\HttpFoundation\Response;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Core\Config\ConfigFactoryInterface;
-use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\DependencyInjection\ContainerInterface;
-use Drupal\Core\Session\AccountProxy;
-
+use Drupal\Core\Session\AccountInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class CustomModelViewIdeaProposalForm extends FormBase {
+ protected $connection;
+ protected $messenger;
+ protected $currentUser;
+ protected $routeMatch;
+
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ RouteMatchInterface $routeMatch
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $routeMatch;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -32,36 +54,16 @@ public function getFormId() {
}
public function buildForm(array $form, FormStateInterface $form_state) {
- $user = \Drupal::currentUser();
- /* get current proposal */
- // $proposal_id = (int) arg(3);
- $route_match = \Drupal::routeMatch();
-
- $proposal_id = (int) $route_match->getParameter('id');
- $query = \Drupal::database()->select('custom_model_idea_proposal');
- $query->fields('custom_model_idea_proposal');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute();
- if ($proposal_q) {
- if ($proposal_data = $proposal_q->fetchObject()) {
- /* everything ok */
- } //$proposal_data = $proposal_q->fetchObject()
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
-
-
- $response = new RedirectResponse('/custom-model/manage-proposal/view-ideas/');
-$response->send();
- return;
- }
- } //$proposal_q
- else {
- \Drupal::messenger()->addMessage(t('Invalid proposal selected. Please try again.'), 'error');
- // drupal_goto('custom-model/manage-proposal');
- $response = new RedirectResponse('/custom-model/manage-proposal/view-ideas/');
- $response->send();
- return;
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
+ $proposal_data = $this->connection->select('custom_model_idea_proposal')
+ ->fields('custom_model_idea_proposal')
+ ->condition('id', $proposal_id)
+ ->execute()
+ ->fetchObject();
+ if (!$proposal_data) {
+ $this->messenger->addError($this->t('Invalid proposal selected. Please try again.'));
+ $form_state->setRedirectUrl(Url::fromUri('internal:/custom-model/manage-proposal/view-ideas/'));
+ return [];
}
if ($proposal_data->reference_link) {
$reference_link = $proposal_data->reference_link;
diff --git a/modules/custom/dwsim_custom_model/src/Form/DwsimCustomModelCompletedTabForm.php b/modules/custom/dwsim_custom_model/src/Form/DwsimCustomModelCompletedTabForm.php
index 88b5c4d..2f95b6d 100755
--- a/modules/custom/dwsim_custom_model/src/Form/DwsimCustomModelCompletedTabForm.php
+++ b/modules/custom/dwsim_custom_model/src/Form/DwsimCustomModelCompletedTabForm.php
@@ -7,9 +7,21 @@
use Drupal\Core\Render\Markup;
use Drupal\Core\Url;
use Drupal\Core\Link;
+use Drupal\Core\Database\Connection;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class DwsimCustomModelCompletedTabForm extends FormBase {
+ protected $connection;
+
+ public function __construct(Connection $connection) {
+ $this->connection = $connection;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static($container->get('database'));
+ }
+
public function getFormId() {
return 'dwsim_custom_model_completed_tab_form';
}
@@ -47,7 +59,7 @@ public function ajax_example_autocheckboxes_callback(array &$form, FormStateInte
public function _custom_model_details_year_wise() {
$custom_model_years = ['0' => $this->t('Please select...')];
- $result = \Drupal::database()->query("SELECT DISTINCT FROM_UNIXTIME(actual_completion_date, '%Y') AS year FROM custom_model_proposal WHERE approval_status = 3 ORDER BY year DESC");
+ $result = $this->connection->query("SELECT DISTINCT FROM_UNIXTIME(actual_completion_date, '%Y') AS year FROM custom_model_proposal WHERE approval_status = 3 ORDER BY year DESC");
foreach ($result as $record) {
$year = $record->year;
$custom_model_years[$year] = $year;
@@ -60,7 +72,7 @@ public function _custom_model_details1($year) {
return ['#markup' => $this->t('Please select a year to view completed custom model projects.')];
}
- $query = \Drupal::database()->select('custom_model_proposal', 'cmp');
+ $query = $this->connection->select('custom_model_proposal', 'cmp');
$query->fields('cmp');
$query->condition('approval_status', 3);
$query->where("FROM_UNIXTIME(actual_completion_date, '%Y') = :year", [':year' => $year]);
diff --git a/modules/custom/dwsim_custom_model/src/Form/GeneratePdf.php b/modules/custom/dwsim_custom_model/src/Form/GeneratePdf.php
index 42f87de..b1081bc 100755
--- a/modules/custom/dwsim_custom_model/src/Form/GeneratePdf.php
+++ b/modules/custom/dwsim_custom_model/src/Form/GeneratePdf.php
@@ -9,10 +9,45 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Routing\RouteMatchInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Extension\ModuleExtensionList;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class GeneratePdf extends FormBase {
+ protected $connection;
+ protected $messenger;
+ protected $currentUser;
+ protected $routeMatch;
+ protected $moduleList;
+
+ public function __construct(
+ Connection $connection,
+ MessengerInterface $messenger,
+ AccountInterface $currentUser,
+ RouteMatchInterface $routeMatch,
+ ModuleExtensionList $moduleList
+ ) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ $this->routeMatch = $routeMatch;
+ $this->moduleList = $moduleList;
+ }
+
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('database'),
+ $container->get('messenger'),
+ $container->get('current_user'),
+ $container->get('current_route_match'),
+ $container->get('extension.list.module')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -21,22 +56,21 @@ public function getFormId() {
}
public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
- $mpath = drupal_get_path('module', 'custom_model');
- //var_dump($mpath);die;
+ // GeneratePdf relies on FPDF and QRcode libraries included from the module path.
+ $mpath = $this->moduleList->getPath('custom_model');
require($mpath . '/pdf/fpdf/fpdf.php');
require($mpath . '/pdf/phpqrcode/qrlib.php');
- $user = \Drupal::currentUser();
- $x = $user->uid;
- $proposal_id = arg(3);
- $query3 = \Drupal::database()->query("SELECT * FROM custom_model_proposal WHERE approval_status=3 AND uid= :uid AND id=:proposal_id", [
- ':uid' => $user->uid,
+ $uid = $this->currentUser->id();
+ $proposal_id = (int) $this->routeMatch->getParameter('id');
+ $query3 = $this->connection->query("SELECT * FROM custom_model_proposal WHERE approval_status=3 AND uid= :uid AND id=:proposal_id", [
+ ':uid' => $uid,
':proposal_id' => $proposal_id,
]);
$data3 = $query3->fetchObject();
if ($data3) {
- if ($data3->uid != $x) {
- \Drupal::messenger()->addMessage('Certificate is not available', 'error');
- return;
+ if ($data3->uid != $uid) {
+ $this->messenger->addError($this->t('Certificate is not available'));
+ return [];
}
}
$gender = [
@@ -65,7 +99,7 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
$image_bg = $mpath . "/pdf/images/bg_cert.png";
$pdf->Image($image_bg, 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight());
$pdf->SetMargins(18, 1, 18);
- $path = drupal_get_path('module', 'custom_model');
+ $path = $mpath;
$pdf->Ln(15);
$pdf->Ln(20);
$pdf->SetFont('Arial', 'BI', 25);
@@ -109,11 +143,11 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
$proposal_get_id = 0;
$UniqueString = "";
$tempDir = $path . "/pdf/temp_prcode/";
- $query = \Drupal::database()->select('custom_model_qr_code');
+ $query = $this->connection->select('custom_model_qr_code');
$query->fields('custom_model_qr_code');
$query->condition('proposal_id', $proposal_id);
$result = $query->execute();
- $data = $result->fetchObject();
+ $data = $result->fetchObject();
$DBString = $data->qr_code;
$proposal_get_id = $data->proposal_id;
if ($DBString == "" || $DBString == "null") {
@@ -128,7 +162,7 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
":proposal_id" => $proposal_id,
":qr_code" => $UniqueString,
];
- $result = \Drupal::database()->query($query, $args, ['return' => Database::RETURN_INSERT_ID]);
+ $result = $this->connection->query($query, $args);
} //$DBString == "" || $DBString == "null"
else {
$UniqueString = $DBString;
diff --git a/modules/custom/dwsim_custom_model/src/Services/AjaxHelper.php b/modules/custom/dwsim_custom_model/src/Services/AjaxHelper.php
new file mode 100644
index 0000000..d21cf35
--- /dev/null
+++ b/modules/custom/dwsim_custom_model/src/Services/AjaxHelper.php
@@ -0,0 +1,121 @@
+renderer = $renderer;
+ }
+
+ /**
+ * Replaces the HTML of a given CSS selector.
+ *
+ * @param string $selector
+ * @param string|array $content
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function replaceWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new ReplaceCommand($selector, $rendered));
+ return $response;
+ }
+
+ /**
+ * Sets the inner HTML of a given CSS selector.
+ *
+ * @param string $selector
+ * @param string|array $content
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function htmlWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new HtmlCommand($selector, $rendered));
+ return $response;
+ }
+
+ /**
+ * Returns a DataCommand response.
+ *
+ * @param string $selector
+ * @param string $name
+ * @param mixed $value
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function dataCommand($selector, $name, $value) {
+ $response = new AjaxResponse();
+ $response->addCommand(new DataCommand($selector, $name, $value));
+ return $response;
+ }
+
+ /**
+ * Returns a message command.
+ *
+ * @param string $message
+ * @param string $type status|warning|error
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function messageCommand($message, $type = 'status') {
+ $response = new AjaxResponse();
+ $response->addCommand(new MessageCommand($message, NULL, ['type' => $type]));
+ return $response;
+ }
+
+ /**
+ * Builds a response with multiple HTML or Replace commands in one call.
+ *
+ * @param array $commands
+ * Array keyed by CSS selector with values:
+ * - 'type' => 'html'|'replace'|'data'
+ * - 'content' => string|render array
+ * - 'name' => string (only for 'data' type)
+ * - 'value' => mixed (only for 'data' type)
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function buildMultiCommandResponse(array $commands) {
+ $response = new AjaxResponse();
+ foreach ($commands as $selector => $data) {
+ $rendered = is_array($data['content']) ? $this->renderer->render($data['content']) : $data['content'];
+ if ($data['type'] === 'html') {
+ $response->addCommand(new HtmlCommand($selector, $rendered));
+ }
+ elseif ($data['type'] === 'replace') {
+ $response->addCommand(new ReplaceCommand($selector, $rendered));
+ }
+ elseif ($data['type'] === 'data') {
+ $response->addCommand(new DataCommand($selector, $data['name'], $data['value']));
+ }
+ }
+ return $response;
+ }
+
+}
diff --git a/modules/custom/dwsim_custom_model/src/Services/CustomModelGlobalfunction.php b/modules/custom/dwsim_custom_model/src/Services/CustomModelGlobalfunction.php
index ec8c2e7..83cd848 100755
--- a/modules/custom/dwsim_custom_model/src/Services/CustomModelGlobalfunction.php
+++ b/modules/custom/dwsim_custom_model/src/Services/CustomModelGlobalfunction.php
@@ -2,336 +2,271 @@
namespace Drupal\custom_model\Services;
-use Drupal\Core\Extension\ModuleHandlerInterface;
-use Drupal\Core\File\FileSystemInterface;
-use Drupal\Core\Link;
-use Drupal\Core\Url;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\Core\Database\Database;
-use Drupal\Core\DrupalKernel;
-use Drupal\user\Entity\User;
-use Drupal\Core\Form\FormBase;
-use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Controller\ControllerBase;
-use Symfony\Component\HttpFoundation\Response;
-use Drupal\Core\Routing\RouteMatchInterface;
-use Drupal\Service;
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountInterface;
-use Drupal\Core\Form\FormBuilderInterface;
-use Drupal\Core\Render\Markup;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-use Symfony\Component\HttpFoundation\ResponseHeaderBag;
-use Symfony\Component\HttpFoundation\BinaryFileResponse;
+use Drupal\Core\StringTranslation\StringTranslationTrait;
-class CustomModelGlobalFunction{
+class CustomModelGlobalfunction {
-public function custom_model_ideas_files_path()
-{
+ use StringTranslationTrait;
+
+ /** @var \Drupal\Core\Database\Connection */
+ protected $connection;
+
+ /** @var \Drupal\Core\Messenger\MessengerInterface */
+ protected $messenger;
+
+ /** @var \Drupal\Core\Session\AccountInterface */
+ protected $currentUser;
+
+ /**
+ * Constructor with injected services.
+ */
+ public function __construct(Connection $connection, MessengerInterface $messenger, AccountInterface $currentUser) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ }
+
+ public function custom_model_ideas_files_path() {
return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/custom_model_uploads/ideas_files/';
-}
+ }
- public function custom_model_path()
- {
+ public function custom_model_path() {
return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/custom_model_uploads/';
}
- public function default_value_for_uploaded_files($filetype, $proposal_id)
-{
- $query = \Drupal::database()->select('custom_model_submitted_abstracts_file');
- $query->fields('custom_model_submitted_abstracts_file');
- $query->condition('proposal_id', $proposal_id);
- $selected_files_array = "";
- if ($filetype == "A")
- {
- $query->condition('filetype', $filetype);
- $filetype_q = $query->execute()->fetchObject();
- return $filetype_q;
- } //$filetype == "A" A-abstract
- elseif ($filetype == "P")
- {
- $query->condition('filetype', $filetype);
- $filetype_q = $query->execute()->fetchObject();
- return $filetype_q;
- }// P - Script file
- elseif ($filetype == "S")
- {
- $query->condition('filetype', $filetype);
- $filetype_q = $query->execute()->fetchObject();
- return $filetype_q;
- } //S - Simulation file
- else
- {
- return;
- }
- return;
-}
+ public function default_value_for_uploaded_files($filetype, $proposal_id) {
+ $query = $this->connection->select('custom_model_submitted_abstracts_file');
+ $query->fields('custom_model_submitted_abstracts_file');
+ $query->condition('proposal_id', $proposal_id);
+ if ($filetype == "A") {
+ $query->condition('filetype', $filetype);
+ return $query->execute()->fetchObject();
+ }
+ elseif ($filetype == "P") {
+ $query->condition('filetype', $filetype);
+ return $query->execute()->fetchObject();
+ }
+ elseif ($filetype == "S") {
+ $query->condition('filetype', $filetype);
+ return $query->execute()->fetchObject();
+ }
+ else {
+ return;
+ }
+ return;
+ }
- public function _cm_list_of_departments()
-{
- $department = array();
- $query = \Drupal::database()->select('custom_model_list_of_departments');
+ public function _cm_list_of_departments() {
+ $department = [];
+ $query = $this->connection->select('custom_model_list_of_departments');
$query->fields('custom_model_list_of_departments');
$query->orderBy('id', 'ASC');
$department_list = $query->execute();
- while ($department_list_data = $department_list->fetchObject())
- {
- $department[$department_list_data->department] = $department_list_data->department;
- } //$department_list_data = $department_list->fetchObject()
+ while ($department_list_data = $department_list->fetchObject()) {
+ $department[$department_list_data->department] = $department_list_data->department;
+ }
return $department;
-}
+ }
- public function _list_of_software_versions()
-{
- $software_version = array();
- $query = \Drupal::database()->select('dwsim_software_version');
+ public function _list_of_software_versions() {
+ $software_version = [];
+ $query = $this->connection->select('dwsim_software_version');
$query->fields('dwsim_software_version');
$query->orderBy('id', 'ASC');
$software_version_list = $query->execute();
- while ($software_version_list_data = $software_version_list->fetchObject())
- {
- $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
- } //$software_version_list_data = $software_version_list->fetchObject()
+ while ($software_version_list_data = $software_version_list->fetchObject()) {
+ $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
+ }
return $software_version;
-}
+ }
-public function _cm_list_of_states()
-{
- $states = array(
- 0 => '-Select-'
- );
- $query = \Drupal::database()->select('list_states_of_india');
+ public function _cm_list_of_states() {
+ $states = [0 => '-Select-'];
+ $query = $this->connection->select('list_states_of_india');
$query->fields('list_states_of_india');
- //$query->orderBy('', '');
$states_list = $query->execute();
- while ($states_list_data = $states_list->fetchObject())
- {
- $states[$states_list_data->state] = $states_list_data->state;
- } //$states_list_data = $states_list->fetchObject()
+ while ($states_list_data = $states_list->fetchObject()) {
+ $states[$states_list_data->state] = $states_list_data->state;
+ }
return $states;
-}
+ }
-public function _cm_list_of_cities()
-{
- $city = array(
- 0 => '-Select-'
- );
- $query = \Drupal::database()->select('list_cities_of_india');
+ public function _cm_list_of_cities() {
+ $city = [0 => '-Select-'];
+ $query = $this->connection->select('list_cities_of_india');
$query->fields('list_cities_of_india');
$query->orderBy('city', 'ASC');
$city_list = $query->execute();
- while ($city_list_data = $city_list->fetchObject())
- {
- $city[$city_list_data->city] = $city_list_data->city;
- } //$city_list_data = $city_list->fetchObject()
+ while ($city_list_data = $city_list->fetchObject()) {
+ $city[$city_list_data->city] = $city_list_data->city;
+ }
return $city;
-}
-public function _cm_list_of_pincodes()
-{
- $pincode = array(
- 0 => '-Select-'
- );
- $query = \Drupal::database()->select('list_of_all_india_pincode');
+ }
+
+ public function _cm_list_of_pincodes() {
+ $pincode = [0 => '-Select-'];
+ $query = $this->connection->select('list_of_all_india_pincode');
$query->fields('list_of_all_india_pincode');
$query->orderBy('pincode', 'ASC');
$pincode_list = $query->execute();
- while ($pincode_list_data = $pincode_list->fetchObject())
- {
- $pincode[$pincode_list_data->pincode] = $pincode_list_data->pincode;
- } //$pincode_list_data = $pincode_list->fetchObject()
+ while ($pincode_list_data = $pincode_list->fetchObject()) {
+ $pincode[$pincode_list_data->pincode] = $pincode_list_data->pincode;
+ }
return $pincode;
-}
-
-public function _cm_dir_name($project, $proposar_name)
-{
+ }
- $project_title = ucname($project);
- $proposar_name = ucname($proposar_name);
+ public function _cm_dir_name($project, $proposar_name) {
+ $project_title = ucwords(strtolower($project));
+ $proposar_name = ucwords(strtolower($proposar_name));
$dir_name = $project_title . ' By ' . $proposar_name;
$directory_name = str_replace("__", "_", str_replace(" ", "_", str_replace("/", " ", $dir_name)));
return $directory_name;
-}
-public function cm_RenameDir($proposal_id, $dir_name)
-{
- $proposal_id = $proposal_id;
- $dir_name = $dir_name;
- $query = \Drupal::database()->query("SELECT directory_name,id FROM custom_model_proposal WHERE id = :proposal_id", array(
- ':proposal_id' => $proposal_id
- ));
+ }
+
+ public function cm_RenameDir($proposal_id, $dir_name) {
+ $query = $this->connection->query("SELECT directory_name,id FROM custom_model_proposal WHERE id = :proposal_id", [
+ ':proposal_id' => $proposal_id
+ ]);
$result = $query->fetchObject();
- if ($result != NULL)
- {
- $files = scandir(custom_model_path());
- $files_id_dir = custom_model_path() . $result->id;
- //var_dump($files);die;
- $file_dir = custom_model_path() . $result->directory_name;
- if (is_dir($file_dir))
- {
- $new_directory_name = rename(custom_model_path() . $result->directory_name, custom_model_path() . $dir_name);
- return $new_directory_name;
- } //is_dir($file_dir)
- else if (is_dir($files_id_dir))
- {
- $new_directory_name = rename(custom_model_path() . $result->id, custom_model_path() . $dir_name);
- return $new_directory_name;
- } //is_dir($files_id_dir)
- else
- {
- \Drupal::messenger()->addMessage('Directory not available for rename.');
- return;
- }
- } //$result != NULL
- else
- {
- \Drupal::messenger()->addMessage('Project directory name not present in databse');
+ if ($result != NULL) {
+ $files_id_dir = $this->custom_model_path() . $result->id;
+ $file_dir = $this->custom_model_path() . $result->directory_name;
+ if (is_dir($file_dir)) {
+ return rename($this->custom_model_path() . $result->directory_name, $this->custom_model_path() . $dir_name);
+ }
+ else if (is_dir($files_id_dir)) {
+ return rename($this->custom_model_path() . $result->id, $this->custom_model_path() . $dir_name);
+ }
+ else {
+ $this->messenger->addWarning('Directory not available for rename.');
return;
+ }
}
- //var_dump($files);die;
- /* if ($files != NULL)
- {
- $new_directory_name = rename(custom_model_path() . $result->directory_name, custom_model_path() . $dir_name) or \Drupal::messenger()->addMessage("Unable to rename folder");
+ else {
+ $this->messenger->addError('Project directory name not present in database');
+ return;
}
- else
- {
- $new_directory_name = 'Can not rename the directory. Directory not present';
- }*/
- return;
-}
-public function CreateReadmeFileCustomModel($proposal_id)
-{
- $result = \Drupal::database()->query("
- SELECT * from custom_model_proposal WHERE id = :proposal_id", array(
- ":proposal_id" => $proposal_id
- ));
+ }
+
+ public function CreateReadmeFileCustomModel($proposal_id) {
+ $result = $this->connection->query("SELECT * from custom_model_proposal WHERE id = :proposal_id", [
+ ":proposal_id" => $proposal_id
+ ]);
$proposal_data = $result->fetchObject();
- $root_path = custom_model_path();
+ $root_path = $this->custom_model_path();
$readme_file = fopen($root_path . $proposal_data->directory_name . "/README.txt", "w") or die("Unable to open file!");
$txt = "";
- $txt .= "About the Custom Model";
- $txt .= "\n" . "\n";
+ $txt .= "About the Custom Model\n\n";
$txt .= "Title Of The Custom Model Project: " . $proposal_data->project_title . "\n";
$txt .= "Proposar Name: " . $proposal_data->name_title . " " . $proposal_data->contributor_name . "\n";
- $txt .= "University: " . $proposal_data->university . "\n";
- $txt .= "\n" . "\n";
- $txt .= "OM PSSP Project By FOSSEE, IIT Bombay" . "\n";
+ $txt .= "University: " . $proposal_data->university . "\n\n";
+ $txt .= "OM PSSP Project By FOSSEE, IIT Bombay\n";
fwrite($readme_file, $txt);
fclose($readme_file);
return $txt;
-}
+ }
-public function cm_rrmdir_project($prop_id)
-{
- $proposal_id = $prop_id;
- $result = \Drupal::database()->query("
- SELECT * from custom_model_proposal WHERE id = :proposal_id", array(
- ":proposal_id" => $proposal_id
- ));
+ public function cm_rrmdir_project($prop_id) {
+ $result = $this->connection->query("SELECT * from custom_model_proposal WHERE id = :proposal_id", [
+ ":proposal_id" => $prop_id
+ ]);
$proposal_data = $result->fetchObject();
- $root_path = custom_model_path();
+ if (!$proposal_data) {
+ $this->messenger->addError('Data not found.');
+ return FALSE;
+ }
+
+ $root_path = $this->custom_model_path();
$dir = $root_path . $proposal_data->directory_name;
- if ($proposal_data->id == $prop_id)
- {
- if (is_dir($dir))
- {
- $objects = scandir($dir);
- foreach ($objects as $object)
- {
- if ($object != "." && $object != "..")
- {
- if (filetype($dir . "/" . $object) == "dir")
- {
- cm_rrmdir($dir . "/" . $object);
- } //filetype($dir . "/" . $object) == "dir"
- else
- {
- unlink($dir . "/" . $object);
- }
- } //$object != "." && $object != ".."
- } //$objects as $object
- reset($objects);
- rmdir($dir);
- $msg = \Drupal::messenger()->addMessage("Directory deleted successfully");
- return $msg;
- } //is_dir($dir)
- $msg = \Drupal::messenger()->addMessage("Directory not present");
- return $msg;
- } //$proposal_data->id == $prop_id
- else
- {
- $msg = \Drupal::messenger()->addMessage("Data not found");
- return $msg;
+
+ if (is_dir($dir)) {
+ $objects = scandir($dir);
+ foreach ($objects as $object) {
+ if ($object != "." && $object != "..") {
+ if (filetype($dir . "/" . $object) == "dir") {
+ $this->cm_rrmdir($dir . "/" . $object);
+ }
+ else {
+ unlink($dir . "/" . $object);
+ }
+ }
+ }
+ reset($objects);
+ rmdir($dir);
+ $this->messenger->addStatus('Directory deleted successfully.');
+ return TRUE;
}
-}
+ $this->messenger->addWarning('Directory not present.');
+ return FALSE;
+ }
-public function cm_rrmdir($dir)
-{
- if (is_dir($dir))
- {
- $objects = scandir($dir);
- foreach ($objects as $object)
- {
- if ($object != "." && $object != "..")
- {
- if (filetype($dir . "/" . $object) == "dir")
- cm_rrmdir($dir . "/" . $object);
- else
- unlink($dir . "/" . $object);
- } //$object != "." && $object != ".."
- } //$objects as $object
- reset($objects);
- rmdir($dir);
- } //is_dir($dir)
-}
+ public function cm_rrmdir($dir) {
+ if (is_dir($dir)) {
+ $objects = scandir($dir);
+ foreach ($objects as $object) {
+ if ($object != "." && $object != "..") {
+ if (filetype($dir . "/" . $object) == "dir")
+ $this->cm_rrmdir($dir . "/" . $object);
+ else
+ unlink($dir . "/" . $object);
+ }
+ }
+ reset($objects);
+ rmdir($dir);
+ }
+ }
-public function custom_model_get_proposal()
- {
- global $user;
- //$proposal_q = \Drupal::database()->query("SELECT * FROM {custom_model_proposal} WHERE solution_provider_uid = ".$user->uid." AND solution_status = 2 ORDER BY id DESC LIMIT 1");
- $query = \Drupal::database()->select('custom_model_proposal');
+ public function custom_model_get_proposal() {
+ $user = $this->currentUser;
+ $query = $this->connection->select('custom_model_proposal');
$query->fields('custom_model_proposal');
+ $query->condition('uid', $user->id());
+ $query->condition('approval_status', 1);
$query->orderBy('id', 'DESC');
$query->range(0, 1);
- $proposal_q = $query->execute();
- $proposal_data = $proposal_q->fetchObject();
- if (!$proposal_data)
- {
- \Drupal::messenger()->addMessage("You do not have any approved custom model proposal. Please check the ");
- drupal_goto('');
- }
- switch ($proposal_data->approval_status)
- {
- case 0:
- \Drupal::messenger()->addMessage(t('Proposal is awaiting approval.'), 'status');
- return FALSE;
- case 1:
- return $proposal_data;
- case 2:
- \Drupal::messenger()->addMessage(t('Proposal has been dis-approved.'), 'error');
- return FALSE;
- case 3:
- \Drupal::messenger()->addMessage(t('Proposal has been marked as completed.'), 'status');
- return FALSE;
- default:
- \Drupal::messenger()->addMessage(t('Invalid proposal state. Please contact site administrator for further information.'), 'error');
- return FALSE;
+ $proposal_data = $query->execute()->fetchObject();
+ if ($proposal_data) {
+ return $proposal_data;
}
- return FALSE;
-}
-public function custom_model_ucname($string)
- {
+ $status_query = $this->connection->select('custom_model_proposal');
+ $status_query->fields('custom_model_proposal');
+ $status_query->condition('uid', $user->id());
+ $status_query->orderBy('id', 'DESC');
+ $status_query->range(0, 1);
+ $latest_proposal = $status_query->execute()->fetchObject();
+
+ if (!$latest_proposal) {
+ $this->messenger->addError($this->t("You do not have any approved custom model proposal. Please check the proposal status."));
+ return FALSE;
+ }
+
+ switch ($latest_proposal->approval_status) {
+ case 0:
+ $this->messenger->addStatus($this->t('Proposal is awaiting approval.'));
+ return FALSE;
+ case 2:
+ $this->messenger->addError($this->t('Proposal has been dis-approved.'));
+ return FALSE;
+ case 3:
+ $this->messenger->addStatus($this->t('Proposal has been marked as completed.'));
+ return FALSE;
+ default:
+ $this->messenger->addError($this->t('Invalid proposal state. Please contact site administrator for further information.'));
+ return FALSE;
+ }
+ }
+
+ public function custom_model_ucname($string) {
$string = ucwords(strtolower($string));
- foreach (array(
- '-',
- '\''
- ) as $delimiter)
- {
- if (strpos($string, $delimiter) !== false)
- {
- $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
- }
+ foreach (['-', "'"] as $delimiter) {
+ if (strpos($string, $delimiter) !== false) {
+ $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
}
+ }
return $string;
}
-
-
}
\ No newline at end of file
diff --git a/modules/custom/dwsim_custom_model/src/Services/MailService.php b/modules/custom/dwsim_custom_model/src/Services/MailService.php
new file mode 100644
index 0000000..08c4924
--- /dev/null
+++ b/modules/custom/dwsim_custom_model/src/Services/MailService.php
@@ -0,0 +1,169 @@
+mailManager = $mail_manager;
+ $this->loggerFactory = $logger_factory;
+ $this->configFactory = $config_factory;
+ $this->languageManager = $language_manager;
+ }
+
+ /**
+ * Sends a module email with standard headers.
+ *
+ * @param string $module_name
+ * The module name used for hook_mail and config lookup.
+ * @param string $mail_key
+ * The mail key defined in hook_mail.
+ * @param string $to
+ * Recipient email address.
+ * @param array $params
+ * Mail parameters (body, subject, etc).
+ * @param bool $send
+ * Whether to actually send (defaults TRUE).
+ *
+ * @return bool
+ * TRUE on success, FALSE on failure.
+ */
+ public function sendMail($module_name, $mail_key, $to, array $params = [], $send = TRUE) {
+ if (empty($to)) {
+ $this->loggerFactory->get($module_name)->warning(
+ 'Email not sent: recipient address is empty for mail key: @key',
+ ['@key' => $mail_key]
+ );
+ \Drupal::messenger()->addWarning($this->t('Email could not be sent because the recipient email address is empty.'));
+ return FALSE;
+ }
+
+ $config = $this->configFactory->get($module_name . '.settings');
+ $from = $config->get($module_name . '_from_email') ?: $this->configFactory->get('system.site')->get('mail');
+
+ // Set standard mail headers.
+ if (!isset($params[$mail_key]['headers'])) {
+ $params[$mail_key]['headers'] = [
+ 'From' => $from,
+ 'MIME-Version' => '1.0',
+ 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
+ 'Content-Transfer-Encoding' => '8Bit',
+ 'X-Mailer' => 'Drupal',
+ ];
+ }
+ else {
+ $params[$mail_key]['headers']['From'] = $params[$mail_key]['headers']['From'] ?? $from;
+ }
+
+ // Attach Cc if configured and not manually set.
+ if (!isset($params[$mail_key]['headers']['Cc'])) {
+ $cc = $config->get($module_name . '_cc_emails');
+ if (!empty($cc)) {
+ $params[$mail_key]['headers']['Cc'] = $cc;
+ }
+ }
+
+ // Attach Bcc if configured and not manually set.
+ if (!isset($params[$mail_key]['headers']['Bcc'])) {
+ $bcc = $config->get($module_name . '_emails');
+ if (!empty($bcc)) {
+ $params[$mail_key]['headers']['Bcc'] = $bcc;
+ }
+ }
+
+ $langcode = $this->languageManager->getCurrentLanguage()->getId();
+
+ $result = $this->mailManager->mail($module_name, $mail_key, $to, $langcode, $params, $from, $send);
+
+ if (empty($result['result'])) {
+ $this->loggerFactory->get($module_name)->error(
+ 'Error sending email for key: @key to @to',
+ ['@key' => $mail_key, '@to' => $to]
+ );
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ /**
+ * Sends a proposal approval email.
+ */
+ public function sendApprovalMail($module_name, $proposal_id, $user_id, $to, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_approved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Sends a proposal rejection email.
+ */
+ public function sendRejectionMail($module_name, $proposal_id, $user_id, $to, $reason, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_disapproved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+ $params[$mail_key]['reason'] = $reason;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Sends a generic notification email.
+ */
+ public function sendNotification($module_name, $mail_key, $to, $subject, $body, array $extra_params = []) {
+ $params = $extra_params;
+ $params[$mail_key]['subject'] = $subject;
+ $params[$mail_key]['body'] = $body;
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+}
diff --git a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.info.yml b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.info.yml
index 229be34..db82368 100755
--- a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.info.yml
+++ b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.info.yml
@@ -2,6 +2,5 @@ name: 'DWSIM Flowsheet'
description: 'DWSIM Project, FOSSEE, IIT Bombay'
type: module
package: FOSSEE
-core: 8.x
-core_version_requirement: ^8 || ^9 || ^10
+core_version_requirement: ^10 || ^11
dependencies: { }
diff --git a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.module b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.module
index 0f5bfa5..563a1f7 100755
--- a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.module
+++ b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.module
@@ -1,699 +1,43 @@
'Flowsheet Proposal Form',
- 'description' => 'Flowsheet Proposal Form Proposal Form',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_proposal_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet create proposal'
- ),
- #'type' => MENU_NORMAL_ITEM,
- 'file' => 'proposal.inc'
- );
- $items['flowsheeting-project/manage-proposal'] = array(
- 'title' => 'Manage Flowsheet Proposals',
- 'description' => 'Manage Flowsheet Proposals',
- 'page callback' => 'dwsim_flowsheet_proposal_pending',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- 'file' => 'manage_proposal.inc'
- );
- $items['flowsheeting-project/manage-proposal/pending'] = array(
- 'title' => 'Pending Proposals',
- 'description' => 'Pending dwsim flowsheet Proposals Queue',
- 'page callback' => 'dwsim_flowsheet_proposal_pending',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- #'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => 1,
- 'file' => 'manage_proposal.inc'
- );
- $items['flowsheeting-project/manage-proposal/all'] = array(
- 'title' => 'All Proposals',
- 'description' => 'All Proposals',
- 'page callback' => 'dwsim_flowsheet_proposal_all',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- #'type' => MENU_LOCAL_TASK,
- 'weight' => 2,
- 'file' => 'manage_proposal.inc'
- );
- $items['flowsheeting-project/manage-proposal/approved_proposals'] = array(
- 'title' => 'Approved Proposals',
- 'description' => 'Approved Proposals',
- 'page callback' => 'dwsim_flowsheet_approved_tab',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- #'type' => MENU_LOCAL_TASK,
- 'weight' => 3,
- 'file' => 'proposals_review_tab.inc'
- );
- $items['flowsheeting-project/manage-proposal/uploaded_proposals'] = array(
- 'title' => 'Uploaded Proposals',
- 'description' => 'Uploaded Proposals',
- 'page callback' => 'dwsim_flowsheet_uploaded_tab',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- #'type' => MENU_LOCAL_TASK,
- 'weight' => 4,
- 'file' => 'proposals_review_tab.inc'
- );
- $items['flowsheeting-project/manage-proposal/completed_proposals'] = array(
- 'title' => 'Completed Proposals',
- 'description' => 'Completed Proposals',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('dwsim_flowsheet_completed_tab_form'),
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- #'type' => MENU_LOCAL_TASK,
- 'weight' => 5,
- 'file' => 'proposals_review_tab.inc'
- );
- /*$items['flowsheeting-project/download'] = array(
- 'title' => 'Flowsheet Download Proposals',
- 'description' => 'Flowsheet Download Proposals',
- 'page callback' => 'dwsim_flowsheet_download_proposals_tab',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- 'file' => 'proposals_review_tab.inc'
- );*/
- $items['flowsheeting-project/manage-proposal/approve'] = array(
- 'title' => 'Approve Proposal',
- 'description' => 'Approve Proposal',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_proposal_approval_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'manage_proposal.inc'
- );
- // $items['flowsheeting-project/manage-proposal/solution-proposal-approve'] = array(
- // 'title' => 'Approve Solution Proposal',
- // 'description' => 'Approve Solution Proposal',
- // 'page callback' => 'drupal_get_form',
- // 'page arguments' => array(
- // 'dwsim_flowsheet_solution_proposal_approval_form'
- // ),
- // 'access arguments' => array(
- // 'dwsim flowsheet manage proposal'
- // ),
- // #'type' => MENU_CALLBACK,
- // 'file' => 'manage_solution_proposal.inc'
- // );
- $items['flowsheeting-project/manage-proposal/edit'] = array(
- 'title' => 'Edit Proposal',
- 'description' => 'Edit Proposal',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_proposal_edit_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet manage proposal'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'manage_proposal.inc'
- );
- $items['flowsheeting-project/manage-proposal/status'] = array(
- 'title' => 'Proposal Status',
- 'description' => 'Proposal Status',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_proposal_status_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet approve proposal'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'manage_proposal.inc'
- );
- // $items['flowsheeting-project/show-proposal'] = array(
- // 'title' => 'dwsim flowsheet Solution Proposal',
- // 'page callback' => 'drupal_get_form',
- // 'page arguments' => array(
- // 'dwsim_flowsheet_solution_proposal_form'
- // ),
- // 'access arguments' => array(
- // 'dwsim flowsheet propose solution'
- // ),
- // #'type' => MENU_CALLBACK,
- // 'file' => 'solution_proposal.inc'
- // );
- /* CODE REVIEW */
- // $items['flowsheeting-project/code-approval'] = array(
- // 'title' => 'LM Manage Code Approval',
- // 'description' => 'Manage Code Approval',
- // 'page callback' => 'dwsim_flowsheet_code_approval',
- // 'access arguments' => array(
- // 'dwsim flowsheet approve code'
- // ),
- // #'type' => MENU_NORMAL_ITEM,
- // 'file' => 'code_approval.inc'
- // );
- $items['flowsheeting-project/abstract-approval/approve'] = array(
- 'title' => 'Code Approval',
- 'description' => 'Code Approval',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_abstract_approval_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet approve code'
- ),
- #'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => 1,
- 'file' => 'code_approval.inc'
- );
- $items['flowsheeting-project/abstract-approval/bulk'] = array(
- 'title' => 'Bulk Manage',
- 'description' => 'Bulk Mangage',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_abstract_bulk_approval_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet bulk manage abstract'
- ),
- #'type' => MENU_LOCAL_TASK,
- 'weight' => 2,
- 'file' => 'abstract_bulk_approval.inc'
- );
- // $items['flowsheeting-project/code-approval/bulk'] = array(
- // 'title' => 'Bulk Manage',
- // 'description' => 'Bulk Mangage',
- // 'page callback' => 'drupal_get_form',
- // 'page arguments' => array(
- // 'dwsim_flowsheet_bulk_approval_form'
- // ),
- // 'access arguments' => array(
- // 'dwsim flowsheet bulk manage abstract'
- // ),
- // #'type' => MENU_LOCAL_TASK,
- // 'weight' => 2,
- // 'file' => 'bulk_approval.inc'
- // );
- // $items['flowsheeting-project/code-approval/upload'] = array(
- // 'title' => 'Upload Code',
- // 'description' => 'Admin Upload',
- // 'page callback' => 'drupal_get_form',
- // 'page arguments' => array(
- // 'dwsim_flowsheet_bulk_upload_code_form'
- // ),
- // 'access arguments' => array(
- // 'dwsim flowsheet bulk manage abstract'
- // ),
- // #'type' => MENU_CALLBACK,
- // 'weight' => 4,
- // 'file' => 'bulk_upload_code.inc'
- // );
- // $items['flowsheeting-project/code-approval/notes'] = array(
- // 'title' => 'Notes for Reviewers',
- // 'description' => 'Notes for Reviewers',
- // 'page callback' => 'drupal_get_form',
- // 'page arguments' => array(
- // 'dwsim_flowsheet_lab_notes_form'
- // ),
- // 'access arguments' => array(
- // 'dwsim flowsheet bulk manage abstract'
- // ),
- // #'type' => MENU_CALLBACK,
- // 'weight' => 4,
- // 'file' => 'notes.inc'
- // );
- /* CODE UPLOAD */
- $items['flowsheeting-project/abstract-code'] = array(
- 'title' => 'Abstract and Flowsheet Submission',
- 'description' => 'Abstract Submission',
- 'page callback' => 'dwsim_flowsheet_abstract',
- 'access callback' => 'user_access',
- 'access arguments' => array(
- 'dwsim flowsheet upload code'
- ),
- 'file' => 'upload_code.inc'
- );
- $items['flowsheeting-project/abstract-code/flowsheet-project-list'] = array(
- 'title' => 'Flowsheet project',
- 'description' => 'List Experiments',
- 'page callback' => 'dwsim_flowsheet_abstract',
- 'access arguments' => array(
- 'dwsim flowsheet upload code'
- ),
- #'type' => MENU_DEFAULT_LOCAL_TASK,
- 'file' => 'upload_code.inc',
- 'weight' => 1
- );
- $items['flowsheeting-project/abstract-code/upload'] = array(
- 'title' => 'Abstract and Flowsheet Submission',
- 'description' => 'Abstract Submission',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_upload_abstract_code_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet upload code'
- ),
- #'type' => MENU_LOCAL_TASK,
- 'file' => 'upload_code.inc',
- 'weight' => 2
- );
- // $items['flowsheeting-project/abstract-code/delete'] = array(
- // 'title' => 'Delete Solution',
- // 'description' => 'Delete Solution',
- // 'page callback' => 'dwsim_flowsheet_upload_code_delete',
- // 'access arguments' => array(
- // 'dwsim flowsheet upload code'
- // ),
- // #'type' => MENU_CALLBACK,
- // 'file' => 'upload_code_delete.inc'
- // );
- /* CODE DOWNLOADS */
- $items['flowsheeting-project/download/file'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'dwsim_flowsheet_download_solution_file',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- $items['flowsheeting-project/download/project-file'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'dwsim_flowsheet_download_abstract',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- $items['flowsheeting-project/download/solution'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'dwsim_flowsheet_download_solution',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- $items['flowsheeting-project/download/experiment'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'dwsim_flowsheet_download_experiment',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- $items['flowsheeting-project/download/lab'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'dwsim_flowsheet_download_lab',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- // $items['flowsheeting-project/full-download/experiment'] = array(
- // 'title' => 'Code Download',
- // 'description' => 'Code Download',
- // 'page callback' => 'dwsim_flowsheet_download_full_experiment',
- // 'access arguments' => array(
- // 'dwsim flowsheet approve code'
- // ),
- // #'type' => MENU_CALLBACK,
- // 'file' => 'full_download.inc'
- // );
- $items['flowsheeting-project/full-download/project'] = array(
- 'title' => 'Code Download',
- 'description' => 'Code Download',
- 'page callback' => 'dwsim_flowsheet_download_full_project',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'full_download.inc'
- );
- $items['flowsheeting-project/download-proposals'] = array(
- 'title' => 'Download Proposals',
- 'description' => 'Download Proposals',
- 'page callback' => 'dwsim_flowsheet_download_completed_proposals',
- 'access arguments' => array(
- 'dwsim flowsheet download proposals'
- ),
- 'file' => 'download_proposals.inc'
- );
- $items['flowsheeting-project/download-proposals-all'] = array(
- 'title' => 'Download Proposals',
- 'description' => 'Download Proposals',
- 'page callback' => 'dwsim_flowsheet_download_proposals',
- 'access arguments' => array(
- 'dwsim flowsheet download proposals'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- /* COMPLETED dwsim flowsheetS */
- $items['flowsheeting-project/completed-flowsheet'] = array(
- 'title' => 'Completed Flowsheets',
- 'page callback' => 'dwsim_flowsheet_completed_proposals_all',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- 'file' => 'flowsheet_details.inc'
- );
- /* LABS IN PROGRESS */
- $items['flowsheeting-project/flowsheet-progress'] = array(
- 'title' => 'Flowsheets in Progress',
- 'page callback' => 'dwsim_flowsheet_progress_all',
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- 'file' => 'flowsheet_details.inc'
- );
- /* DOWNLOAD FOR EVERYONE */
- $items['flowsheeting-project/dwsim-flowsheet-run'] = array(
- 'title' => 'Download Codes',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_run_form'
- ),
- 'access arguments' => array(
- 'dwsim flowsheet download code'
- ),
- #'type' => MENU_NORMAL_ITEM,
- 'file' => 'run.inc'
- );
- $items['flowsheeting-project/download/user-defined-compound-file'] = array(
- 'title' => 'Download user defined compound file',
- 'description' => 'Download user defined compound',
- 'page callback' => 'dwsim_flowsheet_download_user_defined_compound',
- 'access arguments' => array(
- 'download code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'download.inc'
- );
- /* LATEX SCRIPT */
- /*$items['flowsheeting-project/generate-lab'] = array(
- 'title' => 'Generate Lab',
- 'description' => 'Generate Lab From Latex Script',
- 'page callback' => 'dwsim_flowsheet_download_lab_pdf',
- 'access arguments' => array(
- 'dwsim flowsheet generate lab'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'latex.inc'
- );
- $items['flowsheeting-project/delete-lab'] = array(
- 'title' => 'Delete Lab PDF',
- 'description' => 'Delete Lab PDF',
- 'page callback' => 'dwsim_flowsheet_delete_lab_pdf',
- 'access arguments' => array(
- 'dwsim flowsheet approve code'
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'latex.inc'
- );*/
- /* ADMIN SETTINGS */
- $items['admin/settings/dwsim-flowsheet'] = array(
- 'title' => 'dwsim flowsheet Settings',
- 'description' => 'dwsim flowsheet Settings',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'dwsim_flowsheet_settings_form'
- ),
- 'access arguments' => array(
- 'administer dwsim flowsheet'
- ),
- #'type' => MENU_NORMAL_ITEM,
- 'file' => 'settings.inc'
- );
- /* AJAX REQUEST */
- // $items["lab-bulk-manage-exp/ajax"] = array(
- // "title" => "Ajax callbacks",
- // "page callback" => "lab_bulk_manage_exp_ajax",
- // "access arguments" => array(
- // "dwsim flowsheet bulk manage abstract"
- // ),
- // "type" => MENU_CALLBACK,
- // 'file' => 'bulk_approval.inc'
- // );
- /*$items['flowsheeting-project/certificates'] = array(
- 'title' => 'List of Flowsheet Certificates',
- 'description' => 'List of flowsheet Certificates',
- 'page callback' => '_list_flowsheet_certificates',
- 'access arguments' => array(
- 'list flowsheet certificates'
- ),
- 'file' => 'pdf/list_flowsheet_certificate.inc'
- );
- $items['flowsheeting-project/certificates/generate-pdf'] = array(
- 'title' => 'Download Certificate',
- 'description' => 'Download Certificate',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'generate_pdf'
- ),
- #'type' => MENU_CALLBACK,
- 'access arguments' => array(
- 'generate pdf'
- ),
- 'file' => 'pdf/cert_new.inc'
- );
- $items['flowsheeting-project/certificates-custom'] = array(
- 'title' => 'List of Flowsheet Custom Certificates',
- 'description' => 'List of flowsheet Custom Certificates',
- 'page callback' => '_list_flowsheet_custom_certificates',
- 'access arguments' => array(
- 'list flowsheet custom certificates'
- ),
- 'file' => 'pdf/list_mentor_certificates.inc'
- );
- $items['flowsheeting-project/certificates-custom/pdf'] = array(
- 'title' => 'Download Certificate',
- 'description' => 'Download Certificate',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array(
- 'generate_pdf'
- ),
- #'type' => MENU_CALLBACK,
- 'access arguments' => array(
- 'generate pdf'
- ),
- 'file' => 'pdf/mentor_cert_pdf.inc'
- );
- $items["flowsheeting-project/certificates/verify"] = array(
- "title" => "Certificate Verification",
- "page callback" => "verify_certificates",
- "access arguments" => array(
- "verify certificates"
- ),
- #'type' => MENU_CALLBACK,
- 'file' => 'pdf/verify_certificates.inc'
- );*/
- return $items;
-}
-/**
- * Implementation of hook_perm().
- */
-function dwsim_flowsheet_permission()
-{
- return array(
- 'dwsim flowsheet create proposal' => array(
- 'title' => t('dwsim flowsheet create proposal'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet manage proposal' => array(
- 'title' => t('dwsim flowsheet manage proposal'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet edit proposal' => array(
- 'title' => t('dwsim flowsheet edit proposal'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet approve proposal' => array(
- 'title' => t('dwsim flowsheet approve proposal'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet propose solution' => array(
- 'title' => t('dwsim flowsheet propose solution'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet approve abstract' => array(
- 'title' => t('dwsim flowsheet approve code'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet bulk manage abstract' => array(
- 'title' => t('dwsim flowsheet bulk manage abstract'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet bulk delete abstract' => array(
- 'title' => t('dwsim flowsheet bulk delete code'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet upload abstract' => array(
- 'title' => t('dwsim flowsheet upload code'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet download abstract' => array(
- 'title' => t('dwsim flowsheet download code'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet download proposals' => array(
- 'title' => t('dwsim flowsheet download proposals'),
- 'restrict access' => TRUE
- ),
- 'administer dwsim flowsheet' => array(
- 'title' => t('administer dwsim flowsheet'),
- 'restrict access' => TRUE
- ),
- 'dwsim flowsheet generate abstract' => array(
- 'title' => t('dwsim flowsheet generate abstract'),
- 'restrict access' => TRUE
- ),
- "list flowsheet certificates" => array(
- "title" => t("list flowsheet certificates"),
- "description" => t("Allows users to list flowsheet certificates.")
- ),
- "list flowsheet custom certificates" => array(
- "title" => t("list flowsheet custom certificates"),
- "description" => t("Allows users to list flowsheet custom certificates.")
- ),
- "generate pdf" => array(
- "title" => t("Generate pdf"),
- "description" => t("Allows users to Generate pdf.")
- )
- );
- // return array('dwsim flowsheet create proposal', 'dwsim flowsheet manage proposal', 'dwsim flowsheet edit proposal', 'dwsim flowsheet approve proposal', 'dwsim flowsheet propose solution', 'dwsim flowsheet approve code', 'dwsim flowsheet bulk manage abstract', 'dwsim flowsheet bulk delete code', 'dwsim flowsheet upload code', 'dwsim flowsheet download code', 'administer dwsim flowsheet', 'dwsim flowsheet generate lab');
-}
-
+// Helper functions used by forms and the controller as global procedural calls.
+// hook_menu() removed — routing is handled by dwsim_flowsheet.routing.yml.
+// hook_permission() removed — permissions are declared in dwsim_flowsheet.permissions.yml.
-/* AJAX CALLS */
-function dwsim_flowsheet_ajax()
-{
- $query_type = arg(2);
- if ($query_type == 'chapter_title')
- {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- //$chapter_q = db_query("SELECT * FROM {dwsim_flowsheet_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);
- $query = \Drupal::database()->select('dwsim_flowsheet_chapter');
- $query->fields('dwsim_flowsheet_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if ($chapter_data = $chapter_q->fetchObject())
- {
- echo $chapter_data->name;
- return;
- } //$chapter_data = $chapter_q->fetchObject()
- } //$query_type == 'chapter_title'
- else if ($query_type == 'example_exists')
- {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- $example_number = arg(5);
- $chapter_id = 0;
- $query = \Drupal::database()->select('dwsim_flowsheet_chapter');
- $query->fields('dwsim_flowsheet_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if (!$chapter_data = $chapter_q->fetchObject())
- {
- echo '';
- return;
- } //!$chapter_data = $chapter_q->fetchObject()
- else
- {
- $chapter_id = $chapter_data->id;
- }
- $query = \Drupal::database()->select('dwsim_flowsheet_example');
- $query->fields('dwsim_flowsheet_example');
- $query->condition('chapter_id', $chapter_id);
- $query->condition('number', $example_number);
- $query->range(0, 1);
- $example_q = $query->execute();
- if ($example_data = $example_q->fetchObject())
- {
- if ($example_data->approval_status == 1)
- echo 'Warning! Solution already approved. You cannot upload the same solution again.';
- else
- echo 'Warning! Solution already uploaded. Delete the solution and reupload it.';
- return;
- } //$example_data = $example_q->fetchObject()
- } //$query_type == 'example_exists'
- echo '';
-}
/*************************** VALIDATION FUNCTIONS *****************************/
-function dwsim_flowsheet_check_valid_filename($file_name)
-{
- if (!preg_match('/^[0-9a-zA-Z\.\_]+$/', $file_name))
+
+function dwsim_flowsheet_check_valid_filename($file_name) {
+ if (!preg_match('/^[0-9a-zA-Z\.\\_]+$/', $file_name))
return FALSE;
else if (substr_count($file_name, ".") > 1)
return FALSE;
else
return TRUE;
}
-function dwsim_flowsheet_check_name($name = '')
-{
+
+function dwsim_flowsheet_check_name($name = '') {
if (!preg_match('/^[0-9a-zA-Z\ ]+$/', $name))
return FALSE;
else
return TRUE;
}
-function dwsim_flowsheet_check_code_number($number = '')
-{
+
+function dwsim_flowsheet_check_code_number($number = '') {
if (!preg_match('/^[0-9]+$/', $number))
return FALSE;
else
return TRUE;
}
-function dwsim_flowsheet_path()
-{
+
+function dwsim_flowsheet_path() {
return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/dwsim_flowsheet_uploads/';
}
+
/************************* USER VERIFICATION FUNCTIONS ************************/
-function dwsim_flowsheet_get_proposal()
-{
+
+function dwsim_flowsheet_get_proposal() {
$user = \Drupal::currentUser();
- // Use the most recent approved proposal so uploads resolve to the active
- // project directory instead of an arbitrary older proposal row.
+ // Use the most recent approved proposal.
$query = \Drupal::database()->select('dwsim_flowsheet_proposal');
$query->fields('dwsim_flowsheet_proposal');
$query->condition('uid', $user->id());
@@ -701,8 +45,7 @@ function dwsim_flowsheet_get_proposal()
$query->orderBy('id', 'DESC');
$query->range(0, 1);
$proposal_data = $query->execute()->fetchObject();
- if ($proposal_data)
- {
+ if ($proposal_data) {
return $proposal_data;
}
@@ -713,14 +56,12 @@ function dwsim_flowsheet_get_proposal()
$status_query->orderBy('id', 'DESC');
$status_query->range(0, 1);
$latest_proposal = $status_query->execute()->fetchObject();
- if (!$latest_proposal)
- {
+ if (!$latest_proposal) {
\Drupal::messenger()->addError("You do not have any approved DWSIM Flowsheet proposal. Please propose the flowsheet proposal");
return FALSE;
}
- switch ($latest_proposal->approval_status)
- {
+ switch ($latest_proposal->approval_status) {
case 0:
\Drupal::messenger()->addStatus(t('Proposal is awaiting approval.'));
return FALSE;
@@ -735,227 +76,181 @@ function dwsim_flowsheet_get_proposal()
return FALSE;
}
}
+
/*************************************************************************/
-/***** Function To convert only first charater of string in uppercase ****/
+/***** Convert only first character of string to uppercase ***************/
/*************************************************************************/
-function dwsim_flowsheet_ucname($string)
-{
+
+function dwsim_flowsheet_ucname($string) {
$string = ucwords(strtolower($string));
- foreach (array(
- '-',
- '\''
- ) as $delimiter)
- {
- if (strpos($string, $delimiter) !== false)
- {
+ foreach (['-', "'"] as $delimiter) {
+ if (strpos($string, $delimiter) !== false) {
$string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
- } //strpos($string, $delimiter) !== false
- } //array( '-', '\'' ) as $delimiter
+ }
+ }
return $string;
}
-function _df_sentence_case($string)
-{
+
+function _df_sentence_case($string) {
$string = ucwords(strtolower($string));
- foreach (array(
- '-',
- '\''
- ) as $delimiter)
- {
- if (strpos($string, $delimiter) !== false)
- {
+ foreach (['-', "'"] as $delimiter) {
+ if (strpos($string, $delimiter) !== false) {
$string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
- } //strpos($string, $delimiter) !== false
- } //array( '-', '\'' ) as $delimiter
+ }
+ }
return $string;
}
-function _df_list_of_dwsim_compound()
-{
- $dwsim_compound = array();
+
+function _df_list_of_dwsim_compound() {
+ $dwsim_compound = [];
$query = \Drupal::database()->select('dwsim_flowsheet_compounds_from_dwsim');
$query->fields('dwsim_flowsheet_compounds_from_dwsim');
$query->orderBy('id', 'ASC');
$dwsim_compound_list = $query->execute();
- while ($dwsim_compound_list_data = $dwsim_compound_list->fetchObject())
- {
+ while ($dwsim_compound_list_data = $dwsim_compound_list->fetchObject()) {
$dwsim_compound[$dwsim_compound_list_data->compound] = $dwsim_compound_list_data->compound;
- } //$dwsim_compound_list_data = $dwsim_compound_list->fetchObject()
+ }
return $dwsim_compound;
}
-function _df_list_of_unit_operations()
-{
- $dwsim_unit_operations = array();
+
+function _df_list_of_unit_operations() {
+ $dwsim_unit_operations = [];
$query = \Drupal::database()->select('dwsim_flowsheet_unit_operations');
$query->fields('dwsim_flowsheet_unit_operations');
$query->orderBy('id', 'ASC');
$dwsim_unit_operations_list = $query->execute();
- while ($dwsim_unit_operations_list_data = $dwsim_unit_operations_list->fetchObject())
- {
+ while ($dwsim_unit_operations_list_data = $dwsim_unit_operations_list->fetchObject()) {
$dwsim_unit_operations[$dwsim_unit_operations_list_data->unit_operations] = $dwsim_unit_operations_list_data->unit_operations;
- } //$dwsim_unit_operations_list_data = $dwsim_unit_operations_list->fetchObject()
+ }
return $dwsim_unit_operations;
}
-function _df_list_of_thermodynamic_packages()
-{
- $dwsim_thermodynamic_packages = array();
+
+function _df_list_of_thermodynamic_packages() {
+ $dwsim_thermodynamic_packages = [];
$query = \Drupal::database()->select('dwsim_flowsheet_thermodynamic_packages');
$query->fields('dwsim_flowsheet_thermodynamic_packages');
$query->orderBy('thermodynamic_packages', 'ASC');
$dwsim_thermodynamic_packages_list = $query->execute();
- while ($dwsim_thermodynamic_packages_list_data = $dwsim_thermodynamic_packages_list->fetchObject())
- {
+ while ($dwsim_thermodynamic_packages_list_data = $dwsim_thermodynamic_packages_list->fetchObject()) {
$dwsim_thermodynamic_packages[$dwsim_thermodynamic_packages_list_data->thermodynamic_packages] = $dwsim_thermodynamic_packages_list_data->thermodynamic_packages;
- } //$dwsim_thermodynamic_packages_list_data = $dwsim_thermodynamic_packages_list->fetchObject()
+ }
return $dwsim_thermodynamic_packages;
}
-function _df_list_of_logical_block()
-{
- $dwsim_logical_block = array();
+
+function _df_list_of_logical_block() {
+ $dwsim_logical_block = [];
$query = \Drupal::database()->select('dwsim_flowsheet_logical_block');
$query->fields('dwsim_flowsheet_logical_block');
$query->orderBy('id', 'ASC');
$dwsim_logical_block_list = $query->execute();
- while ($dwsim_logical_block_list_data = $dwsim_logical_block_list->fetchObject())
- {
+ while ($dwsim_logical_block_list_data = $dwsim_logical_block_list->fetchObject()) {
$dwsim_logical_block[$dwsim_logical_block_list_data->logical_block] = $dwsim_logical_block_list_data->logical_block;
- } //$dwsim_logical_block_list_data = $dwsim_logical_block_list->fetchObject()
+ }
return $dwsim_logical_block;
}
-function _df_list_of_states()
-{
- $states = array(
- 0 => '-Select-'
- );
+
+function _df_list_of_states() {
+ $states = [0 => '-Select-'];
$query = \Drupal::database()->select('list_states_of_india');
$query->fields('list_states_of_india');
- //$query->orderBy('', '');
$states_list = $query->execute();
- while ($states_list_data = $states_list->fetchObject())
- {
+ while ($states_list_data = $states_list->fetchObject()) {
$states[$states_list_data->state] = $states_list_data->state;
- } //$states_list_data = $states_list->fetchObject()
+ }
return $states;
}
-function _df_list_of_cities()
-{
- $city = array(
- 0 => '-Select-'
- );
+
+function _df_list_of_cities() {
+ $city = [0 => '-Select-'];
$query = \Drupal::database()->select('list_cities_of_india');
$query->fields('list_cities_of_india');
$query->orderBy('city', 'ASC');
$city_list = $query->execute();
- while ($city_list_data = $city_list->fetchObject())
- {
+ while ($city_list_data = $city_list->fetchObject()) {
$city[$city_list_data->city] = $city_list_data->city;
- } //$city_list_data = $city_list->fetchObject()
+ }
return $city;
}
-function _df_list_of_pincodes()
-{
- $pincode = array(
- 0 => '-Select-'
- );
+
+function _df_list_of_pincodes() {
+ $pincode = [0 => '-Select-'];
$query = \Drupal::database()->select('list_of_all_india_pincode');
$query->fields('list_of_all_india_pincode');
$query->orderBy('pincode', 'ASC');
$pincode_list = $query->execute();
- while ($pincode_list_data = $pincode_list->fetchObject())
- {
+ while ($pincode_list_data = $pincode_list->fetchObject()) {
$pincode[$pincode_list_data->pincode] = $pincode_list_data->pincode;
- } //$pincode_list_data = $pincode_list->fetchObject()
+ }
return $pincode;
}
-function _df_list_of_departments()
-{
- $department = array();
+
+function _df_list_of_departments() {
+ $department = [];
$query = \Drupal::database()->select('list_of_departments');
$query->fields('list_of_departments');
$query->orderBy('id', 'DESC');
$department_list = $query->execute();
- while ($department_list_data = $department_list->fetchObject())
- {
+ while ($department_list_data = $department_list->fetchObject()) {
$department[$department_list_data->department] = $department_list_data->department;
- } //$department_list_data = $department_list->fetchObject()
+ }
return $department;
}
-function _df_list_of_software_version()
-{
- $software_version = array();
+
+function _df_list_of_software_version() {
+ $software_version = [];
$query = \Drupal::database()->select('dwsim_software_version');
$query->fields('dwsim_software_version');
$query->orderBy('id', 'ASC');
$software_version_list = $query->execute();
- while ($software_version_list_data = $software_version_list->fetchObject())
- {
+ while ($software_version_list_data = $software_version_list->fetchObject()) {
$software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
- } //$software_version_list_data = $software_version_list->fetchObject()
+ }
return $software_version;
}
-function _df_dir_name($project, $proposar_name)
-{
+function _df_dir_name($project, $proposar_name) {
$project_title = ucwords($project);
$proposar_name = ucwords($proposar_name);
$dir_name = $project_title . ' By ' . $proposar_name;
$directory_name = str_replace("__", "_", str_replace(" ", "_", str_replace("/", " ", $dir_name)));
return $directory_name;
}
-function dwsim_flowsheet_document_path()
-{
+
+function dwsim_flowsheet_document_path() {
return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/dwsim_flowsheet_uploads/';
}
-function DF_RenameDir($proposal_id, $dir_name)
-{
- $proposal_id = $proposal_id;
- $dir_name = $dir_name;
- $query = \Drupal::database()->query("SELECT directory_name,id FROM dwsim_flowsheet_proposal WHERE id = :proposal_id", array(
- ':proposal_id' => $proposal_id
- ));
+
+function DF_RenameDir($proposal_id, $dir_name) {
+ $query = \Drupal::database()->query("SELECT directory_name,id FROM dwsim_flowsheet_proposal WHERE id = :proposal_id", [
+ ':proposal_id' => $proposal_id,
+ ]);
$result = $query->fetchObject();
- if ($result != NULL)
- {
- $files = scandir(dwsim_flowsheet_path());
+ if ($result != NULL) {
$files_id_dir = dwsim_flowsheet_path() . $result->id;
- //var_dump($files);die;
$file_dir = dwsim_flowsheet_path() . $result->directory_name;
- if (is_dir($file_dir))
- {
+ if (is_dir($file_dir)) {
$new_directory_name = rename(dwsim_flowsheet_path() . $result->directory_name, dwsim_flowsheet_path() . $dir_name);
return $new_directory_name;
- } //is_dir($file_dir)
- else if (is_dir($files_id_dir))
- {
+ }
+ else if (is_dir($files_id_dir)) {
$new_directory_name = rename(dwsim_flowsheet_path() . $result->id, dwsim_flowsheet_path() . $dir_name);
return $new_directory_name;
- } //is_dir($files_id_dir)
- else
- {
+ }
+ else {
\Drupal::messenger()->addMessage('Directory not available for rename.');
return;
}
- } //$result != NULL
- else
- {
- \Drupal::messenger()->addMessage('Project directory name not present in databse');
- return;
}
- //var_dump($files);die;
- /* if ($files != NULL)
- {
- $new_directory_name = rename(dwsim_flowsheet_path() . $result->directory_name, dwsim_flowsheet_path() . $dir_name) or drupal_set_message("Unable to rename folder");
+ else {
+ \Drupal::messenger()->addMessage('Project directory name not present in database');
+ return;
}
- else
- {
- $new_directory_name = 'Can not rename the directory. Directory not present';
- }*/
- return;
}
-function CreateReadmeFileDWSIMFlowsheetingProject($proposal_id)
-{
- $result = \Drupal::database()->query("
- SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", array(
- ":proposal_id" => $proposal_id
- ));
+
+function CreateReadmeFileDWSIMFlowsheetingProject($proposal_id) {
+ $result = \Drupal::database()->query("SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", [
+ ':proposal_id' => $proposal_id,
+ ]);
$proposal_data = $result->fetchObject();
$root_path = dwsim_flowsheet_path();
$readme_file = fopen($root_path . $proposal_data->directory_name . "/README.txt", "w") or die("Unable to open file!");
@@ -971,98 +266,83 @@ function CreateReadmeFileDWSIMFlowsheetingProject($proposal_id)
fclose($readme_file);
return $txt;
}
-function rrmdir_project($prop_id)
-{
+
+function rrmdir_project($prop_id) {
$proposal_id = $prop_id;
- $result = \Drupal::database()->query("
- SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", array(
- ":proposal_id" => $proposal_id
- ));
+ $result = \Drupal::database()->query("SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", [
+ ':proposal_id' => $proposal_id,
+ ]);
$proposal_data = $result->fetchObject();
$root_path = dwsim_flowsheet_document_path();
$dir = $root_path . $proposal_data->directory_name;
- if ($proposal_data->id == $prop_id)
- {
- if (is_dir($dir))
- {
+ if ($proposal_data->id == $prop_id) {
+ if (is_dir($dir)) {
$objects = scandir($dir);
- foreach ($objects as $object)
- {
- if ($object != "." && $object != "..")
- {
- if (filetype($dir . "/" . $object) == "dir")
- {
+ foreach ($objects as $object) {
+ if ($object != "." && $object != "..") {
+ if (filetype($dir . "/" . $object) == "dir") {
rrmdir($dir . "/" . $object);
- } //filetype($dir . "/" . $object) == "dir"
- else
- {
+ }
+ else {
unlink($dir . "/" . $object);
}
- } //$object != "." && $object != ".."
- } //$objects as $object
+ }
+ }
reset($objects);
rmdir($dir);
$msg = \Drupal::messenger()->addMessage("Directory deleted successfully");
return $msg;
- } //is_dir($dir)
+ }
$msg = \Drupal::messenger()->addMessage("Directory not present");
return $msg;
- } //$proposal_data->id == $prop_id
- else
- {
+ }
+ else {
$msg = \Drupal::messenger()->addMessage("Data not found");
return $msg;
}
}
-function rrmdir($dir)
-{
- if (is_dir($dir))
- {
+
+function rrmdir($dir) {
+ if (is_dir($dir)) {
$objects = scandir($dir);
- foreach ($objects as $object)
- {
- if ($object != "." && $object != "..")
- {
+ foreach ($objects as $object) {
+ if ($object != "." && $object != "..") {
if (filetype($dir . "/" . $object) == "dir")
rrmdir($dir . "/" . $object);
else
unlink($dir . "/" . $object);
- } //$object != "." && $object != ".."
- } //$objects as $object
+ }
+ }
reset($objects);
rmdir($dir);
- } //is_dir($dir)
+ }
}
-function _dwsim_flowsheet_list_of_user_defined_compound($proposal_id)
-{
+
+function _dwsim_flowsheet_list_of_user_defined_compound($proposal_id) {
$data = "";
- //$query = db_select('dwsim_flowsheet_user_defined_compound');
- //$query->fields('dwsim_flowsheet_user_defined_compound');
- //$query->condition('proposal_id', $proposal_id, '=');
- //$query->orderBy('user_defined_compound', 'ASC');
- $user_defined_compound_list = \Drupal::database()->query("SELECT * FROM dwsim_flowsheet_user_defined_compound WHERE proposal_id = :proposal_id", array(":proposal_id" => $proposal_id));
- $headers = array(
- "List of user defined compounds used in process flowsheet",
- "CAS No."
+ $user_defined_compound_list = \Drupal::database()->query(
+ "SELECT * FROM dwsim_flowsheet_user_defined_compound WHERE proposal_id = :proposal_id",
+ [':proposal_id' => $proposal_id]
);
- if($user_defined_compound_list){
- $rows = array();
- while ($row = $user_defined_compound_list->fetchObject())
- {
- $item = array(
- "{$row->user_defined_compound}",
- "{$row->cas_no}"
- );
- array_push($rows, $item);
- } //$row = $user_defined_compound_list->fetchObject()
-
-$data = [
- '#type' => 'table',
- '#header' => $headers,
- '#rows' => $rows,
- ];
-
- }else{
+ $headers = [
+ "List of user defined compounds used in process flowsheet",
+ "CAS No.",
+ ];
+ if ($user_defined_compound_list) {
+ $rows = [];
+ while ($row = $user_defined_compound_list->fetchObject()) {
+ $rows[] = [
+ "{$row->user_defined_compound}",
+ "{$row->cas_no}",
+ ];
+ }
+ $data = [
+ '#type' => 'table',
+ '#header' => $headers,
+ '#rows' => $rows,
+ ];
+ }
+ else {
$data .= "Not entered";
}
return $data;
@@ -1084,7 +364,6 @@ function _dwsim_flowsheet_append_mail_body(array &$message, $body) {
}
return;
}
-
if ($body !== NULL && $body !== '') {
$message['body'][] = (string) $body;
}
@@ -1175,7 +454,6 @@ function dwsim_flowsheet_mail($key, &$message, $params) {
$state = $proposal_data->state ?? $state;
$country = $proposal_data->country ?? $country;
}
-
$message['subject'] = t(
'[@site_name][Circuit Simulation Project] Your eSim Circuit Simulation Project proposal has been received',
['@site_name' => $site_name],
@@ -1206,11 +484,7 @@ function dwsim_flowsheet_mail($key, &$message, $params) {
);
$message['body'][] = t(
"Dear @name,\n\nYour DWSIM Flowsheeting proposal has been deleted by the review team.\n\nProject Title: @project_title\n\nYou may submit a fresh proposal if required.\n\nBest Wishes,\n\n@site_name Team,\nFOSSEE, IIT Bombay",
- [
- '@name' => $full_name,
- '@project_title' => $project_title,
- '@site_name' => $site_name,
- ],
+ ['@name' => $full_name, '@project_title' => $project_title, '@site_name' => $site_name],
['langcode' => $langcode]
);
break;
@@ -1223,11 +497,7 @@ function dwsim_flowsheet_mail($key, &$message, $params) {
);
$message['body'][] = t(
"Dear @name,\n\nCongratulations.\n\nYour DWSIM Flowsheeting proposal has been approved.\n\nProject Title: @project_title\n\nBest Wishes,\n\n@site_name Team,\nFOSSEE, IIT Bombay",
- [
- '@name' => $full_name,
- '@project_title' => $project_title,
- '@site_name' => $site_name,
- ],
+ ['@name' => $full_name, '@project_title' => $project_title, '@site_name' => $site_name],
['langcode' => $langcode]
);
break;
@@ -1244,12 +514,7 @@ function dwsim_flowsheet_mail($key, &$message, $params) {
);
$message['body'][] = t(
"Dear @name,\n\nWe regret to inform you that your DWSIM Flowsheeting proposal has been disapproved.\n\nProject Title: @project_title\nReason: @reason\n\nBest Wishes,\n\n@site_name Team,\nFOSSEE, IIT Bombay",
- [
- '@name' => $full_name,
- '@project_title' => $project_title,
- '@reason' => $reason,
- '@site_name' => $site_name,
- ],
+ ['@name' => $full_name, '@project_title' => $project_title, '@reason' => $reason, '@site_name' => $site_name],
['langcode' => $langcode]
);
break;
@@ -1262,11 +527,7 @@ function dwsim_flowsheet_mail($key, &$message, $params) {
);
$message['body'][] = t(
"Dear @name,\n\nCongratulations.\n\nYour DWSIM Flowsheeting proposal has been marked as completed.\n\nProject Title: @project_title\n\nBest Wishes,\n\n@site_name Team,\nFOSSEE, IIT Bombay",
- [
- '@name' => $full_name,
- '@project_title' => $project_title,
- '@site_name' => $site_name,
- ],
+ ['@name' => $full_name, '@project_title' => $project_title, '@site_name' => $site_name],
['langcode' => $langcode]
);
break;
@@ -1279,12 +540,7 @@ function dwsim_flowsheet_mail($key, &$message, $params) {
);
$message['body'][] = t(
"Dear @name,\n\nWe have received your uploaded abstract/files for the DWSIM Flowsheeting project.\n\nProject Title: @project_title\nUniversity/Institute: @university\n\nOur team will review your submission and get back to you.\n\nBest Wishes,\n\n@site_name Team,\nFOSSEE, IIT Bombay",
- [
- '@name' => $full_name,
- '@project_title' => $project_title,
- '@university' => $university,
- '@site_name' => $site_name,
- ],
+ ['@name' => $full_name, '@project_title' => $project_title, '@university' => $university, '@site_name' => $site_name],
['langcode' => $langcode]
);
break;
@@ -1294,13 +550,3 @@ function dwsim_flowsheet_mail($key, &$message, $params) {
function circuit_simulation_mail($key, &$message, $params) {
dwsim_flowsheet_mail($key, $message, $params);
}
-
-// function textbook_companion_check_valid_filename($file_name)
-// {
-// if (!preg_match('/^[0-9a-zA-Z\_\.]+$/', $file_name))
-// return FALSE;
-// else if (substr_count($file_name, ".") > 1)
-// return FALSE;
-// else
-// return TRUE;
-// }
diff --git a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.routing.yml b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.routing.yml
index 30cee17..d938ce2 100755
--- a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.routing.yml
+++ b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.routing.yml
@@ -115,24 +115,27 @@ dwsim_flowsheet.download_abstract:
requirements:
_permission: 'dwsim flowsheet download code'
dwsim_flowsheet.download_solution:
- path: /flowsheeting-project/download/solution
+ path: /flowsheeting-project/download/solution/{id}
defaults:
_title: 'Code Download'
_controller: '\Drupal\dwsim_flowsheet\Controller\DefaultController::dwsim_flowsheet_download_solution'
+ id: NULL
requirements:
_permission: 'dwsim flowsheet download code'
dwsim_flowsheet.download_experiment:
- path: /flowsheeting-project/download/experiment
+ path: /flowsheeting-project/download/experiment/{id}
defaults:
_title: 'Code Download'
_controller: '\Drupal\dwsim_flowsheet\Controller\DefaultController::dwsim_flowsheet_download_experiment'
+ id: NULL
requirements:
_permission: 'dwsim flowsheet download code'
dwsim_flowsheet.download_lab:
- path: /flowsheeting-project/download/lab
+ path: /flowsheeting-project/download/lab/{id}
defaults:
_title: 'Code Download'
_controller: '\Drupal\dwsim_flowsheet\Controller\DefaultController::dwsim_flowsheet_download_lab'
+ id: NULL
requirements:
_permission: 'dwsim flowsheet download code'
dwsim_flowsheet.download_full_project:
diff --git a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.services.yml b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.services.yml
index 9d7ed7d..206436a 100755
--- a/modules/custom/dwsim_flowsheet/dwsim_flowsheet.services.yml
+++ b/modules/custom/dwsim_flowsheet/dwsim_flowsheet.services.yml
@@ -1,3 +1,12 @@
-services:
- dwsim_flowsheet_global:
- class: '\Drupal\dwsim_flowsheet\Services\DwsimFlowsheetGlobalFunction'
\ No newline at end of file
+services:
+ dwsim_flowsheet_global:
+ class: '\Drupal\dwsim_flowsheet\Services\DwsimFlowsheetGlobalFunction'
+ arguments: ['@database', '@messenger', '@current_user']
+
+ dwsim_flowsheet.mail_helper:
+ class: '\Drupal\dwsim_flowsheet\Services\MailService'
+ arguments: ['@plugin.manager.mail', '@logger.factory', '@config.factory', '@language_manager']
+
+ dwsim_flowsheet.ajax_helper:
+ class: '\Drupal\dwsim_flowsheet\Services\AjaxHelper'
+ arguments: ['@renderer']
\ No newline at end of file
diff --git a/modules/custom/dwsim_flowsheet/src/Controller/DefaultController.php b/modules/custom/dwsim_flowsheet/src/Controller/DefaultController.php
index 2f72c50..547a861 100755
--- a/modules/custom/dwsim_flowsheet/src/Controller/DefaultController.php
+++ b/modules/custom/dwsim_flowsheet/src/Controller/DefaultController.php
@@ -5,20 +5,19 @@
namespace Drupal\dwsim_flowsheet\Controller;
-use Drupal\Core\Form\FormBase;
-use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\StreamedResponse;
+use Symfony\Component\HttpFoundation\BinaryFileResponse;
+use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\File\FileSystemInterface;
-use Drupal\Service;
use Drupal\user\Entity\User;
use Drupal\Core\Session\AccountInterface;
-use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Render\Markup;
/**
* Default controller for the dwsim_flowsheet module.
@@ -62,7 +61,7 @@ public function dwsim_flowsheet_proposal_pending() {
/* check if there are any pending proposals */
if (!$pending_rows) {
\Drupal::messenger()->addStatus(t('There are no pending proposals.'));
- return '';
+ return [];
} //!$pending_rows
$pending_header = [
'Date of Submission',
@@ -140,7 +139,7 @@ public function dwsim_flowsheet_proposal_all() {
/* check if there are any pending proposals */
if (!$proposal_rows) {
\Drupal::messenger()->addStatus(t('There are no proposals.'));
- return '';
+ return [];
} //!$proposal_rows
$proposal_header = [
'Date of Submission',
@@ -186,8 +185,10 @@ public function dwsim_flowsheet_approved_tab() {
// $records = $result->fetchAll();
if (count($records) == 0) {
- $page_content .= "Approved Proposals under Flowsheeting Project ";
- } //$result->rowCount() == 0
+ $page_content = [
+ '#markup' => "Approved Proposals under Flowsheeting Project ",
+ ];
+ }
else {
$page_content .= "Approved Proposals under Flowsheeting Project: " . count($records) . " ";
$preference_rows = [];
@@ -228,7 +229,9 @@ public function dwsim_flowsheet_uploaded_tab() {
$result = \Drupal::database()->query("SELECT dfp.project_title, dfp.contributor_name, dfp.id, dfp.university, dfa.abstract_upload_date, dfa.abstract_approval_status from dwsim_flowsheet_proposal as dfp JOIN dwsim_flowsheet_submitted_abstracts as dfa on dfa.proposal_id = dfp.id where dfp.id in (select proposal_id from dwsim_flowsheet_submitted_abstracts) AND approval_status = 1");
$records = $result->fetchAll();
if (count($records)== 0) {
- $page_content .= "Uploaded Proposals under Flowsheeting Project ";
+ $page_content = [
+ '#markup' => "Uploaded Proposals under Flowsheeting Project ",
+ ];
}
else {
$page_content .= "Uploaded Proposals under Flowsheeting Project: " . count($records) . " ";
@@ -268,10 +271,8 @@ public function dwsim_flowsheet_abstract() {
$return_html = "";
$proposal_data = dwsim_flowsheet_get_proposal();
if (!$proposal_data) {
-
- // drupal_goto('');
- return;
- } //!$proposal_data
+ return new RedirectResponse(Url::fromRoute('')->toString());
+ }
//$return_html .= l('Upload abstract', 'flowsheeting-project/abstract-code/upload') . ' ';
/* get experiment list */
$query = \Drupal::database()->select('dwsim_flowsheet_submitted_abstracts');
@@ -507,7 +508,7 @@ public function dwsim_flowsheet_download_abstract()
public function dwsim_flowsheet_download_solution() {
- $solution_id = arg(3);
+ $solution_id = \Drupal::routeMatch()->getParameter('id');
$root_path = dwsim_flowsheet_path();
$query = \Drupal::database()->select('dwsim_flowsheet_solution');
$query->fields('dwsim_flowsheet_solution');
@@ -549,23 +550,24 @@ public function dwsim_flowsheet_download_solution() {
$zip_file_count = $zip->numFiles;
$zip->close();
if ($zip_file_count > 0) {
- /* download zip file */
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="CODE' . $solution_data->code_number . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- ob_clean();
- //flush();
- readfile($zip_filename);
- unlink($zip_filename);
- } //$zip_file_count > 0
+ $filename = 'CODE' . $solution_data->code_number . '.zip';
+ $response = new StreamedResponse(function () use ($zip_filename) {
+ readfile($zip_filename);
+ unlink($zip_filename);
+ });
+ $response->headers->set('Content-Type', 'application/zip');
+ $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
+ $response->headers->set('Content-Length', filesize($zip_filename));
+ return $response;
+ }
else {
\Drupal::messenger()->addError("There are no files in this solutions to download");
- drupal_goto('lab-migration/lab-migration-run');
+ return new RedirectResponse(Url::fromRoute('dwsim_flowsheet.run_form')->toString());
}
}
public function dwsim_flowsheet_download_experiment() {
- $experiment_id = (int) arg(3);
+ $experiment_id = (int) \Drupal::routeMatch()->getParameter('id');
$root_path = dwsim_flowsheet_path();
/* get solution data */
$query = \Drupal::database()->select('dwsim_flowsheet_experiment');
@@ -611,24 +613,25 @@ public function dwsim_flowsheet_download_experiment() {
$zip_file_count = $zip->numFiles;
$zip->close();
if ($zip_file_count > 0) {
- /* download zip file */
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="EXP' . $experiment_data->number . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- ob_clean();
- //flush();
- readfile($zip_filename);
- unlink($zip_filename);
- } //$zip_file_count > 0
+ $filename = 'EXP' . $experiment_data->number . '.zip';
+ $response = new StreamedResponse(function () use ($zip_filename) {
+ readfile($zip_filename);
+ unlink($zip_filename);
+ });
+ $response->headers->set('Content-Type', 'application/zip');
+ $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
+ $response->headers->set('Content-Length', filesize($zip_filename));
+ return $response;
+ }
else {
\Drupal::messenger()->addError("There are no solutions in this experiment to download");
- drupal_goto('lab-migration/lab-migration-run');
+ return new RedirectResponse(Url::fromRoute('dwsim_flowsheet.run_form')->toString());
}
}
public function dwsim_flowsheet_download_lab() {
$user = \Drupal::currentUser();
- $lab_id = arg(3);
+ $lab_id = \Drupal::routeMatch()->getParameter('id');
$root_path = dwsim_flowsheet_path();
/* get solution data */
$query = \Drupal::database()->select('dwsim_flowsheet_proposal');
@@ -683,33 +686,19 @@ public function dwsim_flowsheet_download_lab() {
$zip_file_count = $zip->numFiles;
$zip->close();
if ($zip_file_count > 0) {
- if ($user->uid) {
- /* download zip file */
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . str_replace(' ', '_', $lab_data->lab_title) . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- ob_clean();
- //flush();
- readfile($zip_filename);
- unlink($zip_filename);
- } //$user->uid
- else {
- header('Content-Type: application/zip');
- header('Content-disposition: attachment; filename="' . str_replace(' ', '_', $lab_data->lab_title) . '.zip"');
- header('Content-Length: ' . filesize($zip_filename));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- ob_end_flush();
- ob_clean();
- flush();
+ $lab_filename = str_replace(' ', '_', $lab_data->lab_title) . '.zip';
+ $response = new StreamedResponse(function () use ($zip_filename) {
readfile($zip_filename);
unlink($zip_filename);
- }
- } //$zip_file_count > 0
+ });
+ $response->headers->set('Content-Type', 'application/zip');
+ $response->headers->set('Content-Disposition', 'attachment; filename="' . $lab_filename . '"');
+ $response->headers->set('Content-Length', filesize($zip_filename));
+ return $response;
+ }
else {
\Drupal::messenger()->addError("There are no solutions in this Lab to download");
- drupal_goto('lab-migration/lab-migration-run');
+ return new RedirectResponse(Url::fromRoute('dwsim_flowsheet.run_form')->toString());
}
}
@@ -775,26 +764,18 @@ public function dwsim_flowsheet_download_full_project() {
// Check if the zip file contains any files
if ($zip_file_count > 0) {
- // Send the zip file as a response
- $download_name = str_replace(' ', '_', $flowsheet_data->project_title) . '.zip';
-
- header('Content-Type: application/zip');
- header('Content-Disposition: attachment; filename="' . $download_name . '"');
- header('Content-Length: ' . filesize($zip_filename));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- ob_clean(); // Clear output buffer
- flush();
+ $download_name = str_replace(' ', '_', $flowsheet_data->project_title) . '.zip';
+ $response = new StreamedResponse(function () use ($zip_filename) {
readfile($zip_filename);
-
- // Remove the temporary zip file
unlink($zip_filename);
- exit(); // Terminate script execution after sending the file
+ });
+ $response->headers->set('Content-Type', 'application/zip');
+ $response->headers->set('Content-Disposition', 'attachment; filename="' . $download_name . '"');
+ $response->headers->set('Content-Length', filesize($zip_filename));
+ return $response;
} else {
- // No files in the zip
- \Drupal::messenger()->addError(t('There are no flowsheet projects in this proposal to download.'));
- return new RedirectResponse('/flowsheeting-project/full-download/project' . $proposal_id);
+ \Drupal::messenger()->addError(t('There are no flowsheet projects in this proposal to download.'));
+ return new RedirectResponse('/flowsheeting-project/full-download/project/' . $flowsheet_id);
}
}
@@ -811,14 +792,16 @@ public function dwsim_flowsheet_download_completed_proposals() {
// Output the message with the link.
$output .= t('Click @link to download the proposals of the participants.', ['@link' => $link]) . '';
- return $output;
+ return [
+ '#markup' => $output,
+ ];
}
public function dwsim_flowsheet_download_proposals() {
$root_path = dwsim_flowsheet_path();
- $result = \Drupal::database()->query("SELECT e.contributor_name as contirbutor_name, u.mail as email_id, e.project_title as title, e.contact_no as contact, e.university as university, from_unixtime(creation_date,'%d-%m-%Y') as creation, from_unixtime(approval_date,'%d-%m-%Y') as approval, from_unixtime(actual_completion_date,'%d-%m-%Y') as year, e.approval_status as status FROM dwsim_flowsheet_proposal as e JOIN users as u ON e.uid = u.uid ORDER BY actual_completion_date DESC");
+ $result = \Drupal::database()->query("SELECT e.contributor_name as contirbutor_name, u.mail as email_id, e.project_title as title, e.contact_no as contact, e.university as university, from_unixtime(creation_date,'%d-%m-%Y') as creation, from_unixtime(approval_date,'%d-%m-%Y') as approval, from_unixtime(actual_completion_date,'%d-%m-%Y') as year, e.approval_status as status FROM dwsim_flowsheet_proposal as e JOIN users_field_data as u ON e.uid = u.uid AND u.default_langcode = 1 ORDER BY actual_completion_date DESC");
//var_dump($result->rowCount());die();
//$all_proposals_q = $result->execute();
@@ -878,22 +861,14 @@ public function dwsim_flowsheet_download_proposals() {
}
fclose($fp);
if ($participants_proposal_id_file) {
- ob_clean();
- header("Pragma: public");
- header("Expires: 0");
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header("Cache-Control: public");
- header("Content-Description: File Transfer");
- header('Content-Type: application/csv');
- header('Content-disposition: attachment; filename=participants-proposals.csv');
- header('Content-Length:' . filesize($participants_proposal_id_file));
- header("Content-Transfer-Encoding: binary");
- header('Expires: 0');
- header('Pragma: no-cache');
- readfile($participants_proposal_id_file);
- /*ob_end_flush();
- ob_clean();
- flush();*/
+ $response = new StreamedResponse(function () use ($participants_proposal_id_file) {
+ readfile($participants_proposal_id_file);
+ unlink($participants_proposal_id_file);
+ });
+ $response->headers->set('Content-Type', 'application/csv');
+ $response->headers->set('Content-Disposition', 'attachment; filename=participants-proposals.csv');
+ $response->headers->set('Content-Length', filesize($participants_proposal_id_file));
+ return $response;
}
}
@@ -1012,8 +987,7 @@ public function dwsim_flowsheet_progress_all() {
}
public function dwsim_flowsheet_download_user_defined_compound() {
- // $proposal_id = arg(3);
- $proposal_id = \Drupal::routeMatch()->getParameter('proposal_id');
+ $proposal_id = \Drupal::routeMatch()->getParameter('proposal_id');
$root_path = dwsim_flowsheet_document_path();
$query = \Drupal::database()->select('dwsim_flowsheet_proposal');
$query->fields('dwsim_flowsheet_proposal');
@@ -1021,12 +995,14 @@ public function dwsim_flowsheet_download_user_defined_compound() {
$query->range(0, 1);
$result = $query->execute();
$dwsim_flowsheet_user_compund_data = $result->fetchObject();
- $samplecodename = substr($dwsim_flowsheet_user_compund_data->user_defined_compound_filepath, strrpos($dwsim_flowsheet_user_compund_data->user_defined_compound_filepath, '/') + 1);
- header('Content-Type: txt/zip');
- header('Content-disposition: attachment; filename="' . $samplecodename . '"');
- header('Content-Length: ' . filesize($root_path . $dwsim_flowsheet_user_compund_data->directory_name . '/' . $dwsim_flowsheet_user_compund_data->user_defined_compound_filepath));
- ob_clean();
- readfile($root_path . $dwsim_flowsheet_user_compund_data->directory_name . '/' . $dwsim_flowsheet_user_compund_data->user_defined_compound_filepath);
+ $file_path = $root_path . $dwsim_flowsheet_user_compund_data->directory_name . '/' . $dwsim_flowsheet_user_compund_data->user_defined_compound_filepath;
+ $samplecodename = basename($dwsim_flowsheet_user_compund_data->user_defined_compound_filepath);
+ if (!file_exists($file_path)) {
+ throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('File not found.');
+ }
+ $response = new BinaryFileResponse($file_path);
+ $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $samplecodename);
+ return $response;
}
}
diff --git a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractApprovalForm.php b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractApprovalForm.php
index 34e47c6..7f8b2c3 100755
--- a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractApprovalForm.php
+++ b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractApprovalForm.php
@@ -9,10 +9,39 @@
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\Core\Render\Element;
+use Drupal\Core\Link;
+use Drupal\Core\Url;
+use Drupal\dwsim_flowsheet\Services\MailService;
+use Symfony\Component\DependencyInjection\ContainerInterface;
class DwsimFlowsheetAbstractApprovalForm extends FormBase {
+ /**
+ * The mail helper service.
+ *
+ * @var \Drupal\dwsim_flowsheet\Services\MailService
+ */
+ protected $mailHelper;
+
+ /**
+ * Constructs a DwsimFlowsheetAbstractApprovalForm object.
+ *
+ * @param \Drupal\dwsim_flowsheet\Services\MailService $mail_helper
+ * The mail helper service.
+ */
+ public function __construct(MailService $mail_helper) {
+ $this->mailHelper = $mail_helper;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('dwsim_flowsheet.mail_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -33,7 +62,8 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
$solution_data = $solution_q->fetchObject();
if (!$solution_data) {
\Drupal::messenger()->addStatus(t('Invalid solution selected.'));
- drupal_goto('lab-migration/code-approval');
+ $form_state->setRedirectUrl(\Drupal\Core\Url::fromUri('internal:/lab-migration/code-approval'));
+ return $form;
}
if ($solution_data->approval_status == 1) {
\Drupal::messenger()->addError(t('This solution has already been approved. Are you sure you want to change the approval status?'));
@@ -219,7 +249,7 @@ public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface
public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$user = \Drupal::currentUser();
- $solution_id = (int) arg(3);
+ $solution_id = (int) \Drupal::routeMatch()->getParameter('solution_id');
/* get solution details */
//$solution_q = db_query("SELECT * FROM {lab_migration_solution} WHERE id = %d", $solution_id);
$query = \Drupal::database()->select('lab_migration_solution');
@@ -229,7 +259,8 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$solution_data = $solution_q->fetchObject();
if (!$solution_data) {
\Drupal::messenger()->addStatus(t('Invalid solution selected.'));
- drupal_goto('lab_migration/code_approval');
+ $form_state->setRedirectUrl(\Drupal\Core\Url::fromUri('internal:/lab_migration/code_approval'));
+ return;
}
/* get experiment data */
//$experiment_q = db_query("SELECT * FROM {lab_migration_experiment} WHERE id = %d", $solution_data->experiment_id);
@@ -251,43 +282,16 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
if ($form_state->getValue(['approved']) == "0") {
$query = "UPDATE {lab_migration_solution} SET approval_status = 0, approver_uid = :approver_uid, approval_date = :approval_date WHERE id = :solution_id";
$args = [
- ":approver_uid" => $user->uid,
+ ":approver_uid" => $user->id(),
":approval_date" => time(),
":solution_id" => $solution_id,
];
\Drupal::database()->query($query, $args);
/* sending email */
- $email_to = $user_data->mail;
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $from = variable_get('lab_migration_from_email', '');
-
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $bcc = variable_get('lab_migration_emails', '');
-
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $cc = variable_get('lab_migration_cc_emails', '');
-
+ $email_to = $user_data->getEmail();
$param['solution_pending']['solution_id'] = $solution_id;
- $param['solution_pending']['user_id'] = $user_data->uid;
- $param['solution_pending']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('lab_migration', 'solution_pending', $email_to, language_default(), $param, $from, TRUE)) {
+ $param['solution_pending']['user_id'] = $user_data->id();
+ if (!$this->mailHelper->sendMail('lab_migration', 'solution_pending', $email_to, $param)) {
\Drupal::messenger()->addError('Error sending email message.');
}
}
@@ -295,43 +299,16 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
if ($form_state->getValue(['approved']) == "1") {
$query = "UPDATE {lab_migration_solution} SET approval_status = 1, approver_uid = :approver_uid, approval_date = :approval_date WHERE id = :solution_id";
$args = [
- ":approver_uid" => $user->uid,
+ ":approver_uid" => $user->id(),
":approval_date" => time(),
":solution_id" => $solution_id,
];
\Drupal::database()->query($query, $args);
/* sending email */
- $email_to = $user_data->mail;
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $from = variable_get('lab_migration_from_email', '');
-
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $bcc = variable_get('lab_migration_emails', '');
-
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $cc = variable_get('lab_migration_cc_emails', '');
-
+ $email_to = $user_data->getEmail();
$param['solution_approved']['solution_id'] = $solution_id;
- $param['solution_approved']['user_id'] = $user_data->uid;
- $param['solution_approved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('lab_migration', 'solution_approved', $email_to, language_default(), $param, $from, TRUE)) {
+ $param['solution_approved']['user_id'] = $user_data->id();
+ if (!$this->mailHelper->sendMail('lab_migration', 'solution_approved', $email_to, $param)) {
\Drupal::messenger()->addError('Error sending email message.');
}
}
@@ -339,41 +316,14 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
if ($form_state->getValue(['approved']) == "2") {
if (lab_migration_delete_solution($solution_id)) {
/* sending email */
- $email_to = $user_data->mail;
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $from = variable_get('lab_migration_from_email', '');
-
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $bcc = variable_get('lab_migration_emails', '');
-
- // @FIXME
- // // @FIXME
- // // This looks like another module's variable. You'll need to rewrite this call
- // // to ensure that it uses the correct configuration object.
- // $cc = variable_get('lab_migration_cc_emails', '');
-
+ $email_to = $user_data->getEmail();
$param['solution_disapproved']['experiment_number'] = $experiment_data->number;
$param['solution_disapproved']['experiment_title'] = $experiment_data->title;
$param['solution_disapproved']['solution_number'] = $solution_data->code_number;
$param['solution_disapproved']['solution_caption'] = $solution_data->caption;
- $param['solution_disapproved']['user_id'] = $user_data->uid;
+ $param['solution_disapproved']['user_id'] = $user_data->id();
$param['solution_disapproved']['message'] = $form_state->getValue(['message']);
- $param['solution_disapproved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- if (!drupal_mail('lab_migration', 'solution_disapproved', $email_to, language_default(), $param, $from, TRUE)) {
+ if (!$this->mailHelper->sendMail('lab_migration', 'solution_disapproved', $email_to, $param)) {
\Drupal::messenger()->addError('Error sending email message.');
}
}
@@ -384,7 +334,7 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
}
}
\Drupal::messenger()->addStatus('Updated successfully.');
- drupal_goto('lab-migration/code-approval');
+ $form_state->setRedirectUrl(\Drupal\Core\Url::fromUri('internal:/lab-migration/code-approval'));
}
}
diff --git a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractBulkApprovalForm.php b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractBulkApprovalForm.php
index 1372de5..a938573 100755
--- a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractBulkApprovalForm.php
+++ b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetAbstractBulkApprovalForm.php
@@ -18,8 +18,47 @@
use Drupal\Core\Url;
use Drupal\Core\Render\RendererInterface;
+use Drupal\dwsim_flowsheet\Services\MailService;
+use Drupal\dwsim_flowsheet\Services\AjaxHelper;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
class DwsimFlowsheetAbstractBulkApprovalForm extends FormBase {
+ /**
+ * The mail helper service.
+ *
+ * @var \Drupal\dwsim_flowsheet\Services\MailService
+ */
+ protected $mailHelper;
+
+ /**
+ * The ajax response helper service.
+ *
+ * @var \Drupal\dwsim_flowsheet\Services\AjaxHelper
+ */
+ protected $ajaxHelper;
+
+ /**
+ * Constructs a DwsimFlowsheetAbstractBulkApprovalForm object.
+ *
+ * @param \Drupal\dwsim_flowsheet\Services\MailService $mail_helper
+ * @param \Drupal\dwsim_flowsheet\Services\AjaxHelper $ajax_helper
+ */
+ public function __construct(MailService $mail_helper, AjaxHelper $ajax_helper) {
+ $this->mailHelper = $mail_helper;
+ $this->ajaxHelper = $ajax_helper;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('dwsim_flowsheet.mail_helper'),
+ $container->get('dwsim_flowsheet.ajax_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -91,25 +130,19 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
function ajax_bulk_flowsheet_abstract_details_callback(array &$form, FormStateInterface $form_state) {
- $response = new AjaxResponse();
-
$flowsheet_project_default_value = $form_state->getValue('flowsheet_project');
if ($flowsheet_project_default_value != 0) {
- // Update the selected flowsheet details.
$details_html = $this->_flowsheet_details($flowsheet_project_default_value);
- $response->addCommand(new HtmlCommand('#ajax_selected_flowsheet', $details_html));
-
- // Update the flowsheet actions dropdown.
$form['flowsheet_actions']['#options'] = $this->_bulk_list_flowsheet_actions();
- $flowsheet_actions_rendered = \Drupal::service('renderer')->render($form['flowsheet_actions']);
- $response->addCommand(new ReplaceCommand('#ajax_selected_flowsheet_action', $flowsheet_actions_rendered));
+
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_selected_flowsheet' => ['type' => 'html', 'content' => $details_html],
+ '#ajax_selected_flowsheet_action' => ['type' => 'replace', 'content' => $form['flowsheet_actions']],
+ ]);
} else {
- // Clear the selected flowsheet details and flowsheet actions.
- $response->addCommand(new HtmlCommand('#ajax_selected_flowsheet', ''));
+ return $this->ajaxHelper->htmlWrapper('#ajax_selected_flowsheet', '');
}
-
- return $response;
}
public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$user = \Drupal::currentUser();
@@ -185,33 +218,14 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
// );
/** sending email when everything done **/
- $email_to = $user_data->mail;
- $from = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_from_email');
- $bcc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_emails');
- $cc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_cc_emails');
- $params['standard']['subject'] = $email_subject ?? NULL;
- $params['standard']['body'] = $email_body ?? NULL;
- $params['standard']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- $mail_result = \Drupal::service('plugin.manager.mail')->mail(
+ $email_to = $user_data->getEmail();
+ $this->mailHelper->sendNotification(
'dwsim_flowsheet',
'standard',
$email_to,
- $langcode,
- $params,
- $from,
- TRUE
+ $email_subject ?? NULL,
+ $email_body ?? NULL
);
- if (empty($mail_result['result'])) {
- $msg = \Drupal::messenger()->addError('Error sending email message.');
- }
} //$form_state['values']['flowsheet_actions'] == 1
elseif ($form_state->getValue(['flowsheet_actions']) == 2) {
//pending review entire project
@@ -263,33 +277,14 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
// );
/** sending email when everything done **/
- $email_to = $user_data->mail;
- $from = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_from_email');
- $bcc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_emails');
- $cc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_cc_emails');
- $params['standard']['subject'] = $email_subject ?? NULL;
- $params['standard']['body'] = $email_body ?? NULL;
- $params['standard']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- $mail_result = \Drupal::service('plugin.manager.mail')->mail(
+ $email_to = $user_data->getEmail();
+ $this->mailHelper->sendNotification(
'dwsim_flowsheet',
'standard',
$email_to,
- $langcode,
- $params,
- $from,
- TRUE
+ $email_subject ?? NULL,
+ $email_body ?? NULL
);
- if (empty($mail_result['result'])) {
- \Drupal::messenger()->addError('Error sending email message.');
- }
} //$form_state['values']['flowsheet_actions'] == 2
elseif ($form_state->getValue(['flowsheet_actions']) == 3) //disapprove and delete entire flowsheeting project
{
@@ -338,33 +333,14 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
// ))
// );
- $email_to = $user_data->mail;
- $from = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_from_email');
- $bcc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_emails');
- $cc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_cc_emails');
- $params['standard']['subject'] = $email_subject ?? NULL;
- $params['standard']['body'] = $email_body ?? NULL;
- $params['standard']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- $mail_result = \Drupal::service('plugin.manager.mail')->mail(
+ $email_to = $user_data->getEmail();
+ $this->mailHelper->sendNotification(
'dwsim_flowsheet',
'standard',
$email_to,
- $langcode,
- $params,
- $from,
- TRUE
+ $email_subject ?? NULL,
+ $email_body ?? NULL
);
- if (empty($mail_result['result'])) {
- \Drupal::messenger()->addError('Error sending email message.');
- }
} //dwsim_flowsheet_abstract_delete_project($form_state['values']['flowsheet_project'])
else {
\Drupal::messenger()->addError(t('Error Dis-Approving and Deleting Entire flowsheeting project.'));
@@ -588,7 +564,7 @@ public function _flowsheet_details($flowsheet_proposal_id) {
$return_html .= 'Unit Operations used in DWSIM: ' . $unit_operations_used_in_dwsim . ' ';
$return_html .= 'Thermodynamic Packages Used: ' . $thermodynamic_packages_used . ' ';
$return_html .= 'Logical Blocks used: ' . $logical_blocks_used . ' ';
- $return_html .= 'Name of compound for which process development is carried out: ' . render($prodata) . ' ';
+ $return_html .= 'Name of compound for which process development is carried out: ' . \Drupal::service('renderer')->render($prodata) . ' ';
$return_html .= 'List of compounds from DWSIM Database used in process flowsheet: ' . $abstracts_pro->dwsim_database_compound_name . ' ';
$return_html .= 'Uploaded an abstract (brief outline) of the project: ' . $abstract_filename . ' ';
$return_html .= 'Upload the DWSIM flowsheet for the developed process: ' . $abstracts_query_process_filename . ' ';
diff --git a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetCompletedTabForm.php b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetCompletedTabForm.php
index 2ff8298..940595f 100755
--- a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetCompletedTabForm.php
+++ b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetCompletedTabForm.php
@@ -24,9 +24,36 @@
use Drupal\Core\Database\Database;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Mail\MailManager;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\dwsim_flowsheet\Services\AjaxHelper;
class DwsimFlowsheetCompletedTabForm extends FormBase {
+ /**
+ * The ajax response helper service.
+ *
+ * @var \Drupal\dwsim_flowsheet\Services\AjaxHelper
+ */
+ protected $ajaxHelper;
+
+ /**
+ * Constructs a DwsimFlowsheetCompletedTabForm object.
+ *
+ * @param \Drupal\dwsim_flowsheet\Services\AjaxHelper $ajax_helper
+ */
+ public function __construct(AjaxHelper $ajax_helper) {
+ $this->ajaxHelper = $ajax_helper;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('dwsim_flowsheet.ajax_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -66,8 +93,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
public function ajax_example_autocheckboxes_callback(array &$form, FormStateInterface $form_state) {
- $response = new AjaxResponse();
- $flowsheet_project_default_value = $form_state->getValue('howmany_select'); // Correct form state access
+ $flowsheet_project_default_value = $form_state->getValue('howmany_select');
if ($flowsheet_project_default_value != 0) {
// Update the form options dynamically
@@ -76,19 +102,19 @@ public function ajax_example_autocheckboxes_callback(array &$form, FormStateInte
// Example dynamic content
$dynamic_content = $this->_flowsheet_details($flowsheet_project_default_value);
- // Replace content dynamically
- $response->addCommand(new HtmlCommand('#ajax-selected-flowsheet', $dynamic_content));
- $response->addCommand(new ReplaceCommand('#ajax_selected_flowsheet_action', \Drupal::service('renderer')->render($form['howmany_select'])));
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax-selected-flowsheet' => ['type' => 'html', 'content' => $dynamic_content],
+ '#ajax_selected_flowsheet_action' => ['type' => 'replace', 'content' => $form['howmany_select']],
+ ]);
}
else {
// Reset the form state value to "Please select..."
$form['howmany_select']['#options'] = ['Please select...' => 'Please select...'];
- // Use DataCommand for JavaScript context
- $response->addCommand(new DataCommand('#ajax_selected_flowsheet', 'form_state_value_select', $form_state->getValue('howmany_select')));
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_selected_flowsheet' => ['type' => 'data', 'name' => 'form_state_value_select', 'value' => $form_state->getValue('howmany_select')],
+ ]);
}
-
- return $response;
}
// public function ajax_example_autocheckboxes_callback(array &$form, FormStateInterface $form_state)
diff --git a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalApprovalForm.php b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalApprovalForm.php
index 0827ba9..dbd517d 100755
--- a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalApprovalForm.php
+++ b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalApprovalForm.php
@@ -19,11 +19,38 @@
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Mail\MailManagerInterface;
-use Drupal\Core\DependencyInjection\ContainerInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountProxy;
+use Drupal\dwsim_flowsheet\Services\MailService;
+
class DwsimFlowsheetProposalApprovalForm extends FormBase {
+ /**
+ * The mail helper service.
+ *
+ * @var \Drupal\dwsim_flowsheet\Services\MailService
+ */
+ protected $mailHelper;
+
+ /**
+ * Constructs a DwsimFlowsheetProposalApprovalForm object.
+ *
+ * @param \Drupal\dwsim_flowsheet\Services\MailService $mail_helper
+ */
+ public function __construct(MailService $mail_helper) {
+ $this->mailHelper = $mail_helper;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('dwsim_flowsheet.mail_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -49,24 +76,12 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
} //$proposal_data = $proposal_q->fetchObject()
else {
\Drupal::messenger()->addError(t('Invalid proposal selected. Please try again.'));
- $url = Url::fromRoute('dwsim_flowsheet.proposal_approval_form')->toString();
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
- // drupal_goto('flowsheeting-project/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
- // Send the redirect response
- $response->send();
- return;
+ return new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
}
} //$proposal_q
else {
\Drupal::messenger()->addError(t('Invalid proposal selected. Please try again.'));
- $url = Url::fromRoute('dwsim_flowsheet.proposal_approval_form')->toString();
- \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
- // drupal_goto('flowsheeting-project/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
- // Send the redirect response
- $response->send();
- return;
+ return new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
}
if ($proposal_data->project_guide_name == "NULL" || $proposal_data->project_guide_name == "") {
$project_guide_name = "Not Entered";
@@ -301,19 +316,13 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
} //$proposal_data = $proposal_q->fetchObject()
else {
\Drupal::messenger()->addError(t('Invalid proposal selected. Please try again.'));
- // drupal_goto('flowsheeting-project/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
- // Send the redirect response
- $response->send();
+ $form_state->setRedirect('dwsim_flowsheet.proposal_pending_0');
return;
}
} //$proposal_q
else {
\Drupal::messenger()->addError(t('Invalid proposal selected. Please try again.'));
- // drupal_goto('flowsheeting-project/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
- // Send the redirect response
- $response->send();
+ $form_state->setRedirect('dwsim_flowsheet.proposal_pending_0');
return;
}
if ($form_state->getValue(['approval']) == 1) {
@@ -326,39 +335,16 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
\Drupal::database()->query($query, $args);
/* sending email */
$user_data = \Drupal::entityTypeManager()->getStorage('user')->load($proposal_data->uid);
- $email_to = $user_data->mail;
- $from = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_from_email');
- $bcc = $user->mail . ', ' . \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_emails');
- $cc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_cc_emails');
- $params['dwsim_flowsheet_proposal_approved']['proposal_id'] = $proposal_id;
- $params['dwsim_flowsheet_proposal_approved']['user_id'] = $proposal_data->uid;
- $params['dwsim_flowsheet_proposal_approved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
- $mail_result = \Drupal::service('plugin.manager.mail')->mail(
+ $email_to = $user_data->getEmail();
+
+ $this->mailHelper->sendApprovalMail(
'dwsim_flowsheet',
- 'dwsim_flowsheet_proposal_approved',
- $email_to,
- $langcode,
- $params,
- $from,
- TRUE
+ $proposal_id,
+ $proposal_data->uid,
+ $email_to
);
- if (empty($mail_result['result'])) {
- \Drupal::messenger()->addError('Error sending email message.');
- }
\Drupal::messenger()->addStatus('DWSIM flowsheeting proposal No. ' . $proposal_id . ' approved. User has been notified of the approval.');
- // drupal_goto('flowsheeting-project/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
- // Send the redirect response
- $response->send();
+ $form_state->setRedirect('dwsim_flowsheet.proposal_pending_0');
return;
} //$form_state['values']['approval'] == 1
else {
@@ -373,40 +359,17 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$result = \Drupal::database()->query($query, $args);
/* sending email */
$user_data = \Drupal::entityTypeManager()->getStorage('user')->load($proposal_data->uid);
- $email_to = $user_data->mail;
- $from = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_from_email');
- $bcc = $user->mail . ', ' . \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_emails');
- $cc = \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_cc_emails');
- $params['dwsim_flowsheet_proposal_disapproved']['proposal_id'] = $proposal_id;
- $params['dwsim_flowsheet_proposal_disapproved']['user_id'] = $proposal_data->uid;
- $params['dwsim_flowsheet_proposal_disapproved']['reason'] = $form_state->getValue(['message']);
- $params['dwsim_flowsheet_proposal_disapproved']['headers'] = [
- 'From' => $from,
- 'MIME-Version' => '1.0',
- 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
- 'Content-Transfer-Encoding' => '8Bit',
- 'X-Mailer' => 'Drupal',
- 'Cc' => $cc,
- 'Bcc' => $bcc,
- ];
- $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
- $mail_result = \Drupal::service('plugin.manager.mail')->mail(
+ $email_to = $user_data->getEmail();
+
+ $this->mailHelper->sendRejectionMail(
'dwsim_flowsheet',
- 'dwsim_flowsheet_proposal_disapproved',
+ $proposal_id,
+ $proposal_data->uid,
$email_to,
- $langcode,
- $params,
- $from,
- TRUE
+ $form_state->getValue(['message'])
);
- if (empty($mail_result['result'])) {
- \Drupal::messenger()->addError('Error sending email message.');
- }
\Drupal::messenger()->addError('DWSIM flowsheeting proposal No. ' . $proposal_id . ' dis-approved. User has been notified of the dis-approval.');
- // drupal_goto('flowsheeting-project/manage-proposal');
- $response = new RedirectResponse(Url::fromRoute('dwsim_flowsheet.proposal_pending_0')->toString());
- // Send the redirect response
- $response->send();
+ $form_state->setRedirect('dwsim_flowsheet.proposal_pending_0');
return;
}
} //$form_state['values']['approval'] == 2
diff --git a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalEditForm.php b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalEditForm.php
index 788f05f..f1f3d14 100755
--- a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalEditForm.php
+++ b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetProposalEditForm.php
@@ -310,13 +310,13 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
} //$proposal_data = $proposal_q->fetchObject()
else {
\Drupal::messenger()->addError(t('Invalid proposal selected. Please try again.'));
- drupal_goto('flowsheeting-project/manage-proposal');
+ $form_state->setRedirect('dwsim_flowsheet.proposal_pending_0');
return;
}
} //$proposal_q
else {
\Drupal::messenger()->addError(t('Invalid proposal selected. Please try again.'));
- drupal_goto('flowsheeting-project/manage-proposal');
+ $form_state->setRedirect('dwsim_flowsheet.proposal_pending_0');
return;
}
/* delete proposal */
diff --git a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetRunForm.php b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetRunForm.php
index d7b5c2f..5c96052 100755
--- a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetRunForm.php
+++ b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetRunForm.php
@@ -17,8 +17,36 @@
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\user\Entity\User;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\dwsim_flowsheet\Services\AjaxHelper;
+
class DwsimFlowsheetRunForm extends FormBase {
+ /**
+ * The ajax response helper service.
+ *
+ * @var \Drupal\dwsim_flowsheet\Services\AjaxHelper
+ */
+ protected $ajaxHelper;
+
+ /**
+ * Constructs a DwsimFlowsheetRunForm object.
+ *
+ * @param \Drupal\dwsim_flowsheet\Services\AjaxHelper $ajax_helper
+ */
+ public function __construct(AjaxHelper $ajax_helper) {
+ $this->ajaxHelper = $ajax_helper;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('dwsim_flowsheet.ajax_helper')
+ );
+ }
+
/**
* {@inheritdoc}
*/
@@ -100,13 +128,10 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
function dwsim_flowsheet_project_details_callback($form, &$form_state)
{
- $response = new AjaxResponse();
$flowsheet_default_value = $form_state->getValue('flowsheet');
if ($flowsheet_default_value != 0) {
$flowsheet_details_markup = $this->_flowsheet_details($flowsheet_default_value);
- $response->addCommand(new HtmlCommand('#ajax_flowsheet_details', $flowsheet_details_markup));
-
$flowsheet_details = $this->_flowsheet_information($flowsheet_default_value);
if ($flowsheet_details && $flowsheet_details->uid > 0) {
@@ -126,18 +151,25 @@ function dwsim_flowsheet_project_details_callback($form, &$form_state)
])
)->toString();
- $response->addCommand(new HtmlCommand('#ajax_selected_flowsheet', $abstract_link . ' ' . $flowsheet_link));
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_flowsheet_details' => ['type' => 'html', 'content' => $flowsheet_details_markup],
+ '#ajax_selected_flowsheet' => ['type' => 'html', 'content' => $abstract_link . ' ' . $flowsheet_link],
+ '#ajax_selected_flowsheet_dwsim' => ['type' => 'html', 'content' => ''],
+ ]);
} else {
- $response->addCommand(new HtmlCommand('#ajax_selected_flowsheet', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_flowsheet_dwsim', ''));
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_flowsheet_details' => ['type' => 'html', 'content' => $flowsheet_details_markup],
+ '#ajax_selected_flowsheet' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_flowsheet_dwsim' => ['type' => 'html', 'content' => ''],
+ ]);
}
} else {
- $response->addCommand(new HtmlCommand('#ajax_flowsheet_details', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_flowsheet', ''));
- $response->addCommand(new HtmlCommand('#ajax_selected_flowsheet_dwsim', ''));
+ return $this->ajaxHelper->buildMultiCommandResponse([
+ '#ajax_flowsheet_details' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_flowsheet' => ['type' => 'html', 'content' => ''],
+ '#ajax_selected_flowsheet_dwsim' => ['type' => 'html', 'content' => ''],
+ ]);
}
-
- return $response;
}
function bootstrap_table_format($headers, $rows)
diff --git a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetUploadAbstractCodeForm.php b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetUploadAbstractCodeForm.php
index df2f4ce..bec49aa 100755
--- a/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetUploadAbstractCodeForm.php
+++ b/modules/custom/dwsim_flowsheet/src/Form/DwsimFlowsheetUploadAbstractCodeForm.php
@@ -19,7 +19,7 @@
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Database\Database;
use Drupal\Core\Messenger\MessengerInterface;
-use Drupal\Core\Mail\MailManager;
+use Drupal\Core\Mail\MailManagerInterface;
class DwsimFlowsheetUploadAbstractCodeForm extends FormBase {
@@ -313,11 +313,9 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#type' => 'submit',
'#value' => t('Add more compounds'),
'#limit_validation_errors' => [],
- '#submit' => [
- 'user_defined_compounds_add_more_add_one'
- ],
+ '#submit' => [[$this, 'userDefinedCompoundsAddOne']],
'#ajax' => [
- 'callback' => 'user_defined_compounds_add_more_callback',
+ 'callback' => [$this, 'userDefinedCompoundsAjaxCallback'],
'wrapper' => 'user-defined-compounds-fieldset-wrapper',
],
];
@@ -326,13 +324,11 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#type' => 'submit',
'#value' => t('Remove compounds'),
'#limit_validation_errors' => [],
- '#submit' => [
- 'user_defined_compounds_add_more_remove_one'
- ],
- '#ajax' => [
- 'callback' => 'user_defined_compounds_add_more_remove_one',
- 'wrapper' => 'user-defined-compounds-fieldset-wrapper',
- ],
+ '#submit' => [[$this, 'userDefinedCompoundsRemoveOne']],
+ '#ajax' => [
+ 'callback' => [$this, 'userDefinedCompoundsAjaxCallback'],
+ 'wrapper' => 'user-defined-compounds-fieldset-wrapper',
+ ],
];
} //$form_state['num_user_defined_compounds'] > 1
$existing_uploaded_udc_file = $this->default_value_for_uploaded_files("UDC", $proposal_data->id);
@@ -351,12 +347,10 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
'#title' => t('Upload an user defiend compound.'),
'#description' => t('Current File : ' . $udcfilename . ' Separate filenames with underscore. No spaces or any special characters allowed in filename.') . ' ' . t('Allowed file extensions : ') . \Drupal::config('dwsim_flowsheet.settings')->get('dwsim_flowsheet_user_defind_compound_source_extensions') . ' ',
];
- if ($no_js_use) {
- if (!empty($form['user_defined_compound_fieldset']['remove_user_defined_compounds']['#ajax'])) {
+ if (!empty($form['user_defined_compound_fieldset']['remove_user_defined_compounds']['#ajax'])) {
unset($form['user_defined_compound_fieldset']['remove_user_defined_compounds']['#ajax']);
- } //!empty($form['user_defined_compound_fieldset']['remove_user_defined_compounds']['#ajax'])
+ }
unset($form['user_defined_compound_fieldset']['add_user_defined_compounds']['#ajax']);
- } //$no_js_use
}
//////////////////////////////////////////////////////
$existing_uploaded_A_file = $this->default_value_for_uploaded_files("A", $proposal_data->id);
@@ -399,42 +393,39 @@ public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $for
public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
if ($form_state->getValue(['unit_operations_used_in_dwsim'])) {
- $unit_operations_used_in_dwsim = implode(", ", $_POST['unit_operations_used_in_dwsim']);
+ $unit_ops = $form_state->getValue(['unit_operations_used_in_dwsim']);
+ $unit_operations_used_in_dwsim = is_array($unit_ops) ? implode(", ", $unit_ops) : $unit_ops;
$form_state->setValue(['unit_operations_used_in_dwsim'], $unit_operations_used_in_dwsim);
- } //$form_state['values']['unit_operations_used_in_dwsim']
+ }
else {
$form_state->setErrorByName('unit_operations_used_in_dwsim', t('Please select.'));
}
if ($form_state->getValue(['thermodynamic_packages_used'])) {
- $thermodynamic_packages_used = implode(", ", $_POST['thermodynamic_packages_used']);
+ $thermo = $form_state->getValue(['thermodynamic_packages_used']);
+ $thermodynamic_packages_used = is_array($thermo) ? implode(", ", $thermo) : $thermo;
$form_state->setValue(['thermodynamic_packages_used'], $thermodynamic_packages_used);
- } //$form_state['values']['thermodynamic_packages_used']
+ }
else {
$form_state->setErrorByName('thermodynamic_packages_used', t('Please select.'));
}
if ($form_state->getValue(['logical_blocks_used']) != "") {
- $logical_blocks_used_in = $_POST['logical_blocks_used'];
- if ($logical_blocks_used_in != "") {
- if ($logical_blocks_used_in) {
- $logical_blocks_used = implode(", ", $logical_blocks_used_in);
- $form_state->setValue(['logical_blocks_used'], $logical_blocks_used);
- } //$form_state['values']['logical_blocks_used']
- } //$logical_blocks_used_in != ""
+ $logical_blocks = $form_state->getValue(['logical_blocks_used']);
+ if ($logical_blocks) {
+ $logical_blocks_used = is_array($logical_blocks) ? implode(", ", $logical_blocks) : $logical_blocks;
+ $form_state->setValue(['logical_blocks_used'], $logical_blocks_used);
+ }
else {
$form_state->setValue(['logical_blocks_used'], "Not entered");
}
- } //$form_state['values']['logical_blocks_used']
+ }
else {
$form_state->setValue(['logical_blocks_used'], "Not entered");
}
- if ($form_state->getValue([
- 'list_of_compounds_from_dwsim_database_used_in_process_flowsheet'
- ])) {
- $list_of_compounds_from_dwsim_database_used_in_process_flowsheet = implode("| ", $_POST['list_of_compounds_from_dwsim_database_used_in_process_flowsheet']);
- $form_state->setValue([
- 'list_of_compounds_from_dwsim_database_used_in_process_flowsheet'
- ], $list_of_compounds_from_dwsim_database_used_in_process_flowsheet);
- } //$form_state['values']['list_of_compounds_from_dwsim_database_used_in_process_flowsheet']
+ if ($form_state->getValue(['list_of_compounds_from_dwsim_database_used_in_process_flowsheet'])) {
+ $compounds = $form_state->getValue(['list_of_compounds_from_dwsim_database_used_in_process_flowsheet']);
+ $compound_str = is_array($compounds) ? implode("| ", $compounds) : $compounds;
+ $form_state->setValue(['list_of_compounds_from_dwsim_database_used_in_process_flowsheet'], $compound_str);
+ }
if (isset($_FILES['files'])) {
/* check if file is uploaded */
$existing_uploaded_A_file = $this->default_value_for_uploaded_files("A", $form_state->getValue([
@@ -908,55 +899,31 @@ public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $f
$response->send();
}
-}
-
-function default_value_for_selections($operation, $proposal_id) {
- $query = Database::getConnection()->select('dwsim_flowsheet_submitted_abstracts', 'a');
- $query->fields('a');
- $query->condition('proposal_id', $proposal_id);
- $abstracts_q = $query->execute()->fetchObject();
-
- $selected_package_array = [];
-
- if ($abstracts_q) {
- if ($operation === "unit_operations_used_in_dwsim" && !empty($abstracts_q->unit_operations_used_in_dwsim)) {
- $selected_package_array = array_map('trim', explode(',', $abstracts_q->unit_operations_used_in_dwsim));
- } elseif ($operation === "thermodynamic_packages_used" && !empty($abstracts_q->thermodynamic_packages_used)) {
- $selected_package_array = array_map('trim', explode(',', $abstracts_q->thermodynamic_packages_used));
- } elseif ($operation === "logical_blocks_used" && !empty($abstracts_q->logical_blocks_used)) {
- $selected_package_array = array_map('trim', explode(',', $abstracts_q->logical_blocks_used));
- } elseif ($operation === "dwsim_database_compound_name") {
- $query = Database::getConnection()->select('dwsim_flowsheet_proposal', 'p');
- $query->fields('p');
- $query->condition('id', $proposal_id);
- $proposal_q = $query->execute()->fetchObject();
-
- if (!empty($proposal_q->dwsim_database_compound_name)) {
- $selected_package_array = array_map('trim', explode('| ', $proposal_q->dwsim_database_compound_name));
- }
- }
+ /**
+ * AJAX callback: returns the user-defined compounds wrapper.
+ */
+ public function userDefinedCompoundsAjaxCallback(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ return $form['user_defined_compound_fieldset'];
}
- return $selected_package_array;
-}
-
-function default_value_for_uploaded_files($filetype, $proposal_id) {
- $selected_files_array = null;
+ /**
+ * Submit handler: adds one more user-defined compound row.
+ */
+ public function userDefinedCompoundsAddOne(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ $count = $form_state->get(['num_user_defined_compounds']) ?? 1;
+ $form_state->set(['num_user_defined_compounds'], $count + 1);
+ $form_state->setRebuild();
+ }
- if (in_array($filetype, ['A', 'S'])) {
- $query = Database::getConnection()->select('dwsim_flowsheet_submitted_abstracts_file', 'f');
- $query->fields('f');
- $query->condition('proposal_id', $proposal_id);
- $query->condition('filetype', $filetype);
- $selected_files_array = $query->execute()->fetchObject();
- } elseif ($filetype === "UDC") {
- $query = Database::getConnection()->select('dwsim_flowsheet_proposal', 'p');
- $query->fields('p');
- $query->condition('id', $proposal_id);
- $selected_files_array = $query->execute()->fetchObject();
+ /**
+ * Submit handler: removes the last user-defined compound row.
+ */
+ public function userDefinedCompoundsRemoveOne(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
+ $count = $form_state->get(['num_user_defined_compounds']) ?? 1;
+ if ($count > 1) {
+ $form_state->set(['num_user_defined_compounds'], $count - 1);
+ }
+ $form_state->setRebuild();
}
- return $selected_files_array;
}
-
-?>
diff --git a/modules/custom/dwsim_flowsheet/src/Services/AjaxHelper.php b/modules/custom/dwsim_flowsheet/src/Services/AjaxHelper.php
new file mode 100644
index 0000000..62cb9bf
--- /dev/null
+++ b/modules/custom/dwsim_flowsheet/src/Services/AjaxHelper.php
@@ -0,0 +1,124 @@
+renderer = $renderer;
+ }
+
+ /**
+ * Replaces the HTML of a given selector.
+ *
+ * @param string $selector
+ * The CSS selector.
+ * @param string|array $content
+ * The content to replace with (string or render array).
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function replaceWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered_content = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new ReplaceCommand($selector, $rendered_content));
+ return $response;
+ }
+
+ /**
+ * Sets the inner HTML of a given selector.
+ *
+ * @param string $selector
+ * The CSS selector.
+ * @param string|array $content
+ * The content to set (string or render array).
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function htmlWrapper($selector, $content) {
+ $response = new AjaxResponse();
+ $rendered_content = is_array($content) ? $this->renderer->render($content) : $content;
+ $response->addCommand(new HtmlCommand($selector, $rendered_content));
+ return $response;
+ }
+
+ /**
+ * Generates a DataCommand response.
+ *
+ * @param string $selector
+ * The CSS selector.
+ * @param string $name
+ * The data attribute name.
+ * @param mixed $value
+ * The data value.
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function dataCommand($selector, $name, $value) {
+ $response = new AjaxResponse();
+ $response->addCommand(new DataCommand($selector, $name, $value));
+ return $response;
+ }
+
+ /**
+ * Returns a generic message command.
+ *
+ * @param string $message
+ * The message to display.
+ * @param string $type
+ * The message type (status, warning, error). Defaults to 'status'.
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function messageCommand($message, $type = 'status') {
+ $response = new AjaxResponse();
+ // Using MessageCommand directly inside a specific wrapper or globally
+ $response->addCommand(new MessageCommand($message, NULL, ['type' => $type]));
+ return $response;
+ }
+
+ /**
+ * Combine multiple HTML and Replace commands.
+ *
+ * @param array $commands
+ * An array where keys are selectors and values are arrays with 'type' ('html' or 'replace') and 'content'.
+ *
+ * @return \Drupal\Core\Ajax\AjaxResponse
+ */
+ public function buildMultiCommandResponse(array $commands) {
+ $response = new AjaxResponse();
+ foreach ($commands as $selector => $data) {
+ $rendered_content = is_array($data['content']) ? $this->renderer->render($data['content']) : $data['content'];
+ if ($data['type'] === 'html') {
+ $response->addCommand(new HtmlCommand($selector, $rendered_content));
+ } elseif ($data['type'] === 'replace') {
+ $response->addCommand(new ReplaceCommand($selector, $rendered_content));
+ } elseif ($data['type'] === 'data') {
+ $response->addCommand(new DataCommand($selector, $data['name'], $data['value']));
+ }
+ }
+ return $response;
+ }
+}
diff --git a/modules/custom/dwsim_flowsheet/src/Services/DwsimFlowsheetGlobalFunction.php b/modules/custom/dwsim_flowsheet/src/Services/DwsimFlowsheetGlobalFunction.php
index 282bec5..620a836 100755
--- a/modules/custom/dwsim_flowsheet/src/Services/DwsimFlowsheetGlobalFunction.php
+++ b/modules/custom/dwsim_flowsheet/src/Services/DwsimFlowsheetGlobalFunction.php
@@ -2,484 +2,383 @@
namespace Drupal\dwsim_flowsheet\Services;
-use Drupal\Core\Extension\ModuleHandlerInterface;
-use Drupal\Core\File\FileSystemInterface;
-use Drupal\Core\Link;
-use Drupal\Core\Url;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Drupal\Core\Database\Database;
-
-class DwsimFlowsheetGlobalFunction{
-
-function dwsim_flowsheet_ajax()
-{
- $query_type = arg(2);
- if ($query_type == 'chapter_title')
- {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- //$chapter_q = db_query("SELECT * FROM {dwsim_flowsheet_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);
- $query = \Drupal::database()->select('dwsim_flowsheet_chapter');
- $query->fields('dwsim_flowsheet_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if ($chapter_data = $chapter_q->fetchObject())
- {
- echo $chapter_data->name;
- return;
- } //$chapter_data = $chapter_q->fetchObject()
- } //$query_type == 'chapter_title'
- else if ($query_type == 'example_exists')
- {
- $chapter_number = arg(3);
- $preference_id = arg(4);
- $example_number = arg(5);
- $chapter_id = 0;
- $query = \Drupal::database()->select('dwsim_flowsheet_chapter');
- $query->fields('dwsim_flowsheet_chapter');
- $query->condition('number', $chapter_number);
- $query->condition('preference_id', $preference_id);
- $query->range(0, 1);
- $chapter_q = $query->execute();
- if (!$chapter_data = $chapter_q->fetchObject())
- {
- echo '';
- return;
- } //!$chapter_data = $chapter_q->fetchObject()
- else
- {
- $chapter_id = $chapter_data->id;
- }
- $query = \Drupal::database()->select('dwsim_flowsheet_example');
- $query->fields('dwsim_flowsheet_example');
- $query->condition('chapter_id', $chapter_id);
- $query->condition('number', $example_number);
- $query->range(0, 1);
- $example_q = $query->execute();
- if ($example_data = $example_q->fetchObject())
- {
- if ($example_data->approval_status == 1)
- echo 'Warning! Solution already approved. You cannot upload the same solution again.';
- else
- echo 'Warning! Solution already uploaded. Delete the solution and reupload it.';
- return;
- } //$example_data = $example_q->fetchObject()
- } //$query_type == 'example_exists'
- echo '';
-}
-/*************************** VALIDATION FUNCTIONS *****************************/
-function dwsim_flowsheet_check_valid_filename($file_name)
-{
- if (!preg_match('/^[0-9a-zA-Z\.\_]+$/', $file_name))
- return FALSE;
- else if (substr_count($file_name, ".") > 1)
- return FALSE;
- else
- return TRUE;
-}
-function dwsim_flowsheet_check_name($name = '')
-{
- if (!preg_match('/^[0-9a-zA-Z\ ]+$/', $name))
- return FALSE;
- else
- return TRUE;
-}
-function dwsim_flowsheet_check_code_number($number = '')
-{
- if (!preg_match('/^[0-9]+$/', $number))
- return FALSE;
- else
- return TRUE;
-}
-function dwsim_flowsheet_path()
-{
- return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/dwsim_flowsheet_uploads/';
-}
-/************************* USER VERIFICATION FUNCTIONS ************************/
-function dwsim_flowsheet_get_proposal()
-{
- $user = \Drupal::currentUser();
- $query = \Drupal::database()->select('dwsim_flowsheet_proposal');
- $query->fields('dwsim_flowsheet_proposal');
- $query->condition('uid', $user->id());
- $query->condition('approval_status', 1);
- $query->orderBy('id', 'DESC');
- $query->range(0, 1);
- $proposal_data = $query->execute()->fetchObject();
- if ($proposal_data)
- {
- return $proposal_data;
- }
-
- $status_query = \Drupal::database()->select('dwsim_flowsheet_proposal');
- $status_query->fields('dwsim_flowsheet_proposal');
- $status_query->condition('uid', $user->id());
- $status_query->orderBy('id', 'DESC');
- $status_query->range(0, 1);
- $latest_proposal = $status_query->execute()->fetchObject();
- if (!$latest_proposal)
- {
- \Drupal::messenger()->addError("You do not have any approved DWSIM Flowsheet proposal. Please propose the flowsheet proposal");
- return FALSE;
- }
-
- switch ($latest_proposal->approval_status)
- {
- case 0:
- \Drupal::messenger()->addStatus(t('Proposal is awaiting approval.'));
- return FALSE;
- case 2:
- \Drupal::messenger()->addError(t('Proposal has been dis-approved.'));
- return FALSE;
- case 3:
- \Drupal::messenger()->addStatus(t('Proposal has been marked as completed.'));
- return FALSE;
- default:
- \Drupal::messenger()->addError(t('You do not have any approved DWSIM Flowsheet proposal. Please propose the flowsheet proposal.'));
- return FALSE;
- }
-}
-/*************************************************************************/
-/***** Function To convert only first charater of string in uppercase ****/
-/*************************************************************************/
-function dwsim_flowsheet_ucname($string)
-{
- $string = ucwords(strtolower($string));
- foreach (array(
- '-',
- '\''
- ) as $delimiter)
- {
- if (strpos($string, $delimiter) !== false)
- {
- $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
- } //strpos($string, $delimiter) !== false
- } //array( '-', '\'' ) as $delimiter
- return $string;
-}
-function _df_sentence_case($string)
-{
- $string = ucwords(strtolower($string));
- foreach (array(
- '-',
- '\''
- ) as $delimiter)
- {
- if (strpos($string, $delimiter) !== false)
- {
- $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
- } //strpos($string, $delimiter) !== false
- } //array( '-', '\'' ) as $delimiter
- return $string;
-}
-function _df_list_of_dwsim_compound()
-{
- $dwsim_compound = array();
- $query = \Drupal::database()->select('dwsim_flowsheet_compounds_from_dwsim');
- $query->fields('dwsim_flowsheet_compounds_from_dwsim');
- $query->orderBy('id', 'ASC');
- $dwsim_compound_list = $query->execute();
- while ($dwsim_compound_list_data = $dwsim_compound_list->fetchObject())
- {
- $dwsim_compound[$dwsim_compound_list_data->compound] = $dwsim_compound_list_data->compound;
- } //$dwsim_compound_list_data = $dwsim_compound_list->fetchObject()
- return $dwsim_compound;
-}
-function _df_list_of_unit_operations()
-{
- $dwsim_unit_operations = array();
- $query = \Drupal::database()->select('dwsim_flowsheet_unit_operations');
- $query->fields('dwsim_flowsheet_unit_operations');
- $query->orderBy('id', 'ASC');
- $dwsim_unit_operations_list = $query->execute();
- while ($dwsim_unit_operations_list_data = $dwsim_unit_operations_list->fetchObject())
- {
- $dwsim_unit_operations[$dwsim_unit_operations_list_data->unit_operations] = $dwsim_unit_operations_list_data->unit_operations;
- } //$dwsim_unit_operations_list_data = $dwsim_unit_operations_list->fetchObject()
- return $dwsim_unit_operations;
-}
-function _df_list_of_thermodynamic_packages()
-{
- $dwsim_thermodynamic_packages = array();
- $query = \Drupal::database()->select('dwsim_flowsheet_thermodynamic_packages');
- $query->fields('dwsim_flowsheet_thermodynamic_packages');
- $query->orderBy('thermodynamic_packages', 'ASC');
- $dwsim_thermodynamic_packages_list = $query->execute();
- while ($dwsim_thermodynamic_packages_list_data = $dwsim_thermodynamic_packages_list->fetchObject())
- {
- $dwsim_thermodynamic_packages[$dwsim_thermodynamic_packages_list_data->thermodynamic_packages] = $dwsim_thermodynamic_packages_list_data->thermodynamic_packages;
- } //$dwsim_thermodynamic_packages_list_data = $dwsim_thermodynamic_packages_list->fetchObject()
- return $dwsim_thermodynamic_packages;
-}
-function _df_list_of_logical_block()
-{
- $dwsim_logical_block = array();
- $query = \Drupal::database()->select('dwsim_flowsheet_logical_block');
- $query->fields('dwsim_flowsheet_logical_block');
- $query->orderBy('id', 'ASC');
- $dwsim_logical_block_list = $query->execute();
- while ($dwsim_logical_block_list_data = $dwsim_logical_block_list->fetchObject())
- {
- $dwsim_logical_block[$dwsim_logical_block_list_data->logical_block] = $dwsim_logical_block_list_data->logical_block;
- } //$dwsim_logical_block_list_data = $dwsim_logical_block_list->fetchObject()
- return $dwsim_logical_block;
-}
-function _df_list_of_states()
-{
- $states = array(
- 0 => '-Select-'
- );
- $query = \Drupal::database()->select('list_states_of_india');
- $query->fields('list_states_of_india');
- //$query->orderBy('', '');
- $states_list = $query->execute();
- while ($states_list_data = $states_list->fetchObject())
- {
- $states[$states_list_data->state] = $states_list_data->state;
- } //$states_list_data = $states_list->fetchObject()
- return $states;
-}
-function _df_list_of_cities()
-{
- $city = array(
- 0 => '-Select-'
- );
- $query = \Drupal::database()->select('list_cities_of_india');
- $query->fields('list_cities_of_india');
- $query->orderBy('city', 'ASC');
- $city_list = $query->execute();
- while ($city_list_data = $city_list->fetchObject())
- {
- $city[$city_list_data->city] = $city_list_data->city;
- } //$city_list_data = $city_list->fetchObject()
- return $city;
-}
-function _df_list_of_pincodes()
-{
- $pincode = array(
- 0 => '-Select-'
- );
- $query = \Drupal::database()->select('list_of_all_india_pincode');
- $query->fields('list_of_all_india_pincode');
- $query->orderBy('pincode', 'ASC');
- $pincode_list = $query->execute();
- while ($pincode_list_data = $pincode_list->fetchObject())
- {
- $pincode[$pincode_list_data->pincode] = $pincode_list_data->pincode;
- } //$pincode_list_data = $pincode_list->fetchObject()
- return $pincode;
-}
-function _df_list_of_departments()
-{
- $department = array();
- $query = \Drupal::database()->select('list_of_departments');
- $query->fields('list_of_departments');
- $query->orderBy('id', 'DESC');
- $department_list = $query->execute();
- while ($department_list_data = $department_list->fetchObject())
- {
- $department[$department_list_data->department] = $department_list_data->department;
- } //$department_list_data = $department_list->fetchObject()
- return $department;
-}
-function _df_list_of_software_version()
-{
- $software_version = array();
- $query = \Drupal::database()->select('dwsim_software_version');
- $query->fields('dwsim_software_version');
- $query->orderBy('id', 'ASC');
- $software_version_list = $query->execute();
- while ($software_version_list_data = $software_version_list->fetchObject())
- {
- $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
- } //$software_version_list_data = $software_version_list->fetchObject()
- return $software_version;
-}
-function _df_dir_name($project, $proposar_name)
-{
-
- $project_title = ucname($project);
- $proposar_name = ucname($proposar_name);
- $dir_name = $project_title . ' By ' . $proposar_name;
- $directory_name = str_replace("__", "_", str_replace(" ", "_", str_replace("/", " ", $dir_name)));
- return $directory_name;
-}
-function dwsim_flowsheet_document_path()
-{
- return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/dwsim_flowsheet_uploads/';
-}
-function DF_RenameDir($proposal_id, $dir_name)
-{
- $proposal_id = $proposal_id;
- $dir_name = $dir_name;
- $query = \Drupal::database()->query("SELECT directory_name,id FROM dwsim_flowsheet_proposal WHERE id = :proposal_id", array(
- ':proposal_id' => $proposal_id
- ));
- $result = $query->fetchObject();
- if ($result != NULL)
- {
- $files = scandir(dwsim_flowsheet_path());
- $files_id_dir = dwsim_flowsheet_path() . $result->id;
- //var_dump($files);die;
- $file_dir = dwsim_flowsheet_path() . $result->directory_name;
- if (is_dir($file_dir))
- {
- $new_directory_name = rename(dwsim_flowsheet_path() . $result->directory_name, dwsim_flowsheet_path() . $dir_name);
- return $new_directory_name;
- } //is_dir($file_dir)
- else if (is_dir($files_id_dir))
- {
- $new_directory_name = rename(dwsim_flowsheet_path() . $result->id, dwsim_flowsheet_path() . $dir_name);
- return $new_directory_name;
- } //is_dir($files_id_dir)
- else
- {
- \Drupal::messenger()->addMessage('Directory not available for rename.');
- return;
- }
- } //$result != NULL
- else
- {
- \Drupal::messenger()->addMessage('Project directory name not present in databse');
- return;
- }
- //var_dump($files);die;
- /* if ($files != NULL)
- {
- $new_directory_name = rename(dwsim_flowsheet_path() . $result->directory_name, dwsim_flowsheet_path() . $dir_name) or drupal_set_message("Unable to rename folder");
- }
- else
- {
- $new_directory_name = 'Can not rename the directory. Directory not present';
- }*/
- return;
-}
-function CreateReadmeFileDWSIMFlowsheetingProject($proposal_id)
-{
- $result = \Drupal::database()->query("
- SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", array(
- ":proposal_id" => $proposal_id
- ));
- $proposal_data = $result->fetchObject();
- $root_path = dwsim_flowsheet_path();
- $readme_file = fopen($root_path . $proposal_data->directory_name . "/README.txt", "w") or die("Unable to open file!");
- $txt = "";
- $txt .= "About the flowsheet";
- $txt .= "\n" . "\n";
- $txt .= "Title Of The Flowsheet Project: " . $proposal_data->project_title . "\n";
- $txt .= "Proposar Name: " . $proposal_data->name_title . " " . $proposal_data->contributor_name . "\n";
- $txt .= "University: " . $proposal_data->university . "\n";
- $txt .= "\n" . "\n";
- $txt .= "DWSIM Flowsheet Project By FOSSEE, IIT Bombay" . "\n";
- fwrite($readme_file, $txt);
- fclose($readme_file);
- return $txt;
-}
-function rrmdir_project($prop_id)
-{
- $proposal_id = $prop_id;
- $result = \Drupal::database()->query("
- SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", array(
- ":proposal_id" => $proposal_id
- ));
- $proposal_data = $result->fetchObject();
- $root_path = dwsim_flowsheet_document_path();
- $dir = $root_path . $proposal_data->directory_name;
- if ($proposal_data->id == $prop_id)
- {
- if (is_dir($dir))
- {
- $objects = scandir($dir);
- foreach ($objects as $object)
- {
- if ($object != "." && $object != "..")
- {
- if (filetype($dir . "/" . $object) == "dir")
- {
- rrmdir($dir . "/" . $object);
- } //filetype($dir . "/" . $object) == "dir"
- else
- {
- unlink($dir . "/" . $object);
- }
- } //$object != "." && $object != ".."
- } //$objects as $object
- reset($objects);
- rmdir($dir);
- $msg = \Drupal::messenger()->addMessage("Directory deleted successfully");
- return $msg;
- } //is_dir($dir)
- $msg = \Drupal::messenger()->addMessage("Directory not present");
- return $msg;
- } //$proposal_data->id == $prop_id
- else
- {
- $msg = \Drupal::messenger()->addMessage("Data not found");
- return $msg;
- }
-}
-function rrmdir($dir)
-{
- if (is_dir($dir))
- {
- $objects = scandir($dir);
- foreach ($objects as $object)
- {
- if ($object != "." && $object != "..")
- {
- if (filetype($dir . "/" . $object) == "dir")
- rrmdir($dir . "/" . $object);
- else
- unlink($dir . "/" . $object);
- } //$object != "." && $object != ".."
- } //$objects as $object
- reset($objects);
- rmdir($dir);
- } //is_dir($dir)
-}
-function _dwsim_flowsheet_list_of_user_defined_compound($proposal_id)
-{
- $data = "";
- //$query = db_select('dwsim_flowsheet_user_defined_compound');
- //$query->fields('dwsim_flowsheet_user_defined_compound');
- //$query->condition('proposal_id', $proposal_id, '=');
- //$query->orderBy('user_defined_compound', 'ASC');
- $user_defined_compound_list = \Drupal::database()->query("SELECT * FROM dwsim_flowsheet_user_defined_compound WHERE proposal_id = :proposal_id", array(":proposal_id" => $proposal_id));
- $headers = array(
- "List of user defined compounds used in process flowsheet",
- "CAS No."
- );
- if($user_defined_compound_list){
- $rows = array();
- while ($row = $user_defined_compound_list->fetchObject())
- {
- $item = array(
- "{$row->user_defined_compound}",
- "{$row->cas_no}"
- );
- array_push($rows, $item);
- } //$row = $user_defined_compound_list->fetchObject()
-
- // @FIXME
-// theme() has been renamed to _theme() and should NEVER be called directly.
-// Calling _theme() directly can alter the expected output and potentially
-// introduce security issues (see https://www.drupal.org/node/2195739). You
-// should use renderable arrays instead.
-//
-//
-// @see https://www.drupal.org/node/2195739
-// $data .= theme('table', array(
-// 'header' => $headers,
-// 'rows' => $rows
-// ));
-
- }else{
- $data .= "Not entered";
- }
- return $data;
-}
+use Drupal\Core\Database\Connection;
+use Drupal\Core\Messenger\MessengerInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\StringTranslation\StringTranslationTrait;
+
+/**
+ * Helper service for the DWSIM Flowsheet module.
+ */
+class DwsimFlowsheetGlobalFunction {
+
+ use StringTranslationTrait;
+
+ /** @var \Drupal\Core\Database\Connection */
+ protected $connection;
+
+ /** @var \Drupal\Core\Messenger\MessengerInterface */
+ protected $messenger;
+
+ /** @var \Drupal\Core\Session\AccountInterface */
+ protected $currentUser;
+
+ /**
+ * Constructor with injected services.
+ */
+ public function __construct(Connection $connection, MessengerInterface $messenger, AccountInterface $currentUser) {
+ $this->connection = $connection;
+ $this->messenger = $messenger;
+ $this->currentUser = $currentUser;
+ }
+
+ /*************************** VALIDATION FUNCTIONS *****************************/
+
+ public function dwsim_flowsheet_check_valid_filename($file_name) {
+ if (!preg_match('/^[0-9a-zA-Z\.\\_]+$/', $file_name))
+ return FALSE;
+ else if (substr_count($file_name, ".") > 1)
+ return FALSE;
+ else
+ return TRUE;
+ }
+
+ public function dwsim_flowsheet_check_name($name = '') {
+ if (!preg_match('/^[0-9a-zA-Z\ ]+$/', $name))
+ return FALSE;
+ else
+ return TRUE;
+ }
+
+ public function dwsim_flowsheet_check_code_number($number = '') {
+ if (!preg_match('/^[0-9]+$/', $number))
+ return FALSE;
+ else
+ return TRUE;
+ }
+
+ public function dwsim_flowsheet_path() {
+ return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/dwsim_flowsheet_uploads/';
+ }
+
+ /************************* USER VERIFICATION FUNCTIONS ************************/
+
+ public function dwsim_flowsheet_get_proposal() {
+ $user = $this->currentUser;
+ $query = $this->connection->select('dwsim_flowsheet_proposal');
+ $query->fields('dwsim_flowsheet_proposal');
+ $query->condition('uid', $user->id());
+ $query->condition('approval_status', 1);
+ $query->orderBy('id', 'DESC');
+ $query->range(0, 1);
+ $proposal_data = $query->execute()->fetchObject();
+ if ($proposal_data) {
+ return $proposal_data;
+ }
+
+ // Fall back to the latest proposal only for user-facing status messaging.
+ $status_query = $this->connection->select('dwsim_flowsheet_proposal');
+ $status_query->fields('dwsim_flowsheet_proposal');
+ $status_query->condition('uid', $user->id());
+ $status_query->orderBy('id', 'DESC');
+ $status_query->range(0, 1);
+ $latest_proposal = $status_query->execute()->fetchObject();
+ if (!$latest_proposal) {
+ $this->messenger->addError("You do not have any approved DWSIM Flowsheet proposal. Please propose the flowsheet proposal");
+ return FALSE;
+ }
+
+ switch ($latest_proposal->approval_status) {
+ case 0:
+ $this->messenger->addStatus($this->t('Proposal is awaiting approval.'));
+ return FALSE;
+ case 2:
+ $this->messenger->addError($this->t('Proposal has been dis-approved.'));
+ return FALSE;
+ case 3:
+ $this->messenger->addStatus($this->t('Proposal has been marked as completed.'));
+ return FALSE;
+ default:
+ $this->messenger->addError($this->t('You do not have any approved DWSIM Flowsheet proposal. Please propose the flowsheet proposal.'));
+ return FALSE;
+ }
+ }
+
+ /*************************************************************************/
+ /***** Convert only first character of string to uppercase ***************/
+ /*************************************************************************/
+
+ public function dwsim_flowsheet_ucname($string) {
+ $string = ucwords(strtolower($string));
+ foreach (['-', "'"] as $delimiter) {
+ if (strpos($string, $delimiter) !== false) {
+ $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
+ }
+ }
+ return $string;
+ }
+
+ public function _df_sentence_case($string) {
+ $string = ucwords(strtolower($string));
+ foreach (['-', "'"] as $delimiter) {
+ if (strpos($string, $delimiter) !== false) {
+ $string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
+ }
+ }
+ return $string;
+ }
+
+ public function _df_list_of_dwsim_compound() {
+ $dwsim_compound = [];
+ $query = $this->connection->select('dwsim_flowsheet_compounds_from_dwsim');
+ $query->fields('dwsim_flowsheet_compounds_from_dwsim');
+ $query->orderBy('id', 'ASC');
+ $dwsim_compound_list = $query->execute();
+ while ($dwsim_compound_list_data = $dwsim_compound_list->fetchObject()) {
+ $dwsim_compound[$dwsim_compound_list_data->compound] = $dwsim_compound_list_data->compound;
+ }
+ return $dwsim_compound;
+ }
+
+ public function _df_list_of_unit_operations() {
+ $dwsim_unit_operations = [];
+ $query = $this->connection->select('dwsim_flowsheet_unit_operations');
+ $query->fields('dwsim_flowsheet_unit_operations');
+ $query->orderBy('id', 'ASC');
+ $dwsim_unit_operations_list = $query->execute();
+ while ($dwsim_unit_operations_list_data = $dwsim_unit_operations_list->fetchObject()) {
+ $dwsim_unit_operations[$dwsim_unit_operations_list_data->unit_operations] = $dwsim_unit_operations_list_data->unit_operations;
+ }
+ return $dwsim_unit_operations;
+ }
+
+ public function _df_list_of_thermodynamic_packages() {
+ $dwsim_thermodynamic_packages = [];
+ $query = $this->connection->select('dwsim_flowsheet_thermodynamic_packages');
+ $query->fields('dwsim_flowsheet_thermodynamic_packages');
+ $query->orderBy('thermodynamic_packages', 'ASC');
+ $dwsim_thermodynamic_packages_list = $query->execute();
+ while ($dwsim_thermodynamic_packages_list_data = $dwsim_thermodynamic_packages_list->fetchObject()) {
+ $dwsim_thermodynamic_packages[$dwsim_thermodynamic_packages_list_data->thermodynamic_packages] = $dwsim_thermodynamic_packages_list_data->thermodynamic_packages;
+ }
+ return $dwsim_thermodynamic_packages;
+ }
+
+ public function _df_list_of_logical_block() {
+ $dwsim_logical_block = [];
+ $query = $this->connection->select('dwsim_flowsheet_logical_block');
+ $query->fields('dwsim_flowsheet_logical_block');
+ $query->orderBy('id', 'ASC');
+ $dwsim_logical_block_list = $query->execute();
+ while ($dwsim_logical_block_list_data = $dwsim_logical_block_list->fetchObject()) {
+ $dwsim_logical_block[$dwsim_logical_block_list_data->logical_block] = $dwsim_logical_block_list_data->logical_block;
+ }
+ return $dwsim_logical_block;
+ }
+
+ public function _df_list_of_states() {
+ $states = [0 => '-Select-'];
+ $query = $this->connection->select('list_states_of_india');
+ $query->fields('list_states_of_india');
+ $states_list = $query->execute();
+ while ($states_list_data = $states_list->fetchObject()) {
+ $states[$states_list_data->state] = $states_list_data->state;
+ }
+ return $states;
+ }
+
+ public function _df_list_of_cities() {
+ $city = [0 => '-Select-'];
+ $query = $this->connection->select('list_cities_of_india');
+ $query->fields('list_cities_of_india');
+ $query->orderBy('city', 'ASC');
+ $city_list = $query->execute();
+ while ($city_list_data = $city_list->fetchObject()) {
+ $city[$city_list_data->city] = $city_list_data->city;
+ }
+ return $city;
+ }
+
+ public function _df_list_of_pincodes() {
+ $pincode = [0 => '-Select-'];
+ $query = $this->connection->select('list_of_all_india_pincode');
+ $query->fields('list_of_all_india_pincode');
+ $query->orderBy('pincode', 'ASC');
+ $pincode_list = $query->execute();
+ while ($pincode_list_data = $pincode_list->fetchObject()) {
+ $pincode[$pincode_list_data->pincode] = $pincode_list_data->pincode;
+ }
+ return $pincode;
+ }
+
+ public function _df_list_of_departments() {
+ $department = [];
+ $query = $this->connection->select('list_of_departments');
+ $query->fields('list_of_departments');
+ $query->orderBy('id', 'DESC');
+ $department_list = $query->execute();
+ while ($department_list_data = $department_list->fetchObject()) {
+ $department[$department_list_data->department] = $department_list_data->department;
+ }
+ return $department;
+ }
+
+ public function _df_list_of_software_version() {
+ $software_version = [];
+ $query = $this->connection->select('dwsim_software_version');
+ $query->fields('dwsim_software_version');
+ $query->orderBy('id', 'ASC');
+ $software_version_list = $query->execute();
+ while ($software_version_list_data = $software_version_list->fetchObject()) {
+ $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version;
+ }
+ return $software_version;
+ }
+
+ /**
+ * Build directory name from project title and proposer name.
+ * Fixed: replaced missing global ucname() with ucwords().
+ */
+ public function _df_dir_name($project, $proposar_name) {
+ $project_title = ucwords($project);
+ $proposar_name = ucwords($proposar_name);
+ $dir_name = $project_title . ' By ' . $proposar_name;
+ $directory_name = str_replace("__", "_", str_replace(" ", "_", str_replace("/", " ", $dir_name)));
+ return $directory_name;
+ }
+
+ public function dwsim_flowsheet_document_path() {
+ return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/dwsim_flowsheet_uploads/';
+ }
+
+ public function DF_RenameDir($proposal_id, $dir_name) {
+ $query = $this->connection->query("SELECT directory_name,id FROM dwsim_flowsheet_proposal WHERE id = :proposal_id", [
+ ':proposal_id' => $proposal_id,
+ ]);
+ $result = $query->fetchObject();
+ if ($result != NULL) {
+ $files_id_dir = $this->dwsim_flowsheet_path() . $result->id;
+ $file_dir = $this->dwsim_flowsheet_path() . $result->directory_name;
+ if (is_dir($file_dir)) {
+ return rename($this->dwsim_flowsheet_path() . $result->directory_name, $this->dwsim_flowsheet_path() . $dir_name);
+ }
+ else if (is_dir($files_id_dir)) {
+ return rename($this->dwsim_flowsheet_path() . $result->id, $this->dwsim_flowsheet_path() . $dir_name);
+ }
+ else {
+ $this->messenger->addMessage('Directory not available for rename.');
+ return;
+ }
+ }
+ else {
+ $this->messenger->addMessage('Project directory name not present in database');
+ return;
+ }
+ }
+
+ public function CreateReadmeFileDWSIMFlowsheetingProject($proposal_id) {
+ $result = $this->connection->query("SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", [
+ ':proposal_id' => $proposal_id,
+ ]);
+ $proposal_data = $result->fetchObject();
+ $root_path = $this->dwsim_flowsheet_path();
+ $readme_file = fopen($root_path . $proposal_data->directory_name . "/README.txt", "w") or die("Unable to open file!");
+ $txt = "";
+ $txt .= "About the flowsheet";
+ $txt .= "\n" . "\n";
+ $txt .= "Title Of The Flowsheet Project: " . $proposal_data->project_title . "\n";
+ $txt .= "Proposar Name: " . $proposal_data->name_title . " " . $proposal_data->contributor_name . "\n";
+ $txt .= "University: " . $proposal_data->university . "\n";
+ $txt .= "\n" . "\n";
+ $txt .= "DWSIM Flowsheet Project By FOSSEE, IIT Bombay" . "\n";
+ fwrite($readme_file, $txt);
+ fclose($readme_file);
+ return $txt;
+ }
+
+ public function rrmdir_project($prop_id) {
+ $proposal_id = $prop_id;
+ $result = $this->connection->query("SELECT * from dwsim_flowsheet_proposal WHERE id = :proposal_id", [
+ ':proposal_id' => $proposal_id,
+ ]);
+ $proposal_data = $result->fetchObject();
+ $root_path = $this->dwsim_flowsheet_document_path();
+ $dir = $root_path . $proposal_data->directory_name;
+ if ($proposal_data->id == $prop_id) {
+ if (is_dir($dir)) {
+ $objects = scandir($dir);
+ foreach ($objects as $object) {
+ if ($object != "." && $object != "..") {
+ if (filetype($dir . "/" . $object) == "dir") {
+ $this->rrmdir($dir . "/" . $object);
+ }
+ else {
+ unlink($dir . "/" . $object);
+ }
+ }
+ }
+ reset($objects);
+ rmdir($dir);
+ $msg = $this->messenger->addMessage("Directory deleted successfully");
+ return $msg;
+ }
+ $msg = $this->messenger->addMessage("Directory not present");
+ return $msg;
+ }
+ else {
+ $msg = $this->messenger->addMessage("Data not found");
+ return $msg;
+ }
+ }
+
+ public function rrmdir($dir) {
+ if (is_dir($dir)) {
+ $objects = scandir($dir);
+ foreach ($objects as $object) {
+ if ($object != "." && $object != "..") {
+ if (filetype($dir . "/" . $object) == "dir")
+ $this->rrmdir($dir . "/" . $object);
+ else
+ unlink($dir . "/" . $object);
+ }
+ }
+ reset($objects);
+ rmdir($dir);
+ }
+ }
+ /**
+ * Returns render array of user-defined compounds for a proposal.
+ * Fixed: replaced deprecated theme('table') with render array.
+ */
+ public function _dwsim_flowsheet_list_of_user_defined_compound($proposal_id) {
+ $data = "";
+ $user_defined_compound_list = $this->connection->query(
+ "SELECT * FROM dwsim_flowsheet_user_defined_compound WHERE proposal_id = :proposal_id",
+ [':proposal_id' => $proposal_id]
+ );
+ $headers = [
+ "List of user defined compounds used in process flowsheet",
+ "CAS No.",
+ ];
+ if ($user_defined_compound_list) {
+ $rows = [];
+ while ($row = $user_defined_compound_list->fetchObject()) {
+ $rows[] = [
+ "{$row->user_defined_compound}",
+ "{$row->cas_no}",
+ ];
+ }
+ $data = [
+ '#type' => 'table',
+ '#header' => $headers,
+ '#rows' => $rows,
+ ];
+ }
+ else {
+ $data .= "Not entered";
+ }
+ return $data;
+ }
}
diff --git a/modules/custom/dwsim_flowsheet/src/Services/MailService.php b/modules/custom/dwsim_flowsheet/src/Services/MailService.php
new file mode 100644
index 0000000..1289b09
--- /dev/null
+++ b/modules/custom/dwsim_flowsheet/src/Services/MailService.php
@@ -0,0 +1,171 @@
+mailManager = $mail_manager;
+ $this->loggerFactory = $logger_factory;
+ $this->configFactory = $config_factory;
+ $this->languageManager = $language_manager;
+ }
+
+ /**
+ * Generically sends an email handling common module configurations.
+ *
+ * @param string $module_name
+ * The name of the module, used for retrieving configs and keys.
+ * @param string $mail_key
+ * The specific mail key for hook_mail.
+ * @param string $to
+ * The recipient email address.
+ * @param array $params
+ * The params array containing body, subject, proposal_id, etc.
+ * @param bool $send
+ * Whether to actually send the email (defaults to TRUE).
+ *
+ * @return bool
+ * TRUE if mail was sent successfully, FALSE otherwise.
+ */
+ public function sendMail($module_name, $mail_key, $to, array $params = [], $send = TRUE) {
+ if (empty($to)) {
+ $this->loggerFactory->get($module_name)->warning('Email not sent: Recipient email address is empty for mail key: @key', ['@key' => $mail_key]);
+ \Drupal::messenger()->addWarning($this->t('Email could not be sent because the recipient email address is empty.'));
+ return FALSE;
+ }
+
+ $config = $this->configFactory->get($module_name . '.settings');
+ $from = $config->get($module_name . '_from_email') ?: $this->configFactory->get('system.site')->get('mail');
+
+ // Setup basic headers
+ if (!isset($params[$mail_key]['headers'])) {
+ $params[$mail_key]['headers'] = [
+ 'From' => $from,
+ 'MIME-Version' => '1.0',
+ 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
+ 'Content-Transfer-Encoding' => '8Bit',
+ 'X-Mailer' => 'Drupal',
+ ];
+ } else {
+ $params[$mail_key]['headers']['From'] = $params[$mail_key]['headers']['From'] ?? $from;
+ }
+
+ // Safely attach Cc and Bcc if they exist in config and aren't manually overridden
+ if (!isset($params[$mail_key]['headers']['Cc'])) {
+ $cc = $config->get($module_name . '_cc_emails');
+ if (!empty($cc)) {
+ $params[$mail_key]['headers']['Cc'] = $cc;
+ }
+ }
+
+ if (!isset($params[$mail_key]['headers']['Bcc'])) {
+ $bcc = $config->get($module_name . '_emails');
+ if (!empty($bcc)) {
+ $params[$mail_key]['headers']['Bcc'] = $bcc;
+ }
+ }
+
+ $langcode = $this->languageManager->getCurrentLanguage()->getId();
+
+ $mail_result = $this->mailManager->mail(
+ $module_name,
+ $mail_key,
+ $to,
+ $langcode,
+ $params,
+ $from,
+ $send
+ );
+
+ if (empty($mail_result['result'])) {
+ $this->loggerFactory->get($module_name)->error('Error sending email for key: @key to @to', ['@key' => $mail_key, '@to' => $to]);
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ /**
+ * Helper method to send approval emails.
+ */
+ public function sendApprovalMail($module_name, $proposal_id, $user_id, $to, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_approved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Helper method to send rejection emails.
+ */
+ public function sendRejectionMail($module_name, $proposal_id, $user_id, $to, $reason, array $extra_params = []) {
+ $mail_key = $module_name . '_proposal_disapproved';
+ $params = $extra_params;
+ $params[$mail_key]['proposal_id'] = $proposal_id;
+ $params[$mail_key]['user_id'] = $user_id;
+ $params[$mail_key]['reason'] = $reason;
+
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+
+ /**
+ * Helper method for generic notifications.
+ */
+ public function sendNotification($module_name, $mail_key, $to, $subject, $body, array $extra_params = []) {
+ $params = $extra_params;
+ $params[$mail_key]['subject'] = $subject;
+ $params[$mail_key]['body'] = $body;
+
+ return $this->sendMail($module_name, $mail_key, $to, $params);
+ }
+}