comment.module 91 KB

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