comment.module

  1. drupal
    1. 4.6 modules/comment.module
    2. 4.7 modules/comment.module
    3. 5 modules/comment/comment.module
    4. 6 modules/comment/comment.module
    5. 7 modules/comment/comment.module
    6. 8 core/modules/comment/comment.module

Enables users to comment on published content.

When enabled, the Comment module creates a discussion board for each Drupal node. Users can post comments to discuss a forum topic, story, collaborative book page, etc.

Functions & methods

NameDescription
comment_accessDetermines whether the current user has access to a particular comment.
comment_action_infoImplements hook_action_info().
comment_alphadecimal_to_intDecodes a sorting code back to an integer.
comment_block_configureImplements hook_block_configure().
comment_block_infoImplements hook_block_info().
comment_block_saveImplements hook_block_save().
comment_block_viewImplements hook_block_view().
comment_build_contentBuilds a structured array representing the comment's content.
comment_count_unpublishedReturns a menu title which includes the number of unapproved comments.
comment_deleteDeletes a comment and all its replies.
comment_delete_multipleDeletes comments and all their replies.
comment_edit_pagePage callback: Displays the comment editing form.
comment_entity_infoImplements hook_entity_info().
comment_field_extra_fieldsImplements hook_field_extra_fields().
comment_file_download_accessImplements hook_file_download_access().
comment_formForm constructor for the basic commenting form.
comment_formsImplements hook_forms().
comment_form_build_previewForm submission handler for the 'preview' button in comment_form().
comment_form_node_form_alterImplements hook_form_BASE_FORM_ID_alter().
comment_form_node_type_form_alterImplements hook_form_FORM_ID_alter().
comment_form_submitForm submission handler for comment_form().
comment_form_submit_build_commentUpdates the comment entity by processing the submission's values.
comment_form_validateForm validation handler for comment_form().
comment_get_display_ordinalGets the display ordinal for a comment, starting from 0.
comment_get_display_pageReturns the page number for a comment.
comment_get_recentFinds the most recent comments that are available to the current user.
comment_get_threadRetrieves comments for a thread.
comment_helpImplements hook_help().
comment_increment_alphadecimalIncrements a sorting code to the next value.
comment_int_to_alphadecimalGenerates a sorting code.
comment_linksAdds reply, edit, delete, etc. links, depending on user permissions.
comment_loadLoads the entire comment by comment ID.
comment_load_multipleLoads comments from the database.
comment_menuImplements hook_menu().
comment_menu_alterImplements hook_menu_alter().
comment_new_page_countCalculates the page number for the first new comment.
comment_node_insertImplements hook_node_insert().
comment_node_loadImplements hook_node_load().
comment_node_page_additionsBuilds the comment-related elements for node detail pages.
comment_node_predeleteImplements hook_node_predelete().
comment_node_prepareImplements hook_node_prepare().
comment_node_search_resultImplements hook_node_search_result().
comment_node_type_deleteImplements hook_node_type_delete().
comment_node_type_insertImplements hook_node_type_insert().
comment_node_type_loadLoads the comment bundle name corresponding a given content type.
comment_node_type_updateImplements hook_node_type_update().
comment_node_update_indexImplements hook_node_update_index().
comment_node_viewImplements hook_node_view().
comment_num_newGets the number of new comments for the current user and the specified node.
comment_permalinkRedirects comment links to the correct page depending on comment settings.
comment_permissionImplements hook_permission().
comment_prepare_threadCalculates the indentation level of each comment in a comment thread.
comment_preprocess_blockImplements hook_preprocess_HOOK() for block.tpl.php.
comment_previewGenerates a comment preview.
comment_publish_actionPublishes a comment.
comment_rankingImplements hook_ranking().
comment_rdf_mappingImplements hook_rdf_mapping().
comment_saveAccepts a submission of new or changed comment content.
comment_save_actionSaves a comment.
comment_submitPrepare a comment for submission.
comment_themeImplements hook_theme().
comment_unpublish_actionUnpublishes a comment.
comment_unpublish_by_keyword_actionUnpublishes a comment if it contains certain keywords.
comment_unpublish_by_keyword_action_formForm constructor for the blacklisted keywords form.
comment_unpublish_by_keyword_action_submitForm submission handler for comment_unpublish_by_keyword_action_form().
comment_update_indexImplements hook_update_index().
comment_uriEntity uri callback.
comment_user_cancelImplements hook_user_cancel().
comment_user_predeleteImplements hook_user_predelete().
comment_viewGenerates an array for rendering a comment.
comment_view_multipleConstructs render array from an array of loaded comments.
template_preprocess_commentPreprocesses variables for comment.tpl.php.
template_preprocess_comment_wrapperPreprocesses variables for comment-wrapper.tpl.php.
theme_comment_blockReturns HTML for a list of recent comments.
theme_comment_post_forbiddenReturns HTML for a "you can't post comments" notice.
_comment_body_field_createCreates a comment_body field instance for a given node type.
_comment_get_modesReturns an array of viewing modes for comment listings.
_comment_per_pageReturns an array of "comments per page" values that users can select from.

Constants

NameDescription
COMMENT_ANONYMOUS_MAYNOT_CONTACTAnonymous posters cannot enter their contact information.
COMMENT_ANONYMOUS_MAY_CONTACTAnonymous posters may leave their contact information.
COMMENT_ANONYMOUS_MUST_CONTACTAnonymous posters are required to leave their contact information.
COMMENT_FORM_BELOWComment form should be shown below post or list of comments.
COMMENT_FORM_SEPARATE_PAGEComment form should be displayed on a separate page.
COMMENT_MODE_FLATComments are displayed in a flat list - expanded.
COMMENT_MODE_THREADEDComments are displayed as a threaded list - expanded.
COMMENT_NODE_CLOSEDComments for this node are closed.
COMMENT_NODE_HIDDENComments for this node are hidden.
COMMENT_NODE_OPENComments for this node are open.
COMMENT_NOT_PUBLISHEDComment is awaiting approval.
COMMENT_PUBLISHEDComment is published.

File

