CommentFormController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. /**
  3. * @file
  4. * Definition of Drupal\comment\CommentFormController.
  5. */
  6. namespace Drupal\comment;
  7. use Drupal\Core\Datetime\DrupalDateTime;
  8. use Drupal\Core\Entity\EntityInterface;
  9. use Drupal\Core\Entity\EntityFormControllerNG;
  10. /**
  11. * Base for controller for comment forms.
  12. */
  13. class CommentFormController extends EntityFormControllerNG {
  14. /**
  15. * Overrides Drupal\Core\Entity\EntityFormController::form().
  16. */
  17. public function form(array $form, array &$form_state, EntityInterface $comment) {
  18. global $user;
  19. $node = $comment->nid->entity;
  20. // Use #comment-form as unique jump target, regardless of node type.
  21. $form['#id'] = drupal_html_id('comment_form');
  22. $form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');
  23. $anonymous_contact = variable_get('comment_anonymous_' . $node->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT);
  24. $is_admin = $comment->id() && user_access('administer comments');
  25. if (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
  26. $form['#attached']['library'][] = array('system', 'jquery.cookie');
  27. $form['#attributes']['class'][] = 'user-info-from-cookie';
  28. }
  29. // If not replying to a comment, use our dedicated page callback for new
  30. // comments on nodes.
  31. if (!$comment->id() && !$comment->pid->target_id) {
  32. $form['#action'] = url('comment/reply/' . $comment->nid->target_id);
  33. }
  34. if (isset($form_state['comment_preview'])) {
  35. $form += $form_state['comment_preview'];
  36. }
  37. $form['author'] = array(
  38. '#weight' => 10,
  39. );
  40. // Display author information in a details element for comment moderators.
  41. if ($is_admin) {
  42. $form['author'] += array(
  43. '#type' => 'details',
  44. '#title' => t('Administration'),
  45. '#collapsed' => TRUE,
  46. );
  47. }
  48. // Prepare default values for form elements.
  49. if ($is_admin) {
  50. $author = $comment->name->value;
  51. $status = (isset($comment->status->value) ? $comment->status->value : COMMENT_NOT_PUBLISHED);
  52. $date = (!empty($comment->date) ? $comment->date : new DrupalDateTime($comment->created->value));
  53. }
  54. else {
  55. if ($user->uid) {
  56. $author = $user->name;
  57. }
  58. else {
  59. $author = ($comment->name->value ? $comment->name->value : '');
  60. }
  61. $status = (user_access('skip comment approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED);
  62. $date = '';
  63. }
  64. // Add the author name field depending on the current user.
  65. $form['author']['name'] = array(
  66. '#type' => 'textfield',
  67. '#title' => t('Your name'),
  68. '#default_value' => $author,
  69. '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
  70. '#maxlength' => 60,
  71. '#size' => 30,
  72. );
  73. if ($is_admin) {
  74. $form['author']['name']['#title'] = t('Authored by');
  75. $form['author']['name']['#description'] = t('Leave blank for %anonymous.', array('%anonymous' => config('user.settings')->get('anonymous')));
  76. $form['author']['name']['#autocomplete_path'] = 'user/autocomplete';
  77. }
  78. elseif ($user->uid) {
  79. $form['author']['name']['#type'] = 'item';
  80. $form['author']['name']['#value'] = $form['author']['name']['#default_value'];
  81. $form['author']['name']['#markup'] = theme('username', array('account' => $user));
  82. }
  83. // Add author e-mail and homepage fields depending on the current user.
  84. $form['author']['mail'] = array(
  85. '#type' => 'email',
  86. '#title' => t('E-mail'),
  87. '#default_value' => $comment->mail->value,
  88. '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
  89. '#maxlength' => 64,
  90. '#size' => 30,
  91. '#description' => t('The content of this field is kept private and will not be shown publicly.'),
  92. '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  93. );
  94. $form['author']['homepage'] = array(
  95. '#type' => 'url',
  96. '#title' => t('Homepage'),
  97. '#default_value' => $comment->homepage->value,
  98. '#maxlength' => 255,
  99. '#size' => 30,
  100. '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  101. );
  102. // Add administrative comment publishing options.
  103. $form['author']['date'] = array(
  104. '#type' => 'datetime',
  105. '#title' => t('Authored on'),
  106. '#default_value' => $date,
  107. '#size' => 20,
  108. '#access' => $is_admin,
  109. );
  110. $form['author']['status'] = array(
  111. '#type' => 'radios',
  112. '#title' => t('Status'),
  113. '#default_value' => $status,
  114. '#options' => array(
  115. COMMENT_PUBLISHED => t('Published'),
  116. COMMENT_NOT_PUBLISHED => t('Not published'),
  117. ),
  118. '#access' => $is_admin,
  119. );
  120. $form['subject'] = array(
  121. '#type' => 'textfield',
  122. '#title' => t('Subject'),
  123. '#maxlength' => 64,
  124. '#default_value' => $comment->subject->value,
  125. '#access' => variable_get('comment_subject_field_' . $node->type, 1) == 1,
  126. );
  127. // Used for conditional validation of author fields.
  128. $form['is_anonymous'] = array(
  129. '#type' => 'value',
  130. '#value' => ($comment->id() ? !$comment->uid->target_id : !$user->uid),
  131. );
  132. // Make the comment inherit the current content language unless specifically
  133. // set.
  134. if ($comment->isNew()) {
  135. $language_content = language(LANGUAGE_TYPE_CONTENT);
  136. $comment->langcode->value = $language_content->langcode;
  137. }
  138. // Add internal comment properties.
  139. foreach (array('cid', 'pid', 'nid', 'uid', 'node_type', 'langcode') as $key) {
  140. $key_name = key($comment->$key->offsetGet(0)->getProperties());
  141. $form[$key] = array('#type' => 'value', '#value' => $comment->$key->{$key_name});
  142. }
  143. return parent::form($form, $form_state, $comment);
  144. }
  145. /**
  146. * Overrides Drupal\Core\Entity\EntityFormController::actions().
  147. */
  148. protected function actions(array $form, array &$form_state) {
  149. $element = parent::actions($form, $form_state);
  150. $comment = $this->getEntity($form_state);
  151. $node = $comment->nid->entity;
  152. $preview_mode = variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL);
  153. // No delete action on the comment form.
  154. unset($element['delete']);
  155. // Mark the submit action as the primary action, when it appears.
  156. $element['submit']['#button_type'] = 'primary';
  157. // Only show the save button if comment previews are optional or if we are
  158. // already previewing the submission.
  159. $element['submit']['#access'] = ($comment->id() && user_access('administer comments')) || $preview_mode != DRUPAL_REQUIRED || isset($form_state['comment_preview']);
  160. $element['preview'] = array(
  161. '#type' => 'submit',
  162. '#value' => t('Preview'),
  163. '#access' => $preview_mode != DRUPAL_DISABLED,
  164. '#validate' => array(
  165. array($this, 'validate'),
  166. ),
  167. '#submit' => array(
  168. array($this, 'submit'),
  169. array($this, 'preview'),
  170. ),
  171. );
  172. return $element;
  173. }
  174. /**
  175. * Overrides Drupal\Core\Entity\EntityFormController::validate().
  176. */
  177. public function validate(array $form, array &$form_state) {
  178. parent::validate($form, $form_state);
  179. if (!empty($form_state['values']['cid'])) {
  180. // Verify the name in case it is being changed from being anonymous.
  181. $account = user_load_by_name($form_state['values']['name']);
  182. $form_state['values']['uid'] = $account ? $account->uid : 0;
  183. $date = $form_state['values']['date'];
  184. if ($date instanceOf DrupalDateTime && $date->hasErrors()) {
  185. form_set_error('date', t('You have to specify a valid date.'));
  186. }
  187. if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) {
  188. form_set_error('name', t('You have to specify a valid author.'));
  189. }
  190. }
  191. elseif ($form_state['values']['is_anonymous']) {
  192. // Validate anonymous comment author fields (if given). If the (original)
  193. // author of this comment was an anonymous user, verify that no registered
  194. // user with this name exists.
  195. if ($form_state['values']['name']) {
  196. $query = db_select('users', 'u');
  197. $query->addField('u', 'uid', 'uid');
  198. $taken = $query
  199. ->condition('name', db_like($form_state['values']['name']), 'LIKE')
  200. ->countQuery()
  201. ->execute()
  202. ->fetchField();
  203. if ($taken) {
  204. form_set_error('name', t('The name you used belongs to a registered user.'));
  205. }
  206. }
  207. }
  208. }
  209. /**
  210. * Overrides EntityFormController::buildEntity().
  211. */
  212. public function buildEntity(array $form, array &$form_state) {
  213. $comment = parent::buildEntity($form, $form_state);
  214. if (!empty($form_state['values']['date']) && $form_state['values']['date'] instanceOf DrupalDateTime) {
  215. $comment->created->value = $form_state['values']['date']->getTimestamp();
  216. }
  217. else {
  218. $comment->created->value = REQUEST_TIME;
  219. }
  220. $comment->changed->value = REQUEST_TIME;
  221. return $comment;
  222. }
  223. /**
  224. * Overrides Drupal\Core\Entity\EntityFormController::submit().
  225. */
  226. public function submit(array $form, array &$form_state) {
  227. $comment = parent::submit($form, $form_state);
  228. // If the comment was posted by a registered user, assign the author's ID.
  229. // @todo Too fragile. Should be prepared and stored in comment_form()
  230. // already.
  231. if (!$comment->is_anonymous && !empty($comment->name->value) && ($account = user_load_by_name($comment->name->value))) {
  232. $comment->uid->target_id = $account->uid;
  233. }
  234. // If the comment was posted by an anonymous user and no author name was
  235. // required, use "Anonymous" by default.
  236. if ($comment->is_anonymous && (!isset($comment->name->value) || $comment->name->value === '')) {
  237. $comment->name->value = config('user.settings')->get('anonymous');
  238. }
  239. // Validate the comment's subject. If not specified, extract from comment
  240. // body.
  241. if (trim($comment->subject->value) == '') {
  242. // The body may be in any format, so:
  243. // 1) Filter it into HTML
  244. // 2) Strip out all HTML tags
  245. // 3) Convert entities back to plain-text.
  246. $comment_text = $comment->comment_body->processed;
  247. $comment->subject = truncate_utf8(trim(decode_entities(strip_tags($comment_text))), 29, TRUE);
  248. // Edge cases where the comment body is populated only by HTML tags will
  249. // require a default subject.
  250. if ($comment->subject->value == '') {
  251. $comment->subject->value = t('(No subject)');
  252. }
  253. }
  254. return $comment;
  255. }
  256. /**
  257. * Form submission handler for the 'preview' action.
  258. *
  259. * @param $form
  260. * An associative array containing the structure of the form.
  261. * @param $form_state
  262. * A reference to a keyed array containing the current state of the form.
  263. */
  264. public function preview(array $form, array &$form_state) {
  265. $comment = $this->getEntity($form_state);
  266. drupal_set_title(t('Preview comment'), PASS_THROUGH);
  267. $form_state['comment_preview'] = comment_preview($comment);
  268. $form_state['rebuild'] = TRUE;
  269. }
  270. /**
  271. * Overrides Drupal\Core\Entity\EntityFormController::save().
  272. */
  273. public function save(array $form, array &$form_state) {
  274. $node = node_load($form_state['values']['nid']);
  275. $comment = $this->getEntity($form_state);
  276. if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
  277. // Save the anonymous user information to a cookie for reuse.
  278. if (user_is_anonymous()) {
  279. user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
  280. }
  281. comment_save($comment);
  282. $form_state['values']['cid'] = $comment->id();
  283. // Add an entry to the watchdog log.
  284. watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject->value), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->id(), array('fragment' => 'comment-' . $comment->id())));
  285. // Explain the approval queue if necessary.
  286. if ($comment->status->value == COMMENT_NOT_PUBLISHED) {
  287. if (!user_access('administer comments')) {
  288. drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
  289. }
  290. }
  291. else {
  292. drupal_set_message(t('Your comment has been posted.'));
  293. }
  294. $query = array();
  295. // Find the current display page for this comment.
  296. $page = comment_get_display_page($comment->id(), $node->type);
  297. if ($page > 0) {
  298. $query['page'] = $page;
  299. }
  300. // Redirect to the newly posted comment.
  301. $redirect = array('node/' . $node->nid, array('query' => $query, 'fragment' => 'comment-' . $comment->id()));
  302. }
  303. else {
  304. watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject->value), WATCHDOG_WARNING);
  305. drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject->value)), 'error');
  306. // Redirect the user to the node they are commenting on.
  307. $redirect = 'node/' . $node->nid;
  308. }
  309. $form_state['redirect'] = $redirect;
  310. // Clear the block and page caches so that anonymous users see the comment
  311. // they have posted.
  312. cache_invalidate_tags(array('content' => TRUE));
  313. }
  314. }