core/modules/comment/comment.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Enables users to comment on published content.
  5. *
  6. * When enabled, the Comment module creates a discussion board for each Drupal
  7. * node. Users can post comments to discuss a forum topic, story, collaborative
  8. * book page, etc.
  9. */
  10. use DrupalnodeNode;
  11. /**
  12. * Comment is awaiting approval.
  13. */
  14. const COMMENT_NOT_PUBLISHED = 0;
  15. /**
  16. * Comment is published.
  17. */
  18. const COMMENT_PUBLISHED = 1;
  19. /**
  20. * Comments are displayed in a flat list - expanded.
  21. */
  22. const COMMENT_MODE_FLAT = 0;
  23. /**
  24. * Comments are displayed as a threaded list - expanded.
  25. */
  26. const COMMENT_MODE_THREADED = 1;
  27. /**
  28. * Anonymous posters cannot enter their contact information.
  29. */
  30. const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
  31. /**
  32. * Anonymous posters may leave their contact information.
  33. */
  34. const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
  35. /**
  36. * Anonymous posters are required to leave their contact information.
  37. */
  38. const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
  39. /**
  40. * Comment form should be displayed on a separate page.
  41. */
  42. const COMMENT_FORM_SEPARATE_PAGE = 0;
  43. /**
  44. * Comment form should be shown below post or list of comments.
  45. */
  46. const COMMENT_FORM_BELOW = 1;
  47. /**
  48. * Comments for this node are hidden.
  49. */
  50. const COMMENT_NODE_HIDDEN = 0;
  51. /**
  52. * Comments for this node are closed.
  53. */
  54. const COMMENT_NODE_CLOSED = 1;
  55. /**
  56. * Comments for this node are open.
  57. */
  58. const COMMENT_NODE_OPEN = 2;
  59. use DrupalcommentComment;
  60. /**
  61. * Implements hook_help().
  62. */
  63. function comment_help($path, $arg) {
  64. switch ($path) {
  65. case 'admin/help#comment':
  66. $output = '<h3>' . t('About') . '</h3>';
  67. $output .= '<p>' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the online handbook entry for <a href="@comment">Comment module</a>.', array('@comment' => 'http://drupal.org/documentation/modules/comment')) . '</p>';
  68. $output .= '<h3>' . t('Uses') . '</h3>';
  69. $output .= '<dl>';
  70. $output .= '<dt>' . t('Default and custom settings') . '</dt>';
  71. $output .= '<dd>' . t("Each <a href='@content-type'>content type</a> can have its own default comment settings configured as: <em>Open</em> to allow new comments, <em>Hidden</em> to hide existing comments and prevent new comments, or <em>Closed</em> to view existing comments, but prevent new comments. These defaults will apply to all new content created (changes to the settings on existing content must be done manually). Other comment settings can also be customized per content type, and can be overridden for any given item of content. When a comment has no replies, it remains editable by its author, as long as the author has a user account and is logged in.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
  72. $output .= '<dt>' . t('Comment approval') . '</dt>';
  73. $output .= '<dd>' . t("Comments from users who have the <em>Skip comment approval</em> permission are published immediately. All other comments are placed in the <a href='@comment-approval'>Unapproved comments</a> queue, until a user who has permission to <em>Administer comments</em> publishes or deletes them. Published comments can be bulk managed on the <a href='@admin-comment'>Published comments</a> administration page.", array('@comment-approval' => url('admin/content/comment/approval'), '@admin-comment' => url('admin/content/comment'))) . '</dd>';
  74. $output .= '</dl>';
  75. return $output;
  76. }
  77. }
  78. /**
  79. * Implements hook_entity_info().
  80. */
  81. function comment_entity_info() {
  82. $return = array(
  83. 'comment' => array(
  84. 'label' => t('Comment'),
  85. 'base table' => 'comment',
  86. 'uri callback' => 'comment_uri',
  87. 'fieldable' => TRUE,
  88. 'controller class' => 'Drupal\comment\CommentStorageController',
  89. 'entity class' => 'Drupal\comment\Comment',
  90. 'entity keys' => array(
  91. 'id' => 'cid',
  92. 'bundle' => 'node_type',
  93. 'label' => 'subject',
  94. ),
  95. 'bundles' => array(),
  96. 'view modes' => array(
  97. 'full' => array(
  98. 'label' => t('Full comment'),
  99. 'custom settings' => FALSE,
  100. ),
  101. ),
  102. 'static cache' => FALSE,
  103. ),
  104. );
  105. foreach (node_type_get_names() as $type => $name) {
  106. $return['comment']['bundles']['comment_node_' . $type] = array(
  107. 'label' => t('@node_type comment', array('@node_type' => $name)),
  108. // Provide the node type/bundle name for other modules, so it does not
  109. // have to be extracted manually from the bundle name.
  110. 'node bundle' => $type,
  111. 'admin' => array(
  112. // Place the Field UI paths for comments one level below the
  113. // corresponding paths for nodes, so that they appear in the same set
  114. // of local tasks. Note that the paths use a different placeholder name
  115. // and thus a different menu loader callback, so that Field UI page
  116. // callbacks get a comment bundle name from the node type in the URL.
  117. // See comment_node_type_load() and comment_menu_alter().
  118. 'path' => 'admin/structure/types/manage/%comment_node_type/comment',
  119. 'bundle argument' => 4,
  120. 'real path' => 'admin/structure/types/manage/' . $type . '/comment',
  121. 'access arguments' => array('administer content types'),
  122. ),
  123. );
  124. }
  125. return $return;
  126. }
  127. /**
  128. * Loads the comment bundle name corresponding a given content type.
  129. *
  130. * This function is used as a menu loader callback in comment_menu().
  131. *
  132. * @param $name
  133. * The machine name of the node type whose comment fields are to be edited.
  134. *
  135. * @return
  136. * The comment bundle name corresponding to the node type.
  137. *
  138. * @see comment_menu_alter()
  139. */
  140. function comment_node_type_load($name) {
  141. if ($type = node_type_load($name)) {
  142. return 'comment_node_' . $type->type;
  143. }
  144. }
  145. /**
  146. * Entity uri callback.
  147. */
  148. function comment_uri(Comment $comment) {
  149. return array(
  150. 'path' => 'comment/' . $comment->cid,
  151. 'options' => array('fragment' => 'comment-' . $comment->cid),
  152. );
  153. }
  154. /**
  155. * Implements hook_field_extra_fields().
  156. */
  157. function comment_field_extra_fields() {
  158. $return = array();
  159. foreach (node_type_get_types() as $type) {
  160. if (variable_get('comment_subject_field_' . $type->type, 1) == 1) {
  161. $return['comment']['comment_node_' . $type->type] = array(
  162. 'form' => array(
  163. 'author' => array(
  164. 'label' => t('Author'),
  165. 'description' => t('Author textfield'),
  166. 'weight' => -2,
  167. ),
  168. 'subject' => array(
  169. 'label' => t('Subject'),
  170. 'description' => t('Subject textfield'),
  171. 'weight' => -1,
  172. ),
  173. ),
  174. );
  175. }
  176. }
  177. return $return;
  178. }
  179. /**
  180. * Implements hook_theme().
  181. */
  182. function comment_theme() {
  183. return array(
  184. 'comment_block' => array(
  185. 'variables' => array(),
  186. ),
  187. 'comment_preview' => array(
  188. 'variables' => array('comment' => NULL),
  189. ),
  190. 'comment' => array(
  191. 'template' => 'comment',
  192. 'render element' => 'elements',
  193. ),
  194. 'comment_post_forbidden' => array(
  195. 'variables' => array('node' => NULL),
  196. ),
  197. 'comment_wrapper' => array(
  198. 'template' => 'comment-wrapper',
  199. 'render element' => 'content',
  200. ),
  201. );
  202. }
  203. /**
  204. * Implements hook_menu().
  205. */
  206. function comment_menu() {
  207. $items['admin/content/comment'] = array(
  208. 'title' => 'Comments',
  209. 'description' => 'List and edit site comments and the comment approval queue.',
  210. 'page callback' => 'comment_admin',
  211. 'access arguments' => array('administer comments'),
  212. 'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  213. 'file' => 'comment.admin.inc',
  214. );
  215. // Tabs begin here.
  216. $items['admin/content/comment/new'] = array(
  217. 'title' => 'Published comments',
  218. 'type' => MENU_DEFAULT_LOCAL_TASK,
  219. 'weight' => -10,
  220. );
  221. $items['admin/content/comment/approval'] = array(
  222. 'title' => 'Unapproved comments',
  223. 'title callback' => 'comment_count_unpublished',
  224. 'page arguments' => array('approval'),
  225. 'access arguments' => array('administer comments'),
  226. 'type' => MENU_LOCAL_TASK,
  227. );
  228. $items['comment/%'] = array(
  229. 'title' => 'Comment permalink',
  230. 'page callback' => 'comment_permalink',
  231. 'page arguments' => array(1),
  232. 'access arguments' => array('access comments'),
  233. );
  234. $items['comment/%/view'] = array(
  235. 'title' => 'View comment',
  236. 'type' => MENU_DEFAULT_LOCAL_TASK,
  237. 'weight' => -10,
  238. );
  239. // Every other comment path uses %, but this one loads the comment directly,
  240. // so we don't end up loading it twice (in the page and access callback).
  241. $items['comment/%comment/edit'] = array(
  242. 'title' => 'Edit',
  243. 'page callback' => 'comment_edit_page',
  244. 'page arguments' => array(1),
  245. 'access callback' => 'comment_access',
  246. 'access arguments' => array('edit', 1),
  247. 'type' => MENU_LOCAL_TASK,
  248. 'weight' => 0,
  249. );
  250. $items['comment/%/approve'] = array(
  251. 'title' => 'Approve',
  252. 'page callback' => 'comment_approve',
  253. 'page arguments' => array(1),
  254. 'access arguments' => array('administer comments'),
  255. 'file' => 'comment.pages.inc',
  256. 'weight' => 1,
  257. );
  258. $items['comment/%/delete'] = array(
  259. 'title' => 'Delete',
  260. 'page callback' => 'comment_confirm_delete_page',
  261. 'page arguments' => array(1),
  262. 'access arguments' => array('administer comments'),
  263. 'type' => MENU_LOCAL_TASK,
  264. 'file' => 'comment.admin.inc',
  265. 'weight' => 2,
  266. );
  267. $items['comment/reply/%node'] = array(
  268. 'title' => 'Add new comment',
  269. 'page callback' => 'comment_reply',
  270. 'page arguments' => array(2),
  271. 'access callback' => 'node_access',
  272. 'access arguments' => array('view', 2),
  273. 'file' => 'comment.pages.inc',
  274. );
  275. return $items;
  276. }
  277. /**
  278. * Implements hook_menu_alter().
  279. */
  280. function comment_menu_alter(&$items) {
  281. // Add comments to the description for admin/content.
  282. $items['admin/content']['description'] = 'Administer content and comments.';
  283. // Adjust the Field UI tabs on admin/structure/types/manage/[node-type].
  284. // See comment_entity_info().
  285. $items['admin/structure/types/manage/%comment_node_type/comment/fields']['title'] = 'Comment fields';
  286. $items['admin/structure/types/manage/%comment_node_type/comment/fields']['weight'] = 3;
  287. $items['admin/structure/types/manage/%comment_node_type/comment/display']['title'] = 'Comment display';
  288. $items['admin/structure/types/manage/%comment_node_type/comment/display']['weight'] = 4;
  289. }
  290. /**
  291. * Returns a menu title which includes the number of unapproved comments.
  292. */
  293. function comment_count_unpublished() {
  294. $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE status = :status', array(
  295. ':status' => COMMENT_NOT_PUBLISHED,
  296. ))->fetchField();
  297. return t('Unapproved comments (@count)', array('@count' => $count));
  298. }
  299. /**
  300. * Implements hook_node_type_insert().
  301. *
  302. * Creates a comment body field for a node type created while the Comment module
  303. * is enabled. For node types created before the Comment module is enabled,
  304. * hook_modules_enabled() serves to create the body fields.
  305. *
  306. * @see comment_modules_enabled()
  307. */
  308. function comment_node_type_insert($info) {
  309. _comment_body_field_create($info);
  310. }
  311. /**
  312. * Implements hook_node_type_update().
  313. */
  314. function comment_node_type_update($info) {
  315. if (!empty($info->old_type) && $info->type != $info->old_type) {
  316. field_attach_rename_bundle('comment', 'comment_node_' . $info->old_type, 'comment_node_' . $info->type);
  317. }
  318. }
  319. /**
  320. * Implements hook_node_type_delete().
  321. */
  322. function comment_node_type_delete($info) {
  323. field_attach_delete_bundle('comment', 'comment_node_' . $info->type);
  324. $settings = array(
  325. 'comment',
  326. 'comment_default_mode',
  327. 'comment_default_per_page',
  328. 'comment_anonymous',
  329. 'comment_subject_field',
  330. 'comment_preview',
  331. 'comment_form_location',
  332. );
  333. foreach ($settings as $setting) {
  334. variable_del($setting . '_' . $info->type);
  335. }
  336. }
  337. /**
  338. * Creates a comment_body field instance for a given node type.
  339. *
  340. * @param $info
  341. * An object representing the content type. The only property that is
  342. * currently used is $info->type, which is the machine name of the content
  343. * type for which the body field (instance) is to be created.
  344. */
  345. function _comment_body_field_create($info) {
  346. // Create the field if needed.
  347. if (!field_read_field('comment_body', array('include_inactive' => TRUE))) {
  348. $field = array(
  349. 'field_name' => 'comment_body',
  350. 'type' => 'text_long',
  351. 'entity_types' => array('comment'),
  352. );
  353. field_create_field($field);
  354. }
  355. // Create the instance if needed.
  356. if (!field_read_instance('comment', 'comment_body', 'comment_node_' . $info->type, array('include_inactive' => TRUE))) {
  357. field_attach_create_bundle('comment', 'comment_node_' . $info->type);
  358. // Attaches the body field by default.
  359. $instance = array(
  360. 'field_name' => 'comment_body',
  361. 'label' => 'Comment',
  362. 'entity_type' => 'comment',
  363. 'bundle' => 'comment_node_' . $info->type,
  364. 'settings' => array('text_processing' => 1),
  365. 'required' => TRUE,
  366. 'display' => array(
  367. 'default' => array(
  368. 'label' => 'hidden',
  369. 'type' => 'text_default',
  370. 'weight' => 0,
  371. ),
  372. ),
  373. );
  374. field_create_instance($instance);
  375. }
  376. }
  377. /**
  378. * Implements hook_permission().
  379. */
  380. function comment_permission() {
  381. return array(
  382. 'administer comments' => array(
  383. 'title' => t('Administer comments and comment settings'),
  384. ),
  385. 'access comments' => array(
  386. 'title' => t('View comments'),
  387. ),
  388. 'post comments' => array(
  389. 'title' => t('Post comments'),
  390. ),
  391. 'skip comment approval' => array(
  392. 'title' => t('Skip comment approval'),
  393. ),
  394. 'edit own comments' => array(
  395. 'title' => t('Edit own comments'),
  396. ),
  397. );
  398. }
  399. /**
  400. * Implements hook_block_info().
  401. */
  402. function comment_block_info() {
  403. $blocks['recent']['info'] = t('Recent comments');
  404. $blocks['recent']['properties']['administrative'] = TRUE;
  405. return $blocks;
  406. }
  407. /**
  408. * Implements hook_block_configure().
  409. */
  410. function comment_block_configure($delta = '') {
  411. $form['comment_block_count'] = array(
  412. '#type' => 'select',
  413. '#title' => t('Number of recent comments'),
  414. '#default_value' => variable_get('comment_block_count', 10),
  415. '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30)),
  416. );
  417. return $form;
  418. }
  419. /**
  420. * Implements hook_block_save().
  421. */
  422. function comment_block_save($delta = '', $edit = array()) {
  423. variable_set('comment_block_count', (int) $edit['comment_block_count']);
  424. }
  425. /**
  426. * Implements hook_block_view().
  427. *
  428. * Generates a block with the most recent comments.
  429. */
  430. function comment_block_view($delta = '') {
  431. if (user_access('access comments')) {
  432. $block['subject'] = t('Recent comments');
  433. $block['content'] = theme('comment_block');
  434. return $block;
  435. }
  436. }
  437. /**
  438. * Redirects comment links to the correct page depending on comment settings.
  439. *
  440. * Since comments are paged there is no way to guarantee which page a comment
  441. * appears on. Comment paging and threading settings may be changed at any time.
  442. * With threaded comments, an individual comment may move between pages as
  443. * comments can be added either before or after it in the overall discussion.
  444. * Therefore we use a central routing function for comment links, which
  445. * calculates the page number based on current comment settings and returns
  446. * the full comment view with the pager set dynamically.
  447. *
  448. * @param $cid
  449. * A comment identifier.
  450. *
  451. * @return
  452. * The comment listing set to the page on which the comment appears.
  453. */
  454. function comment_permalink($cid) {
  455. if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {
  456. // Find the current display page for this comment.
  457. $page = comment_get_display_page($comment->cid, $node->type);
  458. // Return the node view, this will show the correct comment in context.
  459. // @todo Refactor to use Symfony's Request object.
  460. _current_path('node/' . $node->nid);
  461. $_GET['page'] = $page;
  462. return menu_execute_active_handler('node/' . $node->nid, FALSE);
  463. }
  464. drupal_not_found();
  465. }
  466. /**
  467. * Finds the most recent comments that are available to the current user.
  468. *
  469. * @param integer $number
  470. * (optional) The maximum number of comments to find. Defaults to 10.
  471. *
  472. * @return
  473. * An array of comment objects or an empty array if there are no recent
  474. * comments visible to the current user.
  475. */
  476. function comment_get_recent($number = 10) {
  477. $query = db_select('comment', 'c');
  478. $query->innerJoin('node', 'n', 'n.nid = c.nid');
  479. $query->addTag('node_access');
  480. $comments = $query
  481. ->fields('c')
  482. ->condition('c.status', COMMENT_PUBLISHED)
  483. ->condition('n.status', NODE_PUBLISHED)
  484. ->orderBy('c.created', 'DESC')
  485. // Additionally order by cid to ensure that comments with the same timestamp
  486. // are returned in the exact order posted.
  487. ->orderBy('c.cid', 'DESC')
  488. ->range(0, $number)
  489. ->execute()
  490. ->fetchAll();
  491. return $comments ? $comments : array();
  492. }
  493. /**
  494. * Calculates the page number for the first new comment.
  495. *
  496. * @param $num_comments
  497. * Number of comments.
  498. * @param $new_replies
  499. * Number of new replies.
  500. * @param Drupal\node\Node $node
  501. * The first new comment node.
  502. *
  503. * @return
  504. * "page=X" if the page number is greater than zero; empty string otherwise.
  505. */
  506. function comment_new_page_count($num_comments, $new_replies, Node $node) {
  507. $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
  508. $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
  509. $pagenum = NULL;
  510. $flat = $mode == COMMENT_MODE_FLAT ? TRUE : FALSE;
  511. if ($num_comments <= $comments_per_page) {
  512. // Only one page of comments.
  513. $pageno = 0;
  514. }
  515. elseif ($flat) {
  516. // Flat comments.
  517. $count = $num_comments - $new_replies;
  518. $pageno = $count / $comments_per_page;
  519. }
  520. else {
  521. // Threaded comments: we build a query with a subquery to find the first
  522. // thread with a new comment.
  523. // 1. Find all the threads with a new comment.
  524. $unread_threads_query = db_select('comment')
  525. ->fields('comment', array('thread'))
  526. ->condition('nid', $node->nid)
  527. ->condition('status', COMMENT_PUBLISHED)
  528. ->orderBy('created', 'DESC')
  529. ->orderBy('cid', 'DESC')
  530. ->range(0, $new_replies);
  531. // 2. Find the first thread.
  532. $first_thread = db_select($unread_threads_query, 'thread')
  533. ->fields('thread', array('thread'))
  534. ->orderBy('SUBSTRING(thread, 1, (LENGTH(thread) - 1))')
  535. ->range(0, 1)
  536. ->execute()
  537. ->fetchField();
  538. // Remove the final '/'.
  539. $first_thread = substr($first_thread, 0, -1);
  540. // Find the number of the first comment of the first unread thread.
  541. $count = db_query('SELECT COUNT(*) FROM {comment} WHERE nid = :nid AND status = :status AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread', array(
  542. ':status' => COMMENT_PUBLISHED,
  543. ':nid' => $node->nid,
  544. ':thread' => $first_thread,
  545. ))->fetchField();
  546. $pageno = $count / $comments_per_page;
  547. }
  548. if ($pageno >= 1) {
  549. $pagenum = array('page' => intval($pageno));
  550. }
  551. return $pagenum;
  552. }
  553. /**
  554. * Returns HTML for a list of recent comments.
  555. *
  556. * @ingroup themeable
  557. */
  558. function theme_comment_block() {
  559. $items = array();
  560. $number = variable_get('comment_block_count', 10);
  561. foreach (comment_get_recent($number) as $comment) {
  562. $items[] = l($comment->subject, 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)) . '&nbsp;<span>' . t('@time ago', array('@time' => format_interval(REQUEST_TIME - $comment->changed))) . '</span>';
  563. }
  564. if ($items) {
  565. return theme('item_list', array('items' => $items));
  566. }
  567. else {
  568. return t('No comments available.');
  569. }
  570. }
  571. /**
  572. * Implements hook_node_view().
  573. */
  574. function comment_node_view(Node $node, $view_mode) {
  575. $links = array();
  576. if ($node->comment != COMMENT_NODE_HIDDEN) {
  577. if ($view_mode == 'rss') {
  578. // Add a comments RSS element which is a URL to the comments of this node.
  579. $node->rss_elements[] = array(
  580. 'key' => 'comments',
  581. 'value' => url('node/' . $node->nid, array('fragment' => 'comments', 'absolute' => TRUE))
  582. );
  583. }
  584. elseif ($view_mode == 'teaser') {
  585. // Teaser view: display the number of comments that have been posted,
  586. // or a link to add new comments if the user has permission, the node
  587. // is open to new comments, and there currently are none.
  588. if (user_access('access comments')) {
  589. if (!empty($node->comment_count)) {
  590. $links['comment-comments'] = array(
  591. 'title' => format_plural($node->comment_count, '1 comment', '@count comments'),
  592. 'href' => "node/$node->nid",
  593. 'attributes' => array('title' => t('Jump to the first comment of this posting.')),
  594. 'fragment' => 'comments',
  595. 'html' => TRUE,
  596. );
  597. // Show a link to the first new comment.
  598. if ($new = comment_num_new($node->nid)) {
  599. $links['comment-new-comments'] = array(
  600. 'title' => format_plural($new, '1 new comment', '@count new comments'),
  601. 'href' => "node/$node->nid",
  602. 'query' => comment_new_page_count($node->comment_count, $new, $node),
  603. 'attributes' => array('title' => t('Jump to the first new comment of this posting.')),
  604. 'fragment' => 'new',
  605. 'html' => TRUE,
  606. );
  607. }
  608. }
  609. }
  610. if ($node->comment == COMMENT_NODE_OPEN) {
  611. $comment_form_location = variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW);
  612. if (user_access('post comments')) {
  613. $links['comment-add'] = array(
  614. 'title' => t('Add new comment'),
  615. 'href' => "node/$node->nid",
  616. 'attributes' => array('title' => t('Add a new comment to this page.')),
  617. 'fragment' => 'comment-form',
  618. );
  619. if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
  620. $links['comment-add']['href'] = "comment/reply/$node->nid";
  621. }
  622. }
  623. else {
  624. $links['comment-forbidden'] = array(
  625. 'title' => theme('comment_post_forbidden', array('node' => $node)),
  626. 'html' => TRUE,
  627. );
  628. }
  629. }
  630. }
  631. elseif ($view_mode != 'search_index' && $view_mode != 'search_result') {
  632. // Node in other view modes: add a "post comment" link if the user is
  633. // allowed to post comments and if this node is allowing new comments.
  634. // But we don't want this link if we're building the node for search
  635. // indexing or constructing a search result excerpt.
  636. if ($node->comment == COMMENT_NODE_OPEN) {
  637. $comment_form_location = variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW);
  638. if (user_access('post comments')) {
  639. // Show the "post comment" link if the form is on another page, or
  640. // if there are existing comments that the link will skip past.
  641. if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE || (!empty($node->comment_count) && user_access('access comments'))) {
  642. $links['comment-add'] = array(
  643. 'title' => t('Add new comment'),
  644. 'attributes' => array('title' => t('Share your thoughts and opinions related to this posting.')),
  645. 'href' => "node/$node->nid",
  646. 'fragment' => 'comment-form',
  647. );
  648. if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
  649. $links['comment-add']['href'] = "comment/reply/$node->nid";
  650. }
  651. }
  652. }
  653. else {
  654. $links['comment-forbidden'] = array(
  655. 'title' => theme('comment_post_forbidden', array('node' => $node)),
  656. 'html' => TRUE,
  657. );
  658. }
  659. }
  660. }
  661. $node->content['links']['comment'] = array(
  662. '#theme' => 'links__node__comment',
  663. '#links' => $links,
  664. '#attributes' => array('class' => array('links', 'inline')),
  665. );
  666. // Only append comments when we are building a node on its own node detail
  667. // page. We compare $node and $page_node to ensure that comments are not
  668. // appended to other nodes shown on the page, for example a node_reference
  669. // displayed in 'full' view mode within another node.
  670. if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  671. $node->content['comments'] = comment_node_page_additions($node);
  672. }
  673. }
  674. }
  675. /**
  676. * Builds the comment-related elements for node detail pages.
  677. *
  678. * @param Drupal\node\Node $node
  679. * The node entity for which to build the comment-related elements.
  680. *
  681. * @return
  682. * A renderable array representing the comment-related page elements for the
  683. * node.
  684. */
  685. function comment_node_page_additions(Node $node) {
  686. $additions = array();
  687. // Only attempt to render comments if the node has visible comments.
  688. // Unpublished comments are not included in $node->comment_count, so show
  689. // comments unconditionally if the user is an administrator.
  690. if (($node->comment_count && user_access('access comments')) || user_access('administer comments')) {
  691. $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
  692. $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
  693. if ($cids = comment_get_thread($node, $mode, $comments_per_page)) {
  694. $comments = comment_load_multiple($cids);
  695. comment_prepare_thread($comments);
  696. $build = comment_view_multiple($comments, $node);
  697. $build['pager']['#theme'] = 'pager';
  698. $additions['comments'] = $build;
  699. }
  700. }
  701. // Append comment form if needed.
  702. if (user_access('post comments') && $node->comment == COMMENT_NODE_OPEN && (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW) == COMMENT_FORM_BELOW)) {
  703. $comment = entity_create('comment', array('nid' => $node->nid));
  704. $additions['comment_form'] = drupal_get_form("comment_node_{$node->type}_form", $comment);
  705. }
  706. if ($additions) {
  707. $additions += array(
  708. '#theme' => 'comment_wrapper__node_' . $node->type,
  709. '#node' => $node,
  710. 'comments' => array(),
  711. 'comment_form' => array(),
  712. );
  713. }
  714. return $additions;
  715. }
  716. /**
  717. * Retrieves comments for a thread.
  718. *
  719. * @param Drupal\node\Node $node
  720. * The node whose comment(s) needs rendering.
  721. * @param $mode
  722. * The comment display mode; COMMENT_MODE_FLAT or COMMENT_MODE_THREADED.
  723. * @param $comments_per_page
  724. * The amount of comments to display per page.
  725. *
  726. * @return
  727. * An array of the IDs of the comment to be displayed.
  728. *
  729. * To display threaded comments in the correct order we keep a 'thread' field
  730. * and order by that value. This field keeps this data in
  731. * a way which is easy to update and convenient to use.
  732. *
  733. * A "thread" value starts at "1". If we add a child (A) to this comment,
  734. * we assign it a "thread" = "1.1". A child of (A) will have "1.1.1". Next
  735. * brother of (A) will get "1.2". Next brother of the parent of (A) will get
  736. * "2" and so on.
  737. *
  738. * First of all note that the thread field stores the depth of the comment:
  739. * depth 0 will be "X", depth 1 "X.X", depth 2 "X.X.X", etc.
  740. *
  741. * Now to get the ordering right, consider this example:
  742. *
  743. * 1
  744. * 1.1
  745. * 1.1.1
  746. * 1.2
  747. * 2
  748. *
  749. * If we "ORDER BY thread ASC" we get the above result, and this is the
  750. * natural order sorted by time. However, if we "ORDER BY thread DESC"
  751. * we get:
  752. *
  753. * 2
  754. * 1.2
  755. * 1.1.1
  756. * 1.1
  757. * 1
  758. *
  759. * Clearly, this is not a natural way to see a thread, and users will get
  760. * confused. The natural order to show a thread by time desc would be:
  761. *
  762. * 2
  763. * 1
  764. * 1.2
  765. * 1.1
  766. * 1.1.1
  767. *
  768. * which is what we already did before the standard pager patch. To achieve
  769. * this we simply add a "/" at the end of each "thread" value. This way, the
  770. * thread fields will look like this:
  771. *
  772. * 1/
  773. * 1.1/
  774. * 1.1.1/
  775. * 1.2/
  776. * 2/
  777. *
  778. * we add "/" since this char is, in ASCII, higher than every number, so if
  779. * now we "ORDER BY thread DESC" we get the correct order. However this would
  780. * spoil the reverse ordering, "ORDER BY thread ASC" -- here, we do not need
  781. * to consider the trailing "/" so we use a substring only.
  782. */
  783. function comment_get_thread(Node $node, $mode, $comments_per_page) {
  784. $query = db_select('comment', 'c')->extend('PagerDefault');
  785. $query->addField('c', 'cid');
  786. $query
  787. ->condition('c.nid', $node->nid)
  788. ->addTag('node_access')
  789. ->addTag('comment_filter')
  790. ->addMetaData('node', $node)
  791. ->limit($comments_per_page);
  792. $count_query = db_select('comment', 'c');
  793. $count_query->addExpression('COUNT(*)');
  794. $count_query
  795. ->condition('c.nid', $node->nid)
  796. ->addTag('node_access')
  797. ->addTag('comment_filter')
  798. ->addMetaData('node', $node);
  799. if (!user_access('administer comments')) {
  800. $query->condition('c.status', COMMENT_PUBLISHED);
  801. $count_query->condition('c.status', COMMENT_PUBLISHED);
  802. }
  803. if ($mode === COMMENT_MODE_FLAT) {
  804. $query->orderBy('c.cid', 'ASC');
  805. }
  806. else {
  807. // See comment above. Analysis reveals that this doesn't cost too
  808. // much. It scales much much better than having the whole comment
  809. // structure.
  810. $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
  811. $query->orderBy('torder', 'ASC');
  812. }
  813. $query->setCountQuery($count_query);
  814. $cids = $query->execute()->fetchCol();
  815. return $cids;
  816. }
  817. /**
  818. * Calculates the indentation level of each comment in a comment thread.
  819. *
  820. * This function loops over an array representing a comment thread. For each
  821. * comment, the function calculates the indentation level and saves it in the
  822. * 'divs' property of the comment object.
  823. *
  824. * @param array $comments
  825. * An array of comment objects, keyed by comment ID.
  826. */
  827. function comment_prepare_thread(&$comments) {
  828. // A flag stating if we are still searching for first new comment on the thread.
  829. $first_new = TRUE;
  830. // A counter that helps track how indented we are.
  831. $divs = 0;
  832. foreach ($comments as $key => $comment) {
  833. if ($first_new && $comment->new != MARK_READ) {
  834. // Assign the anchor only for the first new comment. This avoids duplicate
  835. // id attributes on a page.
  836. $first_new = FALSE;
  837. $comment->first_new = TRUE;
  838. }
  839. // The $divs element instructs #prefix whether to add an indent div or
  840. // close existing divs (a negative value).
  841. $comment->depth = count(explode('.', $comment->thread)) - 1;
  842. if ($comment->depth > $divs) {
  843. $comment->divs = 1;
  844. $divs++;
  845. }
  846. else {
  847. $comment->divs = $comment->depth - $divs;
  848. while ($comment->depth < $divs) {
  849. $divs--;
  850. }
  851. }
  852. $comments[$key] = $comment;
  853. }
  854. // The final comment must close up some hanging divs
  855. $comments[$key]->divs_final = $divs;
  856. }
  857. /**
  858. * Generates an array for rendering a comment.
  859. *
  860. * @param Drupal\comment\Comment $comment
  861. * The comment object.
  862. * @param Drupal\node\Node $node
  863. * The node the comment is attached to.
  864. * @param $view_mode
  865. * View mode, e.g. 'full', 'teaser'...
  866. * @param $langcode
  867. * (optional) A language code to use for rendering. Defaults to the global
  868. * content language of the current request.
  869. *
  870. * @return
  871. * An array as expected by drupal_render().
  872. */
  873. function comment_view(Comment $comment, Node $node, $view_mode = 'full', $langcode = NULL) {
  874. if (!isset($langcode)) {
  875. $langcode = $GLOBALS['language_content']->langcode;
  876. }
  877. // Populate $comment->content with a render() array.
  878. comment_build_content($comment, $node, $view_mode, $langcode);
  879. $build = $comment->content;
  880. // We don't need duplicate rendering info in comment->content.
  881. unset($comment->content);
  882. $build += array(
  883. '#theme' => 'comment__node_' . $node->type,
  884. '#comment' => $comment,
  885. '#node' => $node,
  886. '#view_mode' => $view_mode,
  887. '#language' => $langcode,
  888. );
  889. if (empty($comment->in_preview)) {
  890. $prefix = '';
  891. $is_threaded = isset($comment->divs) && variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED) == COMMENT_MODE_THREADED;
  892. // Add 'new' anchor if needed.
  893. if (!empty($comment->first_new)) {
  894. $prefix .= "<a id=\"new\"></a>\n";
  895. }
  896. // Add indentation div or close open divs as needed.
  897. if ($is_threaded) {
  898. $prefix .= $comment->divs <= 0 ? str_repeat('</div>', abs($comment->divs)) : "\n" . '<div class="indented">';
  899. }
  900. // Add anchor for each comment.
  901. $prefix .= "<a id=\"comment-$comment->cid\"></a>\n";
  902. $build['#prefix'] = $prefix;
  903. // Close all open divs.
  904. if ($is_threaded && !empty($comment->divs_final)) {
  905. $build['#suffix'] = str_repeat('</div>', $comment->divs_final);
  906. }
  907. }
  908. // Allow modules to modify the structured comment.
  909. $type = 'comment';
  910. drupal_alter(array('comment_view', 'entity_view'), $build, $type);
  911. return $build;
  912. }
  913. /**
  914. * Builds a structured array representing the comment's content.
  915. *
  916. * The content built for the comment (field values, comments, file attachments
  917. * or other comment components) will vary depending on the $view_mode parameter.
  918. *
  919. * @param Drupal\comment\Comment $comment
  920. * A comment object.
  921. * @param Drupal\node\Node $node
  922. * The node the comment is attached to.
  923. * @param $view_mode
  924. * View mode, e.g. 'full', 'teaser'...
  925. * @param $langcode
  926. * (optional) A language code to use for rendering. Defaults to the global
  927. * content language of the current request.
  928. */
  929. function comment_build_content(Comment $comment, Node $node, $view_mode = 'full', $langcode = NULL) {
  930. if (!isset($langcode)) {
  931. $langcode = $GLOBALS['language_content']->langcode;
  932. }
  933. // Remove previously built content, if exists.
  934. $comment->content = array();
  935. // Build fields content.
  936. field_attach_prepare_view('comment', array($comment->cid => $comment), $view_mode, $langcode);
  937. entity_prepare_view('comment', array($comment->cid => $comment), $langcode);
  938. $comment->content += field_attach_view('comment', $comment, $view_mode, $langcode);
  939. $comment->content['links'] = array(
  940. '#theme' => 'links__comment',
  941. '#pre_render' => array('drupal_pre_render_links'),
  942. '#attributes' => array('class' => array('links', 'inline')),
  943. );
  944. if (empty($comment->in_preview)) {
  945. $comment->content['links']['comment'] = array(
  946. '#theme' => 'links__comment__comment',
  947. '#links' => comment_links($comment, $node),
  948. '#attributes' => array('class' => array('links', 'inline')),
  949. );
  950. }
  951. // Allow modules to make their own additions to the comment.
  952. module_invoke_all('comment_view', $comment, $view_mode, $langcode);
  953. module_invoke_all('entity_view', $comment, 'comment', $view_mode, $langcode);
  954. }
  955. /**
  956. * Adds reply, edit, delete, etc. links, depending on user permissions.
  957. *
  958. * @param Drupal\comment\Comment $comment
  959. * The comment object.
  960. * @param Drupal\node\Node $node
  961. * The node the comment is attached to.
  962. *
  963. * @return
  964. * A structured array of links.
  965. */
  966. function comment_links(Comment $comment, Node $node) {
  967. $links = array();
  968. if ($node->comment == COMMENT_NODE_OPEN) {
  969. if (user_access('administer comments') && user_access('post comments')) {
  970. $links['comment-delete'] = array(
  971. 'title' => t('delete'),
  972. 'href' => "comment/$comment->cid/delete",
  973. 'html' => TRUE,
  974. );
  975. $links['comment-edit'] = array(
  976. 'title' => t('edit'),
  977. 'href' => "comment/$comment->cid/edit",
  978. 'html' => TRUE,
  979. );
  980. $links['comment-reply'] = array(
  981. 'title' => t('reply'),
  982. 'href' => "comment/reply/$comment->nid/$comment->cid",
  983. 'html' => TRUE,
  984. );
  985. if ($comment->status == COMMENT_NOT_PUBLISHED) {
  986. $links['comment-approve'] = array(
  987. 'title' => t('approve'),
  988. 'href' => "comment/$comment->cid/approve",
  989. 'html' => TRUE,
  990. 'query' => array('token' => drupal_get_token("comment/$comment->cid/approve")),
  991. );
  992. }
  993. }
  994. elseif (user_access('post comments')) {
  995. if (comment_access('edit', $comment)) {
  996. $links['comment-edit'] = array(
  997. 'title' => t('edit'),
  998. 'href' => "comment/$comment->cid/edit",
  999. 'html' => TRUE,
  1000. );
  1001. }
  1002. $links['comment-reply'] = array(
  1003. 'title' => t('reply'),
  1004. 'href' => "comment/reply/$comment->nid/$comment->cid",
  1005. 'html' => TRUE,
  1006. );
  1007. }
  1008. else {
  1009. $links['comment-forbidden']['title'] = theme('comment_post_forbidden', array('node' => $node));
  1010. $links['comment-forbidden']['html'] = TRUE;
  1011. }
  1012. }
  1013. return $links;
  1014. }
  1015. /**
  1016. * Constructs render array from an array of loaded comments.
  1017. *
  1018. * @param $comments
  1019. * An array of comments as returned by comment_load_multiple().
  1020. * @param Drupal\node\Node $node
  1021. * The node the comments are attached to.
  1022. * @param $view_mode
  1023. * View mode, e.g. 'full', 'teaser'...
  1024. * @param $weight
  1025. * An integer representing the weight of the first comment in the list.
  1026. * @param $langcode
  1027. * A string indicating the language field values are to be shown in. If no
  1028. * language is provided the current content language is used.
  1029. *
  1030. * @return
  1031. * An array in the format expected by drupal_render().
  1032. *
  1033. * @see drupal_render()
  1034. */
  1035. function comment_view_multiple($comments, Node $node, $view_mode = 'full', $weight = 0, $langcode = NULL) {
  1036. field_attach_prepare_view('comment', $comments, $view_mode, $langcode);
  1037. entity_prepare_view('comment', $comments, $langcode);
  1038. $build = array(
  1039. '#sorted' => TRUE,
  1040. );
  1041. foreach ($comments as $comment) {
  1042. $build[$comment->cid] = comment_view($comment, $node, $view_mode, $langcode);
  1043. $build[$comment->cid]['#weight'] = $weight;
  1044. $weight++;
  1045. }
  1046. return $build;
  1047. }
  1048. /**
  1049. * Implements hook_form_FORM_ID_alter().
  1050. */
  1051. function comment_form_node_type_form_alter(&$form, $form_state) {
  1052. if (isset($form['type'])) {
  1053. $form['comment'] = array(
  1054. '#type' => 'fieldset',
  1055. '#title' => t('Comment settings'),
  1056. '#collapsible' => TRUE,
  1057. '#collapsed' => TRUE,
  1058. '#group' => 'additional_settings',
  1059. '#attributes' => array(
  1060. 'class' => array('comment-node-type-settings-form'),
  1061. ),
  1062. '#attached' => array(
  1063. 'js' => array(drupal_get_path('module', 'comment') . '/comment-node-form.js'),
  1064. ),
  1065. );
  1066. // Unlike coment_form_node_form_alter(), all of these settings are applied
  1067. // as defaults to all new nodes. Therefore, it would be wrong to use #states
  1068. // to hide the other settings based on the primary comment setting.
  1069. $form['comment']['comment'] = array(
  1070. '#type' => 'select',
  1071. '#title' => t('Default comment setting for new content'),
  1072. '#default_value' => variable_get('comment_' . $form['#node_type']->type, COMMENT_NODE_OPEN),
  1073. '#options' => array(
  1074. COMMENT_NODE_OPEN => t('Open'),
  1075. COMMENT_NODE_CLOSED => t('Closed'),
  1076. COMMENT_NODE_HIDDEN => t('Hidden'),
  1077. ),
  1078. );
  1079. $form['comment']['comment_default_mode'] = array(
  1080. '#type' => 'checkbox',
  1081. '#title' => t('Threading'),
  1082. '#default_value' => variable_get('comment_default_mode_' . $form['#node_type']->type, COMMENT_MODE_THREADED),
  1083. '#description' => t('Show comment replies in a threaded list.'),
  1084. );
  1085. $form['comment']['comment_default_per_page'] = array(
  1086. '#type' => 'select',
  1087. '#title' => t('Comments per page'),
  1088. '#default_value' => variable_get('comment_default_per_page_' . $form['#node_type']->type, 50),
  1089. '#options' => _comment_per_page(),
  1090. );
  1091. $form['comment']['comment_anonymous'] = array(
  1092. '#type' => 'select',
  1093. '#title' => t('Anonymous commenting'),
  1094. '#default_value' => variable_get('comment_anonymous_' . $form['#node_type']->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  1095. '#options' => array(
  1096. COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'),
  1097. COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'),
  1098. COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information'),
  1099. ),
  1100. '#access' => user_access('post comments', drupal_anonymous_user()),
  1101. );
  1102. $form['comment']['comment_subject_field'] = array(
  1103. '#type' => 'checkbox',
  1104. '#title' => t('Allow comment title'),
  1105. '#default_value' => variable_get('comment_subject_field_' . $form['#node_type']->type, 1),
  1106. );
  1107. $form['comment']['comment_form_location'] = array(
  1108. '#type' => 'checkbox',
  1109. '#title' => t('Show reply form on the same page as comments'),
  1110. '#default_value' => variable_get('comment_form_location_' . $form['#node_type']->type, COMMENT_FORM_BELOW),
  1111. );
  1112. $form['comment']['comment_preview'] = array(
  1113. '#type' => 'radios',
  1114. '#title' => t('Preview comment'),
  1115. '#default_value' => variable_get('comment_preview_' . $form['#node_type']->type, DRUPAL_OPTIONAL),
  1116. '#options' => array(
  1117. DRUPAL_DISABLED => t('Disabled'),
  1118. DRUPAL_OPTIONAL => t('Optional'),
  1119. DRUPAL_REQUIRED => t('Required'),
  1120. ),
  1121. );
  1122. }
  1123. }
  1124. /**
  1125. * Implements hook_form_BASE_FORM_ID_alter().
  1126. */
  1127. function comment_form_node_form_alter(&$form, $form_state) {
  1128. $node = $form['#node'];
  1129. $form['comment_settings'] = array(
  1130. '#type' => 'fieldset',
  1131. '#access' => user_access('administer comments'),
  1132. '#title' => t('Comment settings'),
  1133. '#collapsible' => TRUE,
  1134. '#collapsed' => TRUE,
  1135. '#group' => 'additional_settings',
  1136. '#attributes' => array(
  1137. 'class' => array('comment-node-settings-form'),
  1138. ),
  1139. '#attached' => array(
  1140. 'js' => array(drupal_get_path('module', 'comment') . '/comment-node-form.js'),
  1141. ),
  1142. '#weight' => 30,
  1143. );
  1144. $comment_count = isset($node->nid) ? db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField() : 0;
  1145. $comment_settings = ($node->comment == COMMENT_NODE_HIDDEN && empty($comment_count)) ? COMMENT_NODE_CLOSED : $node->comment;
  1146. $form['comment_settings']['comment'] = array(
  1147. '#type' => 'radios',
  1148. '#title' => t('Comments'),
  1149. '#title_display' => 'invisible',
  1150. '#parents' => array('comment'),
  1151. '#default_value' => $comment_settings,
  1152. '#options' => array(
  1153. COMMENT_NODE_OPEN => t('Open'),
  1154. COMMENT_NODE_CLOSED => t('Closed'),
  1155. COMMENT_NODE_HIDDEN => t('Hidden'),
  1156. ),
  1157. COMMENT_NODE_OPEN => array(
  1158. '#description' => t('Users with the "Post comments" permission can post comments.'),
  1159. ),
  1160. COMMENT_NODE_CLOSED => array(
  1161. '#description' => t('Users cannot post comments, but existing comments will be displayed.'),
  1162. ),
  1163. COMMENT_NODE_HIDDEN => array(
  1164. '#description' => t('Comments are hidden from view.'),
  1165. ),
  1166. );
  1167. // If the node doesn't have any comments, the "hidden" option makes no
  1168. // sense, so don't even bother presenting it to the user.
  1169. if (empty($comment_count)) {
  1170. $form['comment_settings']['comment'][COMMENT_NODE_HIDDEN]['#access'] = FALSE;
  1171. // Also adjust the description of the "closed" option.
  1172. $form['comment_settings']['comment'][COMMENT_NODE_CLOSED]['#description'] = t('Users cannot post comments.');
  1173. }
  1174. }
  1175. /**
  1176. * Implements hook_node_load().
  1177. */
  1178. function comment_node_load($nodes, $types) {
  1179. $comments_enabled = array();
  1180. // Check if comments are enabled for each node. If comments are disabled,
  1181. // assign values without hitting the database.
  1182. foreach ($nodes as $node) {
  1183. // Store whether comments are enabled for this node.
  1184. if ($node->comment != COMMENT_NODE_HIDDEN) {
  1185. $comments_enabled[] = $node->nid;
  1186. }
  1187. else {
  1188. $node->cid = 0;
  1189. $node->last_comment_timestamp = $node->created;
  1190. $node->last_comment_name = '';
  1191. $node->last_comment_uid = $node->uid;
  1192. $node->comment_count = 0;
  1193. }
  1194. }
  1195. // For nodes with comments enabled, fetch information from the database.
  1196. if (!empty($comments_enabled)) {
  1197. $result = db_query('SELECT nid, cid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count FROM {node_comment_statistics} WHERE nid IN (:comments_enabled)', array(':comments_enabled' => $comments_enabled));
  1198. foreach ($result as $record) {
  1199. $nodes[$record->nid]->cid = $record->cid;
  1200. $nodes[$record->nid]->last_comment_timestamp = $record->last_comment_timestamp;
  1201. $nodes[$record->nid]->last_comment_name = $record->last_comment_name;
  1202. $nodes[$record->nid]->last_comment_uid = $record->last_comment_uid;
  1203. $nodes[$record->nid]->comment_count = $record->comment_count;
  1204. }
  1205. }
  1206. }
  1207. /**
  1208. * Implements hook_node_prepare().
  1209. */
  1210. function comment_node_prepare(Node $node) {
  1211. if (!isset($node->comment)) {
  1212. $node->comment = variable_get("comment_$node->type", COMMENT_NODE_OPEN);
  1213. }
  1214. }
  1215. /**
  1216. * Implements hook_node_insert().
  1217. */
  1218. function comment_node_insert(Node $node) {
  1219. // Allow bulk updates and inserts to temporarily disable the
  1220. // maintenance of the {node_comment_statistics} table.
  1221. if (variable_get('comment_maintain_node_statistics', TRUE)) {
  1222. db_insert('node_comment_statistics')
  1223. ->fields(array(
  1224. 'nid' => $node->nid,
  1225. 'cid' => 0,
  1226. 'last_comment_timestamp' => $node->changed,
  1227. 'last_comment_name' => NULL,
  1228. 'last_comment_uid' => $node->uid,
  1229. 'comment_count' => 0,
  1230. ))
  1231. ->execute();
  1232. }
  1233. }
  1234. /**
  1235. * Implements hook_node_predelete().
  1236. */
  1237. function comment_node_predelete(Node $node) {
  1238. $cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchCol();
  1239. comment_delete_multiple($cids);
  1240. db_delete('node_comment_statistics')
  1241. ->condition('nid', $node->nid)
  1242. ->execute();
  1243. }
  1244. /**
  1245. * Implements hook_node_update_index().
  1246. */
  1247. function comment_node_update_index(Node $node) {
  1248. $index_comments = &drupal_static(__FUNCTION__);
  1249. if ($index_comments === NULL) {
  1250. // Find and save roles that can 'access comments' or 'search content'.
  1251. $perms = array('access comments' => array(), 'search content' => array());
  1252. $result = db_query("SELECT rid, permission FROM {role_permission} WHERE permission IN ('access comments', 'search content')");
  1253. foreach ($result as $record) {
  1254. $perms[$record->permission][$record->rid] = $record->rid;
  1255. }
  1256. // Prevent indexing of comments if there are any roles that can search but
  1257. // not view comments.
  1258. $index_comments = TRUE;
  1259. foreach ($perms['search content'] as $rid) {
  1260. if (!isset($perms['access comments'][$rid]) && ($rid <= DRUPAL_AUTHENTICATED_RID || !isset($perms['access comments'][DRUPAL_AUTHENTICATED_RID]))) {
  1261. $index_comments = FALSE;
  1262. break;
  1263. }
  1264. }
  1265. }
  1266. if ($index_comments) {
  1267. $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
  1268. $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
  1269. if ($node->comment && $cids = comment_get_thread($node, $mode, $comments_per_page)) {
  1270. $comments = comment_load_multiple($cids);
  1271. comment_prepare_thread($comments);
  1272. $build = comment_view_multiple($comments, $node);
  1273. return drupal_render($build);
  1274. }
  1275. }
  1276. return '';
  1277. }
  1278. /**
  1279. * Implements hook_update_index().
  1280. */
  1281. function comment_update_index() {
  1282. // Store the maximum possible comments per thread (used for ranking by reply count)
  1283. variable_set('node_cron_comments_scale', 1.0 / max(1, db_query('SELECT MAX(comment_count) FROM {node_comment_statistics}')->fetchField()));
  1284. }
  1285. /**
  1286. * Implements hook_node_search_result().
  1287. *
  1288. * Formats a comment count string and returns it, for display with search
  1289. * results.
  1290. */
  1291. function comment_node_search_result(Node $node) {
  1292. // Do not make a string if comments are hidden.
  1293. if (user_access('access comments') && $node->comment != COMMENT_NODE_HIDDEN) {
  1294. $comments = db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array('nid' => $node->nid))->fetchField();
  1295. // Do not make a string if comments are closed and there are currently
  1296. // zero comments.
  1297. if ($node->comment != COMMENT_NODE_CLOSED || $comments > 0) {
  1298. return array('comment' => format_plural($comments, '1 comment', '@count comments'));
  1299. }
  1300. }
  1301. }
  1302. /**
  1303. * Implements hook_user_cancel().
  1304. */
  1305. function comment_user_cancel($edit, $account, $method) {
  1306. switch ($method) {
  1307. case 'user_cancel_block_unpublish':
  1308. $comments = comment_load_multiple(array(), array('uid' => $account->uid));
  1309. foreach ($comments as $comment) {
  1310. $comment->status = 0;
  1311. comment_save($comment);
  1312. }
  1313. break;
  1314. case 'user_cancel_reassign':
  1315. $comments = comment_load_multiple(array(), array('uid' => $account->uid));
  1316. foreach ($comments as $comment) {
  1317. $comment->uid = 0;
  1318. comment_save($comment);
  1319. }
  1320. break;
  1321. }
  1322. }
  1323. /**
  1324. * Implements hook_user_predelete().
  1325. */
  1326. function comment_user_predelete($account) {
  1327. $cids = db_query('SELECT c.cid FROM {comment} c WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
  1328. comment_delete_multiple($cids);
  1329. }
  1330. /**
  1331. * Determines whether the current user has access to a particular comment.
  1332. *
  1333. * Authenticated users can edit their comments as long they have not been
  1334. * replied to. This prevents people from changing or revising their statements
  1335. * based on the replies to their posts.
  1336. *
  1337. * @param $op
  1338. * The operation that is to be performed on the comment. Only 'edit' is
  1339. * recognized now.
  1340. * @param Drupal\comment\Comment $comment
  1341. * The comment object.
  1342. *
  1343. * @return
  1344. * TRUE if the current user has acces to the comment, FALSE otherwise.
  1345. */
  1346. function comment_access($op, Comment $comment) {
  1347. global $user;
  1348. if ($op == 'edit') {
  1349. return ($user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
  1350. }
  1351. }
  1352. /**
  1353. * Accepts a submission of new or changed comment content.
  1354. *
  1355. * @param Drupal\comment\Comment $comment
  1356. * A comment object.
  1357. */
  1358. function comment_save(Comment $comment) {
  1359. $comment->save();
  1360. }
  1361. /**
  1362. * Deletes a comment and all its replies.
  1363. *
  1364. * @param $cid
  1365. * The ID of the comment to delete.
  1366. */
  1367. function comment_delete($cid) {
  1368. comment_delete_multiple(array($cid));
  1369. }
  1370. /**
  1371. * Deletes comments and all their replies.
  1372. *
  1373. * @param $cids
  1374. * The IDs of the comments to delete.
  1375. *
  1376. * @see hook_comment_predelete()
  1377. * @see hook_comment_delete()
  1378. */
  1379. function comment_delete_multiple($cids) {
  1380. entity_delete_multiple('comment', $cids);
  1381. }
  1382. /**
  1383. * Loads comments from the database.
  1384. *
  1385. * @param array|bool $cids
  1386. * An array of comment IDs, or FALSE to load all comments.
  1387. * @param array $conditions
  1388. * (deprecated) An associative array of conditions on the {comments}
  1389. * table, where the keys are the database fields and the values are the
  1390. * values those fields must have. Instead, it is preferable to use
  1391. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  1392. * this function.
  1393. * @param bool $reset
  1394. * Whether to reset the internal static entity cache. Note that the static
  1395. * cache is disabled in comment_entity_info() by default.
  1396. *
  1397. * @return array
  1398. * An array of comment objects, indexed by comment ID.
  1399. *
  1400. * @todo Remove $conditions in Drupal 8.
  1401. *
  1402. * @see entity_load()
  1403. * @see EntityFieldQuery
  1404. */
  1405. function comment_load_multiple($cids = array(), array $conditions = array(), $reset = FALSE) {
  1406. return entity_load_multiple('comment', $cids, $conditions, $reset);
  1407. }
  1408. /**
  1409. * Loads the entire comment by comment ID.
  1410. *
  1411. * @param int $cid
  1412. * The ID of the comment to be loaded.
  1413. * @param bool $reset
  1414. * Whether to reset the internal static entity cache. Note that the static
  1415. * cache is disabled in comment_entity_info() by default.
  1416. *
  1417. * @return
  1418. * The comment object.
  1419. */
  1420. function comment_load($cid, $reset = FALSE) {
  1421. return entity_load('comment', $cid);
  1422. }
  1423. /**
  1424. * Gets the number of new comments for the current user and the specified node.
  1425. *
  1426. * @param $nid
  1427. * Node ID to count comments for.
  1428. * @param $timestamp
  1429. * Time to count from (defaults to time of last user access
  1430. * to node).
  1431. *
  1432. * @return
  1433. * The number of new comments or FALSE if the user is not logged in.
  1434. */
  1435. function comment_num_new($nid, $timestamp = 0) {
  1436. global $user;
  1437. if ($user->uid) {
  1438. // Retrieve the timestamp at which the current user last viewed this node.
  1439. if (!$timestamp) {
  1440. $timestamp = node_last_viewed($nid);
  1441. }
  1442. $timestamp = ($timestamp > NODE_NEW_LIMIT ? $timestamp : NODE_NEW_LIMIT);
  1443. // Use the timestamp to retrieve the number of new comments.
  1444. return db_query('SELECT COUNT(cid) FROM {comment} WHERE nid = :nid AND created > :timestamp AND status = :status', array(
  1445. ':nid' => $nid,
  1446. ':timestamp' => $timestamp,
  1447. ':status' => COMMENT_PUBLISHED,
  1448. ))->fetchField();
  1449. }
  1450. else {
  1451. return FALSE;
  1452. }
  1453. }
  1454. /**
  1455. * Gets the display ordinal for a comment, starting from 0.
  1456. *
  1457. * Count the number of comments which appear before the comment we want to
  1458. * display, taking into account display settings and threading.
  1459. *
  1460. * @param $cid
  1461. * The comment ID.
  1462. * @param $node_type
  1463. * The node type of the comment's parent.
  1464. *
  1465. * @return
  1466. * The display ordinal for the comment.
  1467. *
  1468. * @see comment_get_display_page()
  1469. */
  1470. function comment_get_display_ordinal($cid, $node_type) {
  1471. // Count how many comments (c1) are before $cid (c2) in display order. This is
  1472. // the 0-based display ordinal.
  1473. $query = db_select('comment', 'c1');
  1474. $query->innerJoin('comment', 'c2', 'c2.nid = c1.nid');
  1475. $query->addExpression('COUNT(*)', 'count');
  1476. $query->condition('c2.cid', $cid);
  1477. if (!user_access('administer comments')) {
  1478. $query->condition('c1.status', COMMENT_PUBLISHED);
  1479. }
  1480. $mode = variable_get('comment_default_mode_' . $node_type, COMMENT_MODE_THREADED);
  1481. if ($mode == COMMENT_MODE_FLAT) {
  1482. // For flat comments, cid is used for ordering comments due to
  1483. // unpredicatable behavior with timestamp, so we make the same assumption
  1484. // here.
  1485. $query->condition('c1.cid', $cid, '<');
  1486. }
  1487. else {
  1488. // For threaded comments, the c.thread column is used for ordering. We can
  1489. // use the sorting code for comparison, but must remove the trailing slash.
  1490. // See comment_view_multiple().
  1491. $query->where('SUBSTRING(c1.thread, 1, (LENGTH(c1.thread) -1)) < SUBSTRING(c2.thread, 1, (LENGTH(c2.thread) -1))');
  1492. }
  1493. return $query->execute()->fetchField();
  1494. }
  1495. /**
  1496. * Returns the page number for a comment.
  1497. *
  1498. * Finds the correct page number for a comment taking into account display
  1499. * and paging settings.
  1500. *
  1501. * @param $cid
  1502. * The comment ID.
  1503. * @param $node_type
  1504. * The node type the comment is attached to.
  1505. *
  1506. * @return
  1507. * The page number.
  1508. */
  1509. function comment_get_display_page($cid, $node_type) {
  1510. $ordinal = comment_get_display_ordinal($cid, $node_type);
  1511. $comments_per_page = variable_get('comment_default_per_page_' . $node_type, 50);
  1512. return floor($ordinal / $comments_per_page);
  1513. }
  1514. /**
  1515. * Page callback: Displays the comment editing form.
  1516. *
  1517. * @param Drupal\comment\Comment $comment
  1518. * The comment object representing the comment to be edited.
  1519. *
  1520. * @see comment_menu()
  1521. */
  1522. function comment_edit_page(Comment $comment) {
  1523. drupal_set_title(t('Edit comment %comment', array('%comment' => $comment->subject)), PASS_THROUGH);
  1524. $node = node_load($comment->nid);
  1525. return drupal_get_form("comment_node_{$node->type}_form", $comment);
  1526. }
  1527. /**
  1528. * Implements hook_forms().
  1529. */
  1530. function comment_forms() {
  1531. $forms = array();
  1532. foreach (node_type_get_types() as $type) {
  1533. $forms["comment_node_{$type->type}_form"]['callback'] = 'comment_form';
  1534. }
  1535. return $forms;
  1536. }
  1537. /**
  1538. * Form constructor for the basic commenting form.
  1539. *
  1540. * @see comment_form_validate()
  1541. * @see comment_form_submit()
  1542. * @see comment_form_build_preview()
  1543. * @ingroup forms
  1544. */
  1545. function comment_form($form, &$form_state, Comment $comment) {
  1546. global $user, $language_content;
  1547. // During initial form build, add the comment entity to the form state for
  1548. // use during form building and processing. During a rebuild, use what is in
  1549. // the form state.
  1550. if (!isset($form_state['comment'])) {
  1551. $form_state['comment'] = $comment;
  1552. }
  1553. else {
  1554. $comment = $form_state['comment'];
  1555. }
  1556. $node = node_load($comment->nid);
  1557. $form['#node'] = $node;
  1558. // Use #comment-form as unique jump target, regardless of node type.
  1559. $form['#id'] = drupal_html_id('comment_form');
  1560. $form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');
  1561. $anonymous_contact = variable_get('comment_anonymous_' . $node->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT);
  1562. $is_admin = (!empty($comment->cid) && user_access('administer comments'));
  1563. if (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
  1564. $form['#attached']['library'][] = array('system', 'jquery.cookie');
  1565. $form['#attributes']['class'][] = 'user-info-from-cookie';
  1566. }
  1567. // If not replying to a comment, use our dedicated page callback for new
  1568. // comments on nodes.
  1569. if (empty($comment->cid) && empty($comment->pid)) {
  1570. $form['#action'] = url('comment/reply/' . $comment->nid);
  1571. }
  1572. if (isset($form_state['comment_preview'])) {
  1573. $form += $form_state['comment_preview'];
  1574. }
  1575. $form['author'] = array(
  1576. '#weight' => 10,
  1577. );
  1578. // Display author information in a fieldset for comment moderators.
  1579. if ($is_admin) {
  1580. $form['author'] += array(
  1581. '#type' => 'fieldset',
  1582. '#title' => t('Administration'),
  1583. '#collapsible' => TRUE,
  1584. '#collapsed' => TRUE,
  1585. );
  1586. }
  1587. // Prepare default values for form elements.
  1588. if ($is_admin) {
  1589. $author = (!$comment->uid && $comment->name ? $comment->name : $comment->registered_name);
  1590. $status = (isset($comment->status) ? $comment->status : COMMENT_NOT_PUBLISHED);
  1591. $date = (!empty($comment->date) ? $comment->date : format_date($comment->created, 'custom', 'Y-m-d H:i O'));
  1592. }
  1593. else {
  1594. if ($user->uid) {
  1595. $author = $user->name;
  1596. }
  1597. else {
  1598. $author = ($comment->name ? $comment->name : '');
  1599. }
  1600. $status = (user_access('skip comment approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED);
  1601. $date = '';
  1602. }
  1603. // Add the author name field depending on the current user.
  1604. if ($is_admin) {
  1605. $form['author']['name'] = array(
  1606. '#type' => 'textfield',
  1607. '#title' => t('Authored by'),
  1608. '#default_value' => $author,
  1609. '#maxlength' => 60,
  1610. '#size' => 30,
  1611. '#description' => t('Leave blank for %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous')))),
  1612. '#autocomplete_path' => 'user/autocomplete',
  1613. );
  1614. }
  1615. elseif ($user->uid) {
  1616. $form['author']['_author'] = array(
  1617. '#type' => 'item',
  1618. '#title' => t('Your name'),
  1619. '#markup' => theme('username', array('account' => $user)),
  1620. );
  1621. $form['author']['name'] = array(
  1622. '#type' => 'value',
  1623. '#value' => $author,
  1624. );
  1625. }
  1626. else {
  1627. $form['author']['name'] = array(
  1628. '#type' => 'textfield',
  1629. '#title' => t('Your name'),
  1630. '#default_value' => $author,
  1631. '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
  1632. '#maxlength' => 60,
  1633. '#size' => 30,
  1634. );
  1635. }
  1636. // Add author e-mail and homepage fields depending on the current user.
  1637. $form['author']['mail'] = array(
  1638. '#type' => 'email',
  1639. '#title' => t('E-mail'),
  1640. '#default_value' => $comment->mail,
  1641. '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
  1642. '#maxlength' => 64,
  1643. '#size' => 30,
  1644. '#description' => t('The content of this field is kept private and will not be shown publicly.'),
  1645. '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  1646. );
  1647. $form['author']['homepage'] = array(
  1648. '#type' => 'url',
  1649. '#title' => t('Homepage'),
  1650. '#default_value' => $comment->homepage,
  1651. '#maxlength' => 255,
  1652. '#size' => 30,
  1653. '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  1654. );
  1655. // Add administrative comment publishing options.
  1656. $form['author']['date'] = array(
  1657. '#type' => 'textfield',
  1658. '#title' => t('Authored on'),
  1659. '#default_value' => $date,
  1660. '#maxlength' => 25,
  1661. '#size' => 20,
  1662. '#access' => $is_admin,
  1663. );
  1664. $form['author']['status'] = array(
  1665. '#type' => 'radios',
  1666. '#title' => t('Status'),
  1667. '#default_value' => $status,
  1668. '#options' => array(
  1669. COMMENT_PUBLISHED => t('Published'),
  1670. COMMENT_NOT_PUBLISHED => t('Not published'),
  1671. ),
  1672. '#access' => $is_admin,
  1673. );
  1674. $form['subject'] = array(
  1675. '#type' => 'textfield',
  1676. '#title' => t('Subject'),
  1677. '#maxlength' => 64,
  1678. '#default_value' => $comment->subject,
  1679. '#access' => variable_get('comment_subject_field_' . $node->type, 1) == 1,
  1680. );
  1681. // Used for conditional validation of author fields.
  1682. $form['is_anonymous'] = array(
  1683. '#type' => 'value',
  1684. '#value' => ($comment->cid ? !$comment->uid : !$user->uid),
  1685. );
  1686. // Add internal comment properties.
  1687. foreach (array('cid', 'pid', 'nid', 'uid') as $key) {
  1688. $form[$key] = array('#type' => 'value', '#value' => $comment->$key);
  1689. }
  1690. $form['node_type'] = array('#type' => 'value', '#value' => 'comment_node_' . $node->type);
  1691. // If a content type has multilingual support we set the comment to inherit the
  1692. // content language. Otherwise mark the comment as language neutral.
  1693. $comment_langcode = $comment->langcode;
  1694. if (($comment_langcode == LANGUAGE_NOT_SPECIFIED) && variable_get('node_type_language_' . $node->type, 0)) {
  1695. $comment_langcode = $language_content->langcode;
  1696. }
  1697. $form['langcode'] = array(
  1698. '#type' => 'value',
  1699. '#value' => $comment_langcode,
  1700. );
  1701. // Only show the save button if comment previews are optional or if we are
  1702. // already previewing the submission.
  1703. $form['actions'] = array('#type' => 'actions');
  1704. $form['actions']['submit'] = array(
  1705. '#type' => 'submit',
  1706. '#value' => t('Save'),
  1707. '#access' => ($comment->cid && user_access('administer comments')) || variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || isset($form_state['comment_preview']),
  1708. );
  1709. $form['actions']['preview'] = array(
  1710. '#type' => 'submit',
  1711. '#value' => t('Preview'),
  1712. '#access' => (variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED),
  1713. '#submit' => array('comment_form_build_preview'),
  1714. );
  1715. // Attach fields.
  1716. $comment->node_type = 'comment_node_' . $node->type;
  1717. field_attach_form('comment', $comment, $form, $form_state);
  1718. return $form;
  1719. }
  1720. /**
  1721. * Form submission handler for the 'preview' button in comment_form().
  1722. */
  1723. function comment_form_build_preview($form, &$form_state) {
  1724. $comment = comment_form_submit_build_comment($form, $form_state);
  1725. $form_state['comment_preview'] = comment_preview($comment);
  1726. $form_state['rebuild'] = TRUE;
  1727. }
  1728. /**
  1729. * Generates a comment preview.
  1730. *
  1731. * @param Drupal\comment\Comment $comment
  1732. *
  1733. * @see comment_form_build_preview()
  1734. */
  1735. function comment_preview(Comment $comment) {
  1736. global $user;
  1737. drupal_set_title(t('Preview comment'), PASS_THROUGH);
  1738. $node = node_load($comment->nid);
  1739. if (!form_get_errors()) {
  1740. $comment->format = $comment->comment_body[LANGUAGE_NOT_SPECIFIED][0]['format'];
  1741. // Attach the user and time information.
  1742. if (!empty($comment->name)) {
  1743. $account = user_load_by_name($comment->name);
  1744. }
  1745. elseif ($user->uid && empty($comment->is_anonymous)) {
  1746. $account = $user;
  1747. }
  1748. if (!empty($account->uid)) {
  1749. $comment->uid = $account->uid;
  1750. $comment->name = check_plain($account->name);
  1751. $comment->signature = $account->signature;
  1752. $comment->signature_format = $account->signature_format;
  1753. $comment->picture = $account->picture;
  1754. }
  1755. elseif (empty($comment->name)) {
  1756. $comment->name = variable_get('anonymous', t('Anonymous'));
  1757. }
  1758. $comment->created = !empty($comment->created) ? $comment->created : REQUEST_TIME;
  1759. $comment->changed = REQUEST_TIME;
  1760. $comment->in_preview = TRUE;
  1761. $comment_build = comment_view($comment, $node);
  1762. $comment_build['#weight'] = -100;
  1763. $form['comment_preview'] = $comment_build;
  1764. }
  1765. if ($comment->pid) {
  1766. $build = array();
  1767. if ($comments = comment_load_multiple(array($comment->pid), array('status' => COMMENT_PUBLISHED))) {
  1768. $parent_comment = $comments[$comment->pid];
  1769. $build = comment_view($parent_comment, $node);
  1770. }
  1771. }
  1772. else {
  1773. $build = node_view($node);
  1774. }
  1775. $form['comment_output_below'] = $build;
  1776. $form['comment_output_below']['#weight'] = 100;
  1777. return $form;
  1778. }
  1779. /**
  1780. * Form validation handler for comment_form().
  1781. *
  1782. * @see comment_form_submit()
  1783. */
  1784. function comment_form_validate($form, &$form_state) {
  1785. global $user;
  1786. entity_form_field_validate('comment', $form, $form_state);
  1787. if (!empty($form_state['values']['cid'])) {
  1788. // Verify the name in case it is being changed from being anonymous.
  1789. $account = user_load_by_name($form_state['values']['name']);
  1790. $form_state['values']['uid'] = $account ? $account->uid : 0;
  1791. if ($form_state['values']['date'] && strtotime($form_state['values']['date']) === FALSE) {
  1792. form_set_error('date', t('You have to specify a valid date.'));
  1793. }
  1794. if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) {
  1795. form_set_error('name', t('You have to specify a valid author.'));
  1796. }
  1797. }
  1798. elseif ($form_state['values']['is_anonymous']) {
  1799. // Validate anonymous comment author fields (if given). If the (original)
  1800. // author of this comment was an anonymous user, verify that no registered
  1801. // user with this name exists.
  1802. if ($form_state['values']['name']) {
  1803. $query = db_select('users', 'u');
  1804. $query->addField('u', 'uid', 'uid');
  1805. $taken = $query
  1806. ->condition('name', db_like($form_state['values']['name']), 'LIKE')
  1807. ->countQuery()
  1808. ->execute()
  1809. ->fetchField();
  1810. if ($taken) {
  1811. form_set_error('name', t('The name you used belongs to a registered user.'));
  1812. }
  1813. }
  1814. }
  1815. }
  1816. /**
  1817. * Prepare a comment for submission.
  1818. *
  1819. * @param Drupal\comment\Comment $comment
  1820. *
  1821. */
  1822. function comment_submit(Comment $comment) {
  1823. if (empty($comment->date)) {
  1824. $comment->date = 'now';
  1825. }
  1826. $comment->created = strtotime($comment->date);
  1827. $comment->changed = REQUEST_TIME;
  1828. // If the comment was posted by a registered user, assign the author's ID.
  1829. // @todo Too fragile. Should be prepared and stored in comment_form() already.
  1830. if (!$comment->is_anonymous && !empty($comment->name) && ($account = user_load_by_name($comment->name))) {
  1831. $comment->uid = $account->uid;
  1832. }
  1833. // If the comment was posted by an anonymous user and no author name was
  1834. // required, use "Anonymous" by default.
  1835. if ($comment->is_anonymous && (!isset($comment->name) || $comment->name === '')) {
  1836. $comment->name = variable_get('anonymous', t('Anonymous'));
  1837. }
  1838. // Validate the comment's subject. If not specified, extract from comment body.
  1839. if (trim($comment->subject) == '') {
  1840. // The body may be in any format, so:
  1841. // 1) Filter it into HTML
  1842. // 2) Strip out all HTML tags
  1843. // 3) Convert entities back to plain-text.
  1844. $comment_body = $comment->comment_body[LANGUAGE_NOT_SPECIFIED][0];
  1845. if (isset($comment_body['format'])) {
  1846. $comment_text = check_markup($comment_body['value'], $comment_body['format']);
  1847. }
  1848. else {
  1849. $comment_text = check_plain($comment_body['value']);
  1850. }
  1851. $comment->subject = truncate_utf8(trim(decode_entities(strip_tags($comment_text))), 29, TRUE);
  1852. // Edge cases where the comment body is populated only by HTML tags will
  1853. // require a default subject.
  1854. if ($comment->subject == '') {
  1855. $comment->subject = t('(No subject)');
  1856. }
  1857. }
  1858. return $comment;
  1859. }
  1860. /**
  1861. * Updates the comment entity by processing the submission's values.
  1862. *
  1863. * This is the default builder function for the comment form. It is called
  1864. * during the "Save" and "Preview" submit handlers to retrieve the entity to
  1865. * save or preview. This function can also be called by a "Next" button of a
  1866. * wizard to update the form state's entity with the current step's values
  1867. * before proceeding to the next step.
  1868. *
  1869. * @see comment_form()
  1870. * @see comment_form_preview()
  1871. * @see comment_form_submit()
  1872. */
  1873. function comment_form_submit_build_comment($form, &$form_state) {
  1874. $comment = $form_state['comment'];
  1875. entity_form_submit_build_entity('comment', $comment, $form, $form_state);
  1876. comment_submit($comment);
  1877. return $comment;
  1878. }
  1879. /**
  1880. * Form submission handler for comment_form().
  1881. *
  1882. * @see comment_form_validate()
  1883. * @see comment_form_submit_build_comment()
  1884. */
  1885. function comment_form_submit($form, &$form_state) {
  1886. $node = node_load($form_state['values']['nid']);
  1887. $comment = comment_form_submit_build_comment($form, $form_state);
  1888. if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
  1889. // Save the anonymous user information to a cookie for reuse.
  1890. if (user_is_anonymous()) {
  1891. user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
  1892. }
  1893. comment_save($comment);
  1894. $form_state['values']['cid'] = $comment->cid;
  1895. // Add an entry to the watchdog log.
  1896. watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)));
  1897. // Explain the approval queue if necessary.
  1898. if ($comment->status == COMMENT_NOT_PUBLISHED) {
  1899. if (!user_access('administer comments')) {
  1900. drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
  1901. }
  1902. }
  1903. else {
  1904. drupal_set_message(t('Your comment has been posted.'));
  1905. }
  1906. $query = array();
  1907. // Find the current display page for this comment.
  1908. $page = comment_get_display_page($comment->cid, $node->type);
  1909. if ($page > 0) {
  1910. $query['page'] = $page;
  1911. }
  1912. // Redirect to the newly posted comment.
  1913. $redirect = array('node/' . $node->nid, array('query' => $query, 'fragment' => 'comment-' . $comment->cid));
  1914. }
  1915. else {
  1916. watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject), WATCHDOG_WARNING);
  1917. drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject)), 'error');
  1918. // Redirect the user to the node they are commenting on.
  1919. $redirect = 'node/' . $node->nid;
  1920. }
  1921. $form_state['redirect'] = $redirect;
  1922. // Clear the block and page caches so that anonymous users see the comment
  1923. // they have posted.
  1924. cache_clear_all();
  1925. }
  1926. /**
  1927. * Implements hook_preprocess_HOOK() for block.tpl.php.
  1928. */
  1929. function comment_preprocess_block(&$variables) {
  1930. if ($variables['block']->module == 'comment') {
  1931. $variables['attributes_array']['role'] = 'navigation';
  1932. }
  1933. }
  1934. /**
  1935. * Preprocesses variables for comment.tpl.php.
  1936. *
  1937. * @see comment.tpl.php
  1938. */
  1939. function template_preprocess_comment(&$variables) {
  1940. $comment = $variables['elements']['#comment'];
  1941. $node = $variables['elements']['#node'];
  1942. $variables['comment'] = $comment;
  1943. $variables['node'] = $node;
  1944. $variables['author'] = theme('username', array('account' => $comment));
  1945. $variables['created'] = format_date($comment->created);
  1946. $variables['changed'] = format_date($comment->changed);
  1947. $variables['new'] = !empty($comment->new) ? t('new') : '';
  1948. $variables['user_picture'] = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $comment)) : '';
  1949. $variables['signature'] = $comment->signature;
  1950. $uri = entity_uri('comment', $comment);
  1951. $uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  1952. $variables['title'] = l($comment->subject, $uri['path'], $uri['options']);
  1953. $variables['permalink'] = l(t('Permalink'), $uri['path'], $uri['options']);
  1954. $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['author'], '!datetime' => $variables['created']));
  1955. // Preprocess fields.
  1956. field_attach_preprocess('comment', $comment, $variables['elements'], $variables);
  1957. // Helpful $content variable for templates.
  1958. foreach (element_children($variables['elements']) as $key) {
  1959. $variables['content'][$key] = $variables['elements'][$key];
  1960. }
  1961. // Set status to a string representation of comment->status.
  1962. if (isset($comment->in_preview)) {
  1963. $variables['status'] = 'preview';
  1964. }
  1965. else {
  1966. $variables['status'] = ($comment->status == COMMENT_NOT_PUBLISHED) ? 'unpublished' : 'published';
  1967. }
  1968. // Gather comment classes.
  1969. // 'published' class is not needed, it is either 'preview' or 'unpublished'.
  1970. if ($variables['status'] != 'published') {
  1971. $variables['classes_array'][] = $variables['status'];
  1972. }
  1973. if ($variables['new']) {
  1974. $variables['classes_array'][] = 'new';
  1975. }
  1976. if (!$comment->uid) {
  1977. $variables['classes_array'][] = 'by-anonymous';
  1978. }
  1979. else {
  1980. if ($comment->uid == $variables['node']->uid) {
  1981. $variables['classes_array'][] = 'by-node-author';
  1982. }
  1983. if ($comment->uid == $variables['user']->uid) {
  1984. $variables['classes_array'][] = 'by-viewer';
  1985. }
  1986. }
  1987. }
  1988. /**
  1989. * Returns HTML for a "you can't post comments" notice.
  1990. *
  1991. * @param $variables
  1992. * An associative array containing:
  1993. * - node: The comment node.
  1994. *
  1995. * @ingroup themeable
  1996. */
  1997. function theme_comment_post_forbidden($variables) {
  1998. $node = $variables['node'];
  1999. global $user;
  2000. // Since this is expensive to compute, we cache it so that a page with many
  2001. // comments only has to query the database once for all the links.
  2002. $authenticated_post_comments = &drupal_static(__FUNCTION__, NULL);
  2003. if (!$user->uid) {
  2004. if (!isset($authenticated_post_comments)) {
  2005. // We only output a link if we are certain that users will get permission
  2006. // to post comments by logging in.
  2007. $comment_roles = user_roles(TRUE, 'post comments');
  2008. $authenticated_post_comments = isset($comment_roles[DRUPAL_AUTHENTICATED_RID]);
  2009. }
  2010. if ($authenticated_post_comments) {
  2011. // We cannot use drupal_get_destination() because these links
  2012. // sometimes appear on /node and taxonomy listing pages.
  2013. if (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW) == COMMENT_FORM_SEPARATE_PAGE) {
  2014. $destination = array('destination' => "comment/reply/$node->nid#comment-form");
  2015. }
  2016. else {
  2017. $destination = array('destination' => "node/$node->nid#comment-form");
  2018. }
  2019. if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
  2020. // Users can register themselves.
  2021. return t('<a href="@login">Log in</a> or <a href="@register">register</a> to post comments', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination))));
  2022. }
  2023. else {
  2024. // Only admins can add new users, no public registration.
  2025. return t('<a href="@login">Log in</a> to post comments', array('@login' => url('user/login', array('query' => $destination))));
  2026. }
  2027. }
  2028. }
  2029. }
  2030. /**
  2031. * Preprocesses variables for comment-wrapper.tpl.php.
  2032. *
  2033. * @see comment-wrapper.tpl.php
  2034. * @see theme_comment_wrapper()
  2035. */
  2036. function template_preprocess_comment_wrapper(&$variables) {
  2037. // Provide contextual information.
  2038. $variables['node'] = $variables['content']['#node'];
  2039. $variables['display_mode'] = variable_get('comment_default_mode_' . $variables['node']->type, COMMENT_MODE_THREADED);
  2040. // The comment form is optional and may not exist.
  2041. $variables['content'] += array('comment_form' => array());
  2042. }
  2043. /**
  2044. * Returns an array of viewing modes for comment listings.
  2045. *
  2046. * We can't use a global variable array because the locale system
  2047. * is not initialized yet when the Comment module is loaded.
  2048. */
  2049. function _comment_get_modes() {
  2050. return array(
  2051. COMMENT_MODE_FLAT => t('Flat list'),
  2052. COMMENT_MODE_THREADED => t('Threaded list')
  2053. );
  2054. }
  2055. /**
  2056. * Returns an array of "comments per page" values that users can select from.
  2057. */
  2058. function _comment_per_page() {
  2059. return drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300));
  2060. }
  2061. /**
  2062. * Generates a sorting code.
  2063. *
  2064. * Consists of a leading character indicating length, followed by N digits
  2065. * with a numerical value in base 36 (alphadecimal). These codes can be sorted
  2066. * as strings without altering numerical order.
  2067. *
  2068. * It goes:
  2069. * 00, 01, 02, ..., 0y, 0z,
  2070. * 110, 111, ... , 1zy, 1zz,
  2071. * 2100, 2101, ..., 2zzy, 2zzz,
  2072. * 31000, 31001, ...
  2073. */
  2074. function comment_int_to_alphadecimal($i = 0) {
  2075. $num = base_convert((int) $i, 10, 36);
  2076. $length = strlen($num);
  2077. return chr($length + ord('0') - 1) . $num;
  2078. }
  2079. /**
  2080. * Decodes a sorting code back to an integer.
  2081. *
  2082. * @see comment_int_to_alphadecimal()
  2083. */
  2084. function comment_alphadecimal_to_int($c = '00') {
  2085. return base_convert(substr($c, 1), 36, 10);
  2086. }
  2087. /**
  2088. * Increments a sorting code to the next value.
  2089. *
  2090. * @see comment_int_to_alphadecimal()
  2091. */
  2092. function comment_increment_alphadecimal($c = '00') {
  2093. return comment_int_to_alphadecimal(comment_alphadecimal_to_int($c) + 1);
  2094. }
  2095. /**
  2096. * Implements hook_action_info().
  2097. */
  2098. function comment_action_info() {
  2099. return array(
  2100. 'comment_publish_action' => array(
  2101. 'label' => t('Publish comment'),
  2102. 'type' => 'comment',
  2103. 'configurable' => FALSE,
  2104. 'behavior' => array('changes_property'),
  2105. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  2106. ),
  2107. 'comment_unpublish_action' => array(
  2108. 'label' => t('Unpublish comment'),
  2109. 'type' => 'comment',
  2110. 'configurable' => FALSE,
  2111. 'behavior' => array('changes_property'),
  2112. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  2113. ),
  2114. 'comment_unpublish_by_keyword_action' => array(
  2115. 'label' => t('Unpublish comment containing keyword(s)'),
  2116. 'type' => 'comment',
  2117. 'configurable' => TRUE,
  2118. 'behavior' => array('changes_property'),
  2119. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  2120. ),
  2121. 'comment_save_action' => array(
  2122. 'label' => t('Save comment'),
  2123. 'type' => 'comment',
  2124. 'configurable' => FALSE,
  2125. 'triggers' => array('comment_insert', 'comment_update'),
  2126. ),
  2127. );
  2128. }
  2129. /**
  2130. * Publishes a comment.
  2131. *
  2132. * @param Drupal\comment\Comment $comment
  2133. * (optional) A comment object to publish.
  2134. * @param array $context
  2135. * Array with components:
  2136. * - 'cid': Comment ID. Required if $comment is not given.
  2137. *
  2138. * @ingroup actions
  2139. */
  2140. function comment_publish_action(Comment $comment = NULL, $context = array()) {
  2141. if (isset($comment->subject)) {
  2142. $subject = $comment->subject;
  2143. $comment->status = COMMENT_PUBLISHED;
  2144. }
  2145. else {
  2146. $cid = $context['cid'];
  2147. $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(':cid' => $cid))->fetchField();
  2148. db_update('comment')
  2149. ->fields(array('status' => COMMENT_PUBLISHED))
  2150. ->condition('cid', $cid)
  2151. ->execute();
  2152. }
  2153. watchdog('action', 'Published comment %subject.', array('%subject' => $subject));
  2154. }
  2155. /**
  2156. * Unpublishes a comment.
  2157. *
  2158. * @param Drupal\comment\Comment|null $comment
  2159. * (optional) A comment object to unpublish.
  2160. * @param array $context
  2161. * Array with components:
  2162. * - 'cid': Comment ID. Required if $comment is not given.
  2163. *
  2164. * @ingroup actions
  2165. */
  2166. function comment_unpublish_action(Comment $comment = NULL, $context = array()) {
  2167. if (isset($comment->subject)) {
  2168. $subject = $comment->subject;
  2169. $comment->status = COMMENT_NOT_PUBLISHED;
  2170. }
  2171. else {
  2172. $cid = $context['cid'];
  2173. $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(':cid' => $cid))->fetchField();
  2174. db_update('comment')
  2175. ->fields(array('status' => COMMENT_NOT_PUBLISHED))
  2176. ->condition('cid', $cid)
  2177. ->execute();
  2178. }
  2179. watchdog('action', 'Unpublished comment %subject.', array('%subject' => $subject));
  2180. }
  2181. /**
  2182. * Unpublishes a comment if it contains certain keywords.
  2183. *
  2184. * @param Drupal\comment\Comment $comment
  2185. * Comment object to modify.
  2186. * @param array $context
  2187. * Array with components:
  2188. * - 'keywords': Keywords to look for. If the comment contains at least one
  2189. * of the keywords, it is unpublished.
  2190. *
  2191. * @ingroup actions
  2192. * @see comment_unpublish_by_keyword_action_form()
  2193. * @see comment_unpublish_by_keyword_action_submit()
  2194. */
  2195. function comment_unpublish_by_keyword_action(Comment $comment, $context) {
  2196. foreach ($context['keywords'] as $keyword) {
  2197. $text = drupal_render($comment);
  2198. if (strpos($text, $keyword) !== FALSE) {
  2199. $comment->status = COMMENT_NOT_PUBLISHED;
  2200. watchdog('action', 'Unpublished comment %subject.', array('%subject' => $comment->subject));
  2201. break;
  2202. }
  2203. }
  2204. }
  2205. /**
  2206. * Form constructor for the blacklisted keywords form.
  2207. *
  2208. * @ingroup forms
  2209. * @see comment_unpublish_by_keyword_action()
  2210. * @see comment_unpublish_by_keyword_action_submit()
  2211. */
  2212. function comment_unpublish_by_keyword_action_form($context) {
  2213. $form['keywords'] = array(
  2214. '#title' => t('Keywords'),
  2215. '#type' => 'textarea',
  2216. '#description' => t('The comment will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
  2217. '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  2218. );
  2219. return $form;
  2220. }
  2221. /**
  2222. * Form submission handler for comment_unpublish_by_keyword_action_form().
  2223. *
  2224. * @see comment_unpublish_by_keyword_action()
  2225. */
  2226. function comment_unpublish_by_keyword_action_submit($form, $form_state) {
  2227. return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
  2228. }
  2229. /**
  2230. * Saves a comment.
  2231. *
  2232. * @param Drupal\comment\Comment $comment
  2233. *
  2234. * @ingroup actions
  2235. */
  2236. function comment_save_action(Comment $comment) {
  2237. comment_save($comment);
  2238. cache_clear_all();
  2239. watchdog('action', 'Saved comment %title', array('%title' => $comment->subject));
  2240. }
  2241. /**
  2242. * Implements hook_ranking().
  2243. */
  2244. function comment_ranking() {
  2245. return array(
  2246. 'comments' => array(
  2247. 'title' => t('Number of comments'),
  2248. 'join' => array(
  2249. 'type' => 'LEFT',
  2250. 'table' => 'node_comment_statistics',
  2251. 'alias' => 'node_comment_statistics',
  2252. 'on' => 'node_comment_statistics.nid = i.sid',
  2253. ),
  2254. // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
  2255. 'score' => '2.0 - 2.0 / (1.0 + node_comment_statistics.comment_count * CAST(:scale AS DECIMAL))',
  2256. 'arguments' => array(':scale' => variable_get('node_cron_comments_scale', 0)),
  2257. ),
  2258. );
  2259. }
  2260. /**
  2261. * Implements hook_rdf_mapping().
  2262. */
  2263. function comment_rdf_mapping() {
  2264. return array(
  2265. array(
  2266. 'type' => 'comment',
  2267. 'bundle' => RDF_DEFAULT_BUNDLE,
  2268. 'mapping' => array(
  2269. 'rdftype' => array('sioc:Post', 'sioct:Comment'),
  2270. 'title' => array(
  2271. 'predicates' => array('dc:title'),
  2272. ),
  2273. 'created' => array(
  2274. 'predicates' => array('dc:date', 'dc:created'),
  2275. 'datatype' => 'xsd:dateTime',
  2276. 'callback' => 'date_iso8601',
  2277. ),
  2278. 'changed' => array(
  2279. 'predicates' => array('dc:modified'),
  2280. 'datatype' => 'xsd:dateTime',
  2281. 'callback' => 'date_iso8601',
  2282. ),
  2283. 'comment_body' => array(
  2284. 'predicates' => array('content:encoded'),
  2285. ),
  2286. 'pid' => array(
  2287. 'predicates' => array('sioc:reply_of'),
  2288. 'type' => 'rel',
  2289. ),
  2290. 'uid' => array(
  2291. 'predicates' => array('sioc:has_creator'),
  2292. 'type' => 'rel',
  2293. ),
  2294. 'name' => array(
  2295. 'predicates' => array('foaf:name'),
  2296. ),
  2297. ),
  2298. ),
  2299. );
  2300. }
  2301. /**
  2302. * Implements hook_file_download_access().
  2303. */
  2304. function comment_file_download_access($field, $entity_type, $entity) {
  2305. if ($entity_type == 'comment') {
  2306. if (user_access('access comments') && $entity->status == COMMENT_PUBLISHED || user_access('administer comments')) {
  2307. $node = node_load($entity->nid);
  2308. return node_access('view', $node);
  2309. }
  2310. return FALSE;
  2311. }
  2312. }
Login or register to post comments