comment.module 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716
  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. * Entity uri callback.
  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. drupal_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. // Build fields content.
  907. field_attach_prepare_view('comment', array($comment->cid => $comment), $view_mode, $langcode);
  908. entity_prepare_view('comment', array($comment->cid => $comment), $langcode);
  909. $comment->content += field_attach_view('comment', $comment, $view_mode, $langcode);
  910. $comment->content['links'] = array(
  911. '#theme' => 'links__comment',
  912. '#pre_render' => array('drupal_pre_render_links'),
  913. '#attributes' => array('class' => array('links', 'inline')),
  914. );
  915. if (empty($comment->in_preview)) {
  916. $comment->content['links']['comment'] = array(
  917. '#theme' => 'links__comment__comment',
  918. '#links' => comment_links($comment, $node),
  919. '#attributes' => array('class' => array('links', 'inline')),
  920. );
  921. }
  922. // Allow modules to make their own additions to the comment.
  923. module_invoke_all('comment_view', $comment, $view_mode, $langcode);
  924. module_invoke_all('entity_view', $comment, 'comment', $view_mode, $langcode);
  925. }
  926. /**
  927. * Helper function, build links for an individual comment.
  928. *
  929. * Adds reply, edit, delete etc. depending on the current user permissions.
  930. *
  931. * @param $comment
  932. * The comment object.
  933. * @param $node
  934. * The node the comment is attached to.
  935. * @return
  936. * A structured array of links.
  937. */
  938. function comment_links($comment, $node) {
  939. $links = array();
  940. if ($node->comment == COMMENT_NODE_OPEN) {
  941. if (user_access('administer comments') && user_access('post comments')) {
  942. $links['comment-delete'] = array(
  943. 'title' => t('delete'),
  944. 'href' => "comment/$comment->cid/delete",
  945. 'html' => TRUE,
  946. );
  947. $links['comment-edit'] = array(
  948. 'title' => t('edit'),
  949. 'href' => "comment/$comment->cid/edit",
  950. 'html' => TRUE,
  951. );
  952. $links['comment-reply'] = array(
  953. 'title' => t('reply'),
  954. 'href' => "comment/reply/$comment->nid/$comment->cid",
  955. 'html' => TRUE,
  956. );
  957. if ($comment->status == COMMENT_NOT_PUBLISHED) {
  958. $links['comment-approve'] = array(
  959. 'title' => t('approve'),
  960. 'href' => "comment/$comment->cid/approve",
  961. 'html' => TRUE,
  962. 'query' => array('token' => drupal_get_token("comment/$comment->cid/approve")),
  963. );
  964. }
  965. }
  966. elseif (user_access('post comments')) {
  967. if (comment_access('edit', $comment)) {
  968. $links['comment-edit'] = array(
  969. 'title' => t('edit'),
  970. 'href' => "comment/$comment->cid/edit",
  971. 'html' => TRUE,
  972. );
  973. }
  974. $links['comment-reply'] = array(
  975. 'title' => t('reply'),
  976. 'href' => "comment/reply/$comment->nid/$comment->cid",
  977. 'html' => TRUE,
  978. );
  979. }
  980. else {
  981. $links['comment_forbidden']['title'] = theme('comment_post_forbidden', array('node' => $node));
  982. $links['comment_forbidden']['html'] = TRUE;
  983. }
  984. }
  985. return $links;
  986. }
  987. /**
  988. * Construct a drupal_render() style array from an array of loaded comments.
  989. *
  990. * @param $comments
  991. * An array of comments as returned by comment_load_multiple().
  992. * @param $node
  993. * The node the comments are attached to.
  994. * @param $view_mode
  995. * View mode, e.g. 'full', 'teaser'...
  996. * @param $weight
  997. * An integer representing the weight of the first comment in the list.
  998. * @param $langcode
  999. * A string indicating the language field values are to be shown in. If no
  1000. * language is provided the current content language is used.
  1001. *
  1002. * @return
  1003. * An array in the format expected by drupal_render().
  1004. */
  1005. function comment_view_multiple($comments, $node, $view_mode = 'full', $weight = 0, $langcode = NULL) {
  1006. field_attach_prepare_view('comment', $comments, $view_mode, $langcode);
  1007. entity_prepare_view('comment', $comments, $langcode);
  1008. $build = array(
  1009. '#sorted' => TRUE,
  1010. );
  1011. foreach ($comments as $comment) {
  1012. $build[$comment->cid] = comment_view($comment, $node, $view_mode, $langcode);
  1013. $build[$comment->cid]['#weight'] = $weight;
  1014. $weight++;
  1015. }
  1016. return $build;
  1017. }
  1018. /**
  1019. * Implements hook_form_FORM_ID_alter().
  1020. */
  1021. function comment_form_node_type_form_alter(&$form, $form_state) {
  1022. if (isset($form['type'])) {
  1023. $form['comment'] = array(
  1024. '#type' => 'fieldset',
  1025. '#title' => t('Comment settings'),
  1026. '#collapsible' => TRUE,
  1027. '#collapsed' => TRUE,
  1028. '#group' => 'additional_settings',
  1029. '#attributes' => array(
  1030. 'class' => array('comment-node-type-settings-form'),
  1031. ),
  1032. '#attached' => array(
  1033. 'js' => array(drupal_get_path('module', 'comment') . '/comment-node-form.js'),
  1034. ),
  1035. );
  1036. // Unlike coment_form_node_form_alter(), all of these settings are applied
  1037. // as defaults to all new nodes. Therefore, it would be wrong to use #states
  1038. // to hide the other settings based on the primary comment setting.
  1039. $form['comment']['comment'] = array(
  1040. '#type' => 'select',
  1041. '#title' => t('Default comment setting for new content'),
  1042. '#default_value' => variable_get('comment_' . $form['#node_type']->type, COMMENT_NODE_OPEN),
  1043. '#options' => array(
  1044. COMMENT_NODE_OPEN => t('Open'),
  1045. COMMENT_NODE_CLOSED => t('Closed'),
  1046. COMMENT_NODE_HIDDEN => t('Hidden'),
  1047. ),
  1048. );
  1049. $form['comment']['comment_default_mode'] = array(
  1050. '#type' => 'checkbox',
  1051. '#title' => t('Threading'),
  1052. '#default_value' => variable_get('comment_default_mode_' . $form['#node_type']->type, COMMENT_MODE_THREADED),
  1053. '#description' => t('Show comment replies in a threaded list.'),
  1054. );
  1055. $form['comment']['comment_default_per_page'] = array(
  1056. '#type' => 'select',
  1057. '#title' => t('Comments per page'),
  1058. '#default_value' => variable_get('comment_default_per_page_' . $form['#node_type']->type, 50),
  1059. '#options' => _comment_per_page(),
  1060. );
  1061. $form['comment']['comment_anonymous'] = array(
  1062. '#type' => 'select',
  1063. '#title' => t('Anonymous commenting'),
  1064. '#default_value' => variable_get('comment_anonymous_' . $form['#node_type']->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  1065. '#options' => array(
  1066. COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'),
  1067. COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'),
  1068. COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information'),
  1069. ),
  1070. '#access' => user_access('post comments', drupal_anonymous_user()),
  1071. );
  1072. $form['comment']['comment_subject_field'] = array(
  1073. '#type' => 'checkbox',
  1074. '#title' => t('Allow comment title'),
  1075. '#default_value' => variable_get('comment_subject_field_' . $form['#node_type']->type, 1),
  1076. );
  1077. $form['comment']['comment_form_location'] = array(
  1078. '#type' => 'checkbox',
  1079. '#title' => t('Show reply form on the same page as comments'),
  1080. '#default_value' => variable_get('comment_form_location_' . $form['#node_type']->type, COMMENT_FORM_BELOW),
  1081. );
  1082. $form['comment']['comment_preview'] = array(
  1083. '#type' => 'radios',
  1084. '#title' => t('Preview comment'),
  1085. '#default_value' => variable_get('comment_preview_' . $form['#node_type']->type, DRUPAL_OPTIONAL),
  1086. '#options' => array(
  1087. DRUPAL_DISABLED => t('Disabled'),
  1088. DRUPAL_OPTIONAL => t('Optional'),
  1089. DRUPAL_REQUIRED => t('Required'),
  1090. ),
  1091. );
  1092. }
  1093. }
  1094. /**
  1095. * Implements hook_form_BASE_FORM_ID_alter().
  1096. */
  1097. function comment_form_node_form_alter(&$form, $form_state) {
  1098. $node = $form['#node'];
  1099. $form['comment_settings'] = array(
  1100. '#type' => 'fieldset',
  1101. '#access' => user_access('administer comments'),
  1102. '#title' => t('Comment settings'),
  1103. '#collapsible' => TRUE,
  1104. '#collapsed' => TRUE,
  1105. '#group' => 'additional_settings',
  1106. '#attributes' => array(
  1107. 'class' => array('comment-node-settings-form'),
  1108. ),
  1109. '#attached' => array(
  1110. 'js' => array(drupal_get_path('module', 'comment') . '/comment-node-form.js'),
  1111. ),
  1112. '#weight' => 30,
  1113. );
  1114. $comment_count = isset($node->nid) ? db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField() : 0;
  1115. $comment_settings = ($node->comment == COMMENT_NODE_HIDDEN && empty($comment_count)) ? COMMENT_NODE_CLOSED : $node->comment;
  1116. $form['comment_settings']['comment'] = array(
  1117. '#type' => 'radios',
  1118. '#title' => t('Comments'),
  1119. '#title_display' => 'invisible',
  1120. '#parents' => array('comment'),
  1121. '#default_value' => $comment_settings,
  1122. '#options' => array(
  1123. COMMENT_NODE_OPEN => t('Open'),
  1124. COMMENT_NODE_CLOSED => t('Closed'),
  1125. COMMENT_NODE_HIDDEN => t('Hidden'),
  1126. ),
  1127. COMMENT_NODE_OPEN => array(
  1128. '#description' => t('Users with the "Post comments" permission can post comments.'),
  1129. ),
  1130. COMMENT_NODE_CLOSED => array(
  1131. '#description' => t('Users cannot post comments, but existing comments will be displayed.'),
  1132. ),
  1133. COMMENT_NODE_HIDDEN => array(
  1134. '#description' => t('Comments are hidden from view.'),
  1135. ),
  1136. );
  1137. // If the node doesn't have any comments, the "hidden" option makes no
  1138. // sense, so don't even bother presenting it to the user.
  1139. if (empty($comment_count)) {
  1140. $form['comment_settings']['comment'][COMMENT_NODE_HIDDEN]['#access'] = FALSE;
  1141. // Also adjust the description of the "closed" option.
  1142. $form['comment_settings']['comment'][COMMENT_NODE_CLOSED]['#description'] = t('Users cannot post comments.');
  1143. }
  1144. }
  1145. /**
  1146. * Implements hook_node_load().
  1147. */
  1148. function comment_node_load($nodes, $types) {
  1149. $comments_enabled = array();
  1150. // Check if comments are enabled for each node. If comments are disabled,
  1151. // assign values without hitting the database.
  1152. foreach ($nodes as $node) {
  1153. // Store whether comments are enabled for this node.
  1154. if ($node->comment != COMMENT_NODE_HIDDEN) {
  1155. $comments_enabled[] = $node->nid;
  1156. }
  1157. else {
  1158. $node->cid = 0;
  1159. $node->last_comment_timestamp = $node->created;
  1160. $node->last_comment_name = '';
  1161. $node->last_comment_uid = $node->uid;
  1162. $node->comment_count = 0;
  1163. }
  1164. }
  1165. // For nodes with comments enabled, fetch information from the database.
  1166. if (!empty($comments_enabled)) {
  1167. $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));
  1168. foreach ($result as $record) {
  1169. $nodes[$record->nid]->cid = $record->cid;
  1170. $nodes[$record->nid]->last_comment_timestamp = $record->last_comment_timestamp;
  1171. $nodes[$record->nid]->last_comment_name = $record->last_comment_name;
  1172. $nodes[$record->nid]->last_comment_uid = $record->last_comment_uid;
  1173. $nodes[$record->nid]->comment_count = $record->comment_count;
  1174. }
  1175. }
  1176. }
  1177. /**
  1178. * Implements hook_node_prepare().
  1179. */
  1180. function comment_node_prepare($node) {
  1181. if (!isset($node->comment)) {
  1182. $node->comment = variable_get("comment_$node->type", COMMENT_NODE_OPEN);
  1183. }
  1184. }
  1185. /**
  1186. * Implements hook_node_insert().
  1187. */
  1188. function comment_node_insert($node) {
  1189. // Allow bulk updates and inserts to temporarily disable the
  1190. // maintenance of the {node_comment_statistics} table.
  1191. if (variable_get('comment_maintain_node_statistics', TRUE)) {
  1192. db_insert('node_comment_statistics')
  1193. ->fields(array(
  1194. 'nid' => $node->nid,
  1195. 'cid' => 0,
  1196. 'last_comment_timestamp' => $node->changed,
  1197. 'last_comment_name' => NULL,
  1198. 'last_comment_uid' => $node->uid,
  1199. 'comment_count' => 0,
  1200. ))
  1201. ->execute();
  1202. }
  1203. }
  1204. /**
  1205. * Implements hook_node_delete().
  1206. */
  1207. function comment_node_delete($node) {
  1208. $cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchCol();
  1209. comment_delete_multiple($cids);
  1210. db_delete('node_comment_statistics')
  1211. ->condition('nid', $node->nid)
  1212. ->execute();
  1213. }
  1214. /**
  1215. * Implements hook_node_update_index().
  1216. */
  1217. function comment_node_update_index($node) {
  1218. $index_comments = &drupal_static(__FUNCTION__);
  1219. if ($index_comments === NULL) {
  1220. // Find and save roles that can 'access comments' or 'search content'.
  1221. $perms = array('access comments' => array(), 'search content' => array());
  1222. $result = db_query("SELECT rid, permission FROM {role_permission} WHERE permission IN ('access comments', 'search content')");
  1223. foreach ($result as $record) {
  1224. $perms[$record->permission][$record->rid] = $record->rid;
  1225. }
  1226. // Prevent indexing of comments if there are any roles that can search but
  1227. // not view comments.
  1228. $index_comments = TRUE;
  1229. foreach ($perms['search content'] as $rid) {
  1230. if (!isset($perms['access comments'][$rid]) && ($rid <= DRUPAL_AUTHENTICATED_RID || !isset($perms['access comments'][DRUPAL_AUTHENTICATED_RID]))) {
  1231. $index_comments = FALSE;
  1232. break;
  1233. }
  1234. }
  1235. }
  1236. if ($index_comments) {
  1237. $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
  1238. $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
  1239. if ($node->comment && $cids = comment_get_thread($node, $mode, $comments_per_page)) {
  1240. $comments = comment_load_multiple($cids);
  1241. comment_prepare_thread($comments);
  1242. $build = comment_view_multiple($comments, $node);
  1243. return drupal_render($build);
  1244. }
  1245. }
  1246. return '';
  1247. }
  1248. /**
  1249. * Implements hook_update_index().
  1250. */
  1251. function comment_update_index() {
  1252. // Store the maximum possible comments per thread (used for ranking by reply count)
  1253. variable_set('node_cron_comments_scale', 1.0 / max(1, db_query('SELECT MAX(comment_count) FROM {node_comment_statistics}')->fetchField()));
  1254. }
  1255. /**
  1256. * Implements hook_node_search_result().
  1257. *
  1258. * Formats a comment count string and returns it, for display with search
  1259. * results.
  1260. */
  1261. function comment_node_search_result($node) {
  1262. // Do not make a string if comments are hidden.
  1263. if (user_access('access comments') && $node->comment != COMMENT_NODE_HIDDEN) {
  1264. $comments = db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array('nid' => $node->nid))->fetchField();
  1265. // Do not make a string if comments are closed and there are currently
  1266. // zero comments.
  1267. if ($node->comment != COMMENT_NODE_CLOSED || $comments > 0) {
  1268. return array('comment' => format_plural($comments, '1 comment', '@count comments'));
  1269. }
  1270. }
  1271. }
  1272. /**
  1273. * Implements hook_user_cancel().
  1274. */
  1275. function comment_user_cancel($edit, $account, $method) {
  1276. switch ($method) {
  1277. case 'user_cancel_block_unpublish':
  1278. $comments = comment_load_multiple(array(), array('uid' => $account->uid));
  1279. foreach ($comments as $comment) {
  1280. $comment->status = 0;
  1281. comment_save($comment);
  1282. }
  1283. break;
  1284. case 'user_cancel_reassign':
  1285. $comments = comment_load_multiple(array(), array('uid' => $account->uid));
  1286. foreach ($comments as $comment) {
  1287. $comment->uid = 0;
  1288. comment_save($comment);
  1289. }
  1290. break;
  1291. }
  1292. }
  1293. /**
  1294. * Implements hook_user_delete().
  1295. */
  1296. function comment_user_delete($account) {
  1297. $cids = db_query('SELECT c.cid FROM {comment} c WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
  1298. comment_delete_multiple($cids);
  1299. }
  1300. /**
  1301. * Determines whether the current user has access to a particular comment.
  1302. *
  1303. * Authenticated users can edit their comments as long they have not been
  1304. * replied to. This prevents people from changing or revising their statements
  1305. * based on the replies to their posts.
  1306. *
  1307. * @param $op
  1308. * The operation that is to be performed on the comment. Only 'edit' is
  1309. * recognized now.
  1310. * @param $comment
  1311. * The comment object.
  1312. * @return
  1313. * TRUE if the current user has acces to the comment, FALSE otherwise.
  1314. */
  1315. function comment_access($op, $comment) {
  1316. global $user;
  1317. if ($op == 'edit') {
  1318. return ($user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
  1319. }
  1320. }
  1321. /**
  1322. * Accepts a submission of new or changed comment content.
  1323. *
  1324. * @param $comment
  1325. * A comment object.
  1326. */
  1327. function comment_save($comment) {
  1328. global $user;
  1329. $transaction = db_transaction();
  1330. try {
  1331. $defaults = array(
  1332. 'mail' => '',
  1333. 'homepage' => '',
  1334. 'name' => '',
  1335. 'status' => user_access('skip comment approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED,
  1336. );
  1337. foreach ($defaults as $key => $default) {
  1338. if (!isset($comment->$key)) {
  1339. $comment->$key = $default;
  1340. }
  1341. }
  1342. // Make sure we have a bundle name.
  1343. if (!isset($comment->node_type)) {
  1344. $node = node_load($comment->nid);
  1345. $comment->node_type = 'comment_node_' . $node->type;
  1346. }
  1347. // Load the stored entity, if any.
  1348. if (!empty($comment->cid) && !isset($comment->original)) {
  1349. $comment->original = entity_load_unchanged('comment', $comment->cid);
  1350. }
  1351. field_attach_presave('comment', $comment);
  1352. // Allow modules to alter the comment before saving.
  1353. module_invoke_all('comment_presave', $comment);
  1354. module_invoke_all('entity_presave', $comment, 'comment');
  1355. if ($comment->cid) {
  1356. drupal_write_record('comment', $comment, 'cid');
  1357. // Ignore slave server temporarily to give time for the
  1358. // saved comment to be propagated to the slave.
  1359. db_ignore_slave();
  1360. // Update the {node_comment_statistics} table prior to executing hooks.
  1361. _comment_update_node_statistics($comment->nid);
  1362. field_attach_update('comment', $comment);
  1363. // Allow modules to respond to the updating of a comment.
  1364. module_invoke_all('comment_update', $comment);
  1365. module_invoke_all('entity_update', $comment, 'comment');
  1366. }
  1367. else {
  1368. // Add the comment to database. This next section builds the thread field.
  1369. // Also see the documentation for comment_view().
  1370. if (!empty($comment->thread)) {
  1371. // Allow calling code to set thread itself.
  1372. $thread = $comment->thread;
  1373. }
  1374. elseif ($comment->pid == 0) {
  1375. // This is a comment with no parent comment (depth 0): we start
  1376. // by retrieving the maximum thread level.
  1377. $max = db_query('SELECT MAX(thread) FROM {comment} WHERE nid = :nid', array(':nid' => $comment->nid))->fetchField();
  1378. // Strip the "/" from the end of the thread.
  1379. $max = rtrim($max, '/');
  1380. // We need to get the value at the correct depth.
  1381. $parts = explode('.', $max);
  1382. $firstsegment = $parts[0];
  1383. // Finally, build the thread field for this new comment.
  1384. $thread = int2vancode(vancode2int($firstsegment) + 1) . '/';
  1385. }
  1386. else {
  1387. // This is a comment with a parent comment, so increase the part of the
  1388. // thread value at the proper depth.
  1389. // Get the parent comment:
  1390. $parent = comment_load($comment->pid);
  1391. // Strip the "/" from the end of the parent thread.
  1392. $parent->thread = (string) rtrim((string) $parent->thread, '/');
  1393. // Get the max value in *this* thread.
  1394. $max = db_query("SELECT MAX(thread) FROM {comment} WHERE thread LIKE :thread AND nid = :nid", array(
  1395. ':thread' => $parent->thread . '.%',
  1396. ':nid' => $comment->nid,
  1397. ))->fetchField();
  1398. if ($max == '') {
  1399. // First child of this parent.
  1400. $thread = $parent->thread . '.' . int2vancode(0) . '/';
  1401. }
  1402. else {
  1403. // Strip the "/" at the end of the thread.
  1404. $max = rtrim($max, '/');
  1405. // Get the value at the correct depth.
  1406. $parts = explode('.', $max);
  1407. $parent_depth = count(explode('.', $parent->thread));
  1408. $last = $parts[$parent_depth];
  1409. // Finally, build the thread field for this new comment.
  1410. $thread = $parent->thread . '.' . int2vancode(vancode2int($last) + 1) . '/';
  1411. }
  1412. }
  1413. if (empty($comment->created)) {
  1414. $comment->created = REQUEST_TIME;
  1415. }
  1416. if (empty($comment->changed)) {
  1417. $comment->changed = $comment->created;
  1418. }
  1419. if ($comment->uid === $user->uid && isset($user->name)) { // '===' Need to modify anonymous users as well.
  1420. $comment->name = $user->name;
  1421. }
  1422. // Ensure the parent id (pid) has a value set.
  1423. if (empty($comment->pid)) {
  1424. $comment->pid = 0;
  1425. }
  1426. // Add the values which aren't passed into the function.
  1427. $comment->thread = $thread;
  1428. $comment->hostname = ip_address();
  1429. drupal_write_record('comment', $comment);
  1430. // Ignore slave server temporarily to give time for the
  1431. // created comment to be propagated to the slave.
  1432. db_ignore_slave();
  1433. // Update the {node_comment_statistics} table prior to executing hooks.
  1434. _comment_update_node_statistics($comment->nid);
  1435. field_attach_insert('comment', $comment);
  1436. // Tell the other modules a new comment has been submitted.
  1437. module_invoke_all('comment_insert', $comment);
  1438. module_invoke_all('entity_insert', $comment, 'comment');
  1439. }
  1440. if ($comment->status == COMMENT_PUBLISHED) {
  1441. module_invoke_all('comment_publish', $comment);
  1442. }
  1443. unset($comment->original);
  1444. }
  1445. catch (Exception $e) {
  1446. $transaction->rollback('comment');
  1447. watchdog_exception('comment', $e);
  1448. throw $e;
  1449. }
  1450. }
  1451. /**
  1452. * Delete a comment and all its replies.
  1453. *
  1454. * @param $cid
  1455. * The comment to delete.
  1456. */
  1457. function comment_delete($cid) {
  1458. comment_delete_multiple(array($cid));
  1459. }
  1460. /**
  1461. * Delete comments and all their replies.
  1462. *
  1463. * @param $cids
  1464. * The comment to delete.
  1465. */
  1466. function comment_delete_multiple($cids) {
  1467. $comments = comment_load_multiple($cids);
  1468. if ($comments) {
  1469. $transaction = db_transaction();
  1470. try {
  1471. // Delete the comments.
  1472. db_delete('comment')
  1473. ->condition('cid', array_keys($comments), 'IN')
  1474. ->execute();
  1475. foreach ($comments as $comment) {
  1476. field_attach_delete('comment', $comment);
  1477. module_invoke_all('comment_delete', $comment);
  1478. module_invoke_all('entity_delete', $comment, 'comment');
  1479. // Delete the comment's replies.
  1480. $child_cids = db_query('SELECT cid FROM {comment} WHERE pid = :cid', array(':cid' => $comment->cid))->fetchCol();
  1481. comment_delete_multiple($child_cids);
  1482. _comment_update_node_statistics($comment->nid);
  1483. }
  1484. }
  1485. catch (Exception $e) {
  1486. $transaction->rollback();
  1487. watchdog_exception('comment', $e);
  1488. throw $e;
  1489. }
  1490. }
  1491. }
  1492. /**
  1493. * Load comments from the database.
  1494. *
  1495. * @param $cids
  1496. * An array of comment IDs.
  1497. * @param $conditions
  1498. * (deprecated) An associative array of conditions on the {comments}
  1499. * table, where the keys are the database fields and the values are the
  1500. * values those fields must have. Instead, it is preferable to use
  1501. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  1502. * this function.
  1503. * @param $reset
  1504. * Whether to reset the internal static entity cache. Note that the static
  1505. * cache is disabled in comment_entity_info() by default.
  1506. *
  1507. * @return
  1508. * An array of comment objects, indexed by comment ID.
  1509. *
  1510. * @see entity_load()
  1511. * @see EntityFieldQuery
  1512. *
  1513. * @todo Remove $conditions in Drupal 8.
  1514. */
  1515. function comment_load_multiple($cids = array(), $conditions = array(), $reset = FALSE) {
  1516. return entity_load('comment', $cids, $conditions, $reset);
  1517. }
  1518. /**
  1519. * Load the entire comment by cid.
  1520. *
  1521. * @param $cid
  1522. * The identifying comment id.
  1523. * @param $reset
  1524. * Whether to reset the internal static entity cache. Note that the static
  1525. * cache is disabled in comment_entity_info() by default.
  1526. *
  1527. * @return
  1528. * The comment object.
  1529. */
  1530. function comment_load($cid, $reset = FALSE) {
  1531. $comment = comment_load_multiple(array($cid), array(), $reset);
  1532. return $comment ? $comment[$cid] : FALSE;
  1533. }
  1534. /**
  1535. * Controller class for comments.
  1536. *
  1537. * This extends the DrupalDefaultEntityController class, adding required
  1538. * special handling for comment objects.
  1539. */
  1540. class CommentController extends DrupalDefaultEntityController {
  1541. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  1542. $query = parent::buildQuery($ids, $conditions, $revision_id);
  1543. // Specify additional fields from the user and node tables.
  1544. $query->innerJoin('node', 'n', 'base.nid = n.nid');
  1545. $query->addField('n', 'type', 'node_type');
  1546. $query->innerJoin('users', 'u', 'base.uid = u.uid');
  1547. $query->addField('u', 'name', 'registered_name');
  1548. $query->fields('u', array('uid', 'signature', 'signature_format', 'picture'));
  1549. return $query;
  1550. }
  1551. protected function attachLoad(&$comments, $revision_id = FALSE) {
  1552. // Setup standard comment properties.
  1553. foreach ($comments as $key => $comment) {
  1554. $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
  1555. $comment->new = node_mark($comment->nid, $comment->changed);
  1556. $comment->node_type = 'comment_node_' . $comment->node_type;
  1557. $comments[$key] = $comment;
  1558. }
  1559. parent::attachLoad($comments, $revision_id);
  1560. }
  1561. }
  1562. /**
  1563. * Get number of new comments for current user and specified node.
  1564. *
  1565. * @param $nid
  1566. * Node-id to count comments for.
  1567. * @param $timestamp
  1568. * Time to count from (defaults to time of last user access
  1569. * to node).
  1570. * @return The result or FALSE on error.
  1571. */
  1572. function comment_num_new($nid, $timestamp = 0) {
  1573. global $user;
  1574. if ($user->uid) {
  1575. // Retrieve the timestamp at which the current user last viewed this node.
  1576. if (!$timestamp) {
  1577. $timestamp = node_last_viewed($nid);
  1578. }
  1579. $timestamp = ($timestamp > NODE_NEW_LIMIT ? $timestamp : NODE_NEW_LIMIT);
  1580. // Use the timestamp to retrieve the number of new comments.
  1581. return db_query('SELECT COUNT(cid) FROM {comment} WHERE nid = :nid AND created > :timestamp AND status = :status', array(
  1582. ':nid' => $nid,
  1583. ':timestamp' => $timestamp,
  1584. ':status' => COMMENT_PUBLISHED,
  1585. ))->fetchField();
  1586. }
  1587. else {
  1588. return FALSE;
  1589. }
  1590. }
  1591. /**
  1592. * Get the display ordinal for a comment, starting from 0.
  1593. *
  1594. * Count the number of comments which appear before the comment we want to
  1595. * display, taking into account display settings and threading.
  1596. *
  1597. * @param $cid
  1598. * The comment ID.
  1599. * @param $node_type
  1600. * The node type of the comment's parent.
  1601. * @return
  1602. * The display ordinal for the comment.
  1603. * @see comment_get_display_page()
  1604. */
  1605. function comment_get_display_ordinal($cid, $node_type) {
  1606. // Count how many comments (c1) are before $cid (c2) in display order. This is
  1607. // the 0-based display ordinal.
  1608. $query = db_select('comment', 'c1');
  1609. $query->innerJoin('comment', 'c2', 'c2.nid = c1.nid');
  1610. $query->addExpression('COUNT(*)', 'count');
  1611. $query->condition('c2.cid', $cid);
  1612. if (!user_access('administer comments')) {
  1613. $query->condition('c1.status', COMMENT_PUBLISHED);
  1614. }
  1615. $mode = variable_get('comment_default_mode_' . $node_type, COMMENT_MODE_THREADED);
  1616. if ($mode == COMMENT_MODE_FLAT) {
  1617. // For flat comments, cid is used for ordering comments due to
  1618. // unpredicatable behavior with timestamp, so we make the same assumption
  1619. // here.
  1620. $query->condition('c1.cid', $cid, '<');
  1621. }
  1622. else {
  1623. // For threaded comments, the c.thread column is used for ordering. We can
  1624. // use the vancode for comparison, but must remove the trailing slash.
  1625. // See comment_view_multiple().
  1626. $query->where('SUBSTRING(c1.thread, 1, (LENGTH(c1.thread) -1)) < SUBSTRING(c2.thread, 1, (LENGTH(c2.thread) -1))');
  1627. }
  1628. return $query->execute()->fetchField();
  1629. }
  1630. /**
  1631. * Return the page number for a comment.
  1632. *
  1633. * Finds the correct page number for a comment taking into account display
  1634. * and paging settings.
  1635. *
  1636. * @param $cid
  1637. * The comment ID.
  1638. * @param $node_type
  1639. * The node type the comment is attached to.
  1640. * @return
  1641. * The page number.
  1642. */
  1643. function comment_get_display_page($cid, $node_type) {
  1644. $ordinal = comment_get_display_ordinal($cid, $node_type);
  1645. $comments_per_page = variable_get('comment_default_per_page_' . $node_type, 50);
  1646. return floor($ordinal / $comments_per_page);
  1647. }
  1648. /**
  1649. * Page callback for comment editing.
  1650. */
  1651. function comment_edit_page($comment) {
  1652. drupal_set_title(t('Edit comment %comment', array('%comment' => $comment->subject)), PASS_THROUGH);
  1653. $node = node_load($comment->nid);
  1654. return drupal_get_form("comment_node_{$node->type}_form", $comment);
  1655. }
  1656. /**
  1657. * Implements hook_forms().
  1658. */
  1659. function comment_forms() {
  1660. $forms = array();
  1661. foreach (node_type_get_types() as $type) {
  1662. $forms["comment_node_{$type->type}_form"]['callback'] = 'comment_form';
  1663. }
  1664. return $forms;
  1665. }
  1666. /**
  1667. * Generate the basic commenting form, for appending to a node or display on a separate page.
  1668. *
  1669. * @see comment_form_validate()
  1670. * @see comment_form_submit()
  1671. *
  1672. * @ingroup forms
  1673. */
  1674. function comment_form($form, &$form_state, $comment) {
  1675. global $user;
  1676. // During initial form build, add the comment entity to the form state for
  1677. // use during form building and processing. During a rebuild, use what is in
  1678. // the form state.
  1679. if (!isset($form_state['comment'])) {
  1680. $defaults = array(
  1681. 'name' => '',
  1682. 'mail' => '',
  1683. 'homepage' => '',
  1684. 'subject' => '',
  1685. 'comment' => '',
  1686. 'cid' => NULL,
  1687. 'pid' => NULL,
  1688. 'language' => LANGUAGE_NONE,
  1689. 'uid' => 0,
  1690. );
  1691. foreach ($defaults as $key => $value) {
  1692. if (!isset($comment->$key)) {
  1693. $comment->$key = $value;
  1694. }
  1695. }
  1696. $form_state['comment'] = $comment;
  1697. }
  1698. else {
  1699. $comment = $form_state['comment'];
  1700. }
  1701. $node = node_load($comment->nid);
  1702. $form['#node'] = $node;
  1703. // Use #comment-form as unique jump target, regardless of node type.
  1704. $form['#id'] = drupal_html_id('comment_form');
  1705. $form['#attributes']['class'][] = 'comment-form';
  1706. $form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');
  1707. $anonymous_contact = variable_get('comment_anonymous_' . $node->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT);
  1708. $is_admin = (!empty($comment->cid) && user_access('administer comments'));
  1709. if (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
  1710. $form['#attached']['library'][] = array('system', 'jquery.cookie');
  1711. $form['#attributes']['class'][] = 'user-info-from-cookie';
  1712. }
  1713. // If not replying to a comment, use our dedicated page callback for new
  1714. // comments on nodes.
  1715. if (empty($comment->cid) && empty($comment->pid)) {
  1716. $form['#action'] = url('comment/reply/' . $comment->nid);
  1717. }
  1718. if (isset($form_state['comment_preview'])) {
  1719. $form += $form_state['comment_preview'];
  1720. }
  1721. // Display author information in a fieldset for comment moderators.
  1722. if ($is_admin) {
  1723. $form['author'] = array(
  1724. '#type' => 'fieldset',
  1725. '#title' => t('Administration'),
  1726. '#collapsible' => TRUE,
  1727. '#collapsed' => TRUE,
  1728. '#weight' => -2,
  1729. );
  1730. }
  1731. else {
  1732. // Sets the author form elements above the subject.
  1733. $form['author'] = array(
  1734. '#weight' => -2,
  1735. );
  1736. }
  1737. // Prepare default values for form elements.
  1738. if ($is_admin) {
  1739. $author = (!$comment->uid && $comment->name ? $comment->name : $comment->registered_name);
  1740. $status = (isset($comment->status) ? $comment->status : COMMENT_NOT_PUBLISHED);
  1741. $date = (!empty($comment->date) ? $comment->date : format_date($comment->created, 'custom', 'Y-m-d H:i O'));
  1742. }
  1743. else {
  1744. if ($user->uid) {
  1745. $author = $user->name;
  1746. }
  1747. else {
  1748. $author = ($comment->name ? $comment->name : '');
  1749. }
  1750. $status = (user_access('skip comment approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED);
  1751. $date = '';
  1752. }
  1753. // Add the author name field depending on the current user.
  1754. if ($is_admin) {
  1755. $form['author']['name'] = array(
  1756. '#type' => 'textfield',
  1757. '#title' => t('Authored by'),
  1758. '#default_value' => $author,
  1759. '#maxlength' => 60,
  1760. '#size' => 30,
  1761. '#description' => t('Leave blank for %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous')))),
  1762. '#autocomplete_path' => 'user/autocomplete',
  1763. );
  1764. }
  1765. elseif ($user->uid) {
  1766. $form['author']['_author'] = array(
  1767. '#type' => 'item',
  1768. '#title' => t('Your name'),
  1769. '#markup' => theme('username', array('account' => $user)),
  1770. );
  1771. $form['author']['name'] = array(
  1772. '#type' => 'value',
  1773. '#value' => $author,
  1774. );
  1775. }
  1776. else {
  1777. $form['author']['name'] = array(
  1778. '#type' => 'textfield',
  1779. '#title' => t('Your name'),
  1780. '#default_value' => $author,
  1781. '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
  1782. '#maxlength' => 60,
  1783. '#size' => 30,
  1784. );
  1785. }
  1786. // Add author e-mail and homepage fields depending on the current user.
  1787. $form['author']['mail'] = array(
  1788. '#type' => 'textfield',
  1789. '#title' => t('E-mail'),
  1790. '#default_value' => $comment->mail,
  1791. '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
  1792. '#maxlength' => 64,
  1793. '#size' => 30,
  1794. '#description' => t('The content of this field is kept private and will not be shown publicly.'),
  1795. '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  1796. );
  1797. $form['author']['homepage'] = array(
  1798. '#type' => 'textfield',
  1799. '#title' => t('Homepage'),
  1800. '#default_value' => $comment->homepage,
  1801. '#maxlength' => 255,
  1802. '#size' => 30,
  1803. '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  1804. );
  1805. // Add administrative comment publishing options.
  1806. $form['author']['date'] = array(
  1807. '#type' => 'textfield',
  1808. '#title' => t('Authored on'),
  1809. '#default_value' => $date,
  1810. '#maxlength' => 25,
  1811. '#size' => 20,
  1812. '#access' => $is_admin,
  1813. );
  1814. $form['author']['status'] = array(
  1815. '#type' => 'radios',
  1816. '#title' => t('Status'),
  1817. '#default_value' => $status,
  1818. '#options' => array(
  1819. COMMENT_PUBLISHED => t('Published'),
  1820. COMMENT_NOT_PUBLISHED => t('Not published'),
  1821. ),
  1822. '#access' => $is_admin,
  1823. );
  1824. $form['subject'] = array(
  1825. '#type' => 'textfield',
  1826. '#title' => t('Subject'),
  1827. '#maxlength' => 64,
  1828. '#default_value' => $comment->subject,
  1829. '#access' => variable_get('comment_subject_field_' . $node->type, 1) == 1,
  1830. '#weight' => -1,
  1831. );
  1832. // Used for conditional validation of author fields.
  1833. $form['is_anonymous'] = array(
  1834. '#type' => 'value',
  1835. '#value' => ($comment->cid ? !$comment->uid : !$user->uid),
  1836. );
  1837. // Add internal comment properties.
  1838. foreach (array('cid', 'pid', 'nid', 'language', 'uid') as $key) {
  1839. $form[$key] = array('#type' => 'value', '#value' => $comment->$key);
  1840. }
  1841. $form['node_type'] = array('#type' => 'value', '#value' => 'comment_node_' . $node->type);
  1842. // Only show the save button if comment previews are optional or if we are
  1843. // already previewing the submission.
  1844. $form['actions'] = array('#type' => 'actions');
  1845. $form['actions']['submit'] = array(
  1846. '#type' => 'submit',
  1847. '#value' => t('Save'),
  1848. '#access' => ($comment->cid && user_access('administer comments')) || variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || isset($form_state['comment_preview']),
  1849. '#weight' => 19,
  1850. );
  1851. $form['actions']['preview'] = array(
  1852. '#type' => 'submit',
  1853. '#value' => t('Preview'),
  1854. '#access' => (variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED),
  1855. '#weight' => 20,
  1856. '#submit' => array('comment_form_build_preview'),
  1857. );
  1858. // Attach fields.
  1859. $comment->node_type = 'comment_node_' . $node->type;
  1860. field_attach_form('comment', $comment, $form, $form_state);
  1861. return $form;
  1862. }
  1863. /**
  1864. * Build a preview from submitted form values.
  1865. */
  1866. function comment_form_build_preview($form, &$form_state) {
  1867. $comment = comment_form_submit_build_comment($form, $form_state);
  1868. $form_state['comment_preview'] = comment_preview($comment);
  1869. $form_state['rebuild'] = TRUE;
  1870. }
  1871. /**
  1872. * Generate a comment preview.
  1873. */
  1874. function comment_preview($comment) {
  1875. global $user;
  1876. drupal_set_title(t('Preview comment'), PASS_THROUGH);
  1877. $node = node_load($comment->nid);
  1878. if (!form_get_errors()) {
  1879. $comment->format = $comment->comment_body[LANGUAGE_NONE][0]['format'];
  1880. // Attach the user and time information.
  1881. if (!empty($comment->name)) {
  1882. $account = user_load_by_name($comment->name);
  1883. }
  1884. elseif ($user->uid && empty($comment->is_anonymous)) {
  1885. $account = $user;
  1886. }
  1887. if (!empty($account->uid)) {
  1888. $comment->uid = $account->uid;
  1889. $comment->name = check_plain($account->name);
  1890. $comment->signature = $account->signature;
  1891. $comment->signature_format = $account->signature_format;
  1892. $comment->picture = $account->picture;
  1893. }
  1894. elseif (empty($comment->name)) {
  1895. $comment->name = variable_get('anonymous', t('Anonymous'));
  1896. }
  1897. $comment->created = !empty($comment->created) ? $comment->created : REQUEST_TIME;
  1898. $comment->changed = REQUEST_TIME;
  1899. $comment->in_preview = TRUE;
  1900. $comment_build = comment_view($comment, $node);
  1901. $comment_build['#weight'] = -100;
  1902. $form['comment_preview'] = $comment_build;
  1903. }
  1904. if ($comment->pid) {
  1905. $build = array();
  1906. if ($comments = comment_load_multiple(array($comment->pid), array('status' => COMMENT_PUBLISHED))) {
  1907. $parent_comment = $comments[$comment->pid];
  1908. $build = comment_view($parent_comment, $node);
  1909. }
  1910. }
  1911. else {
  1912. $build = node_view($node);
  1913. }
  1914. $form['comment_output_below'] = $build;
  1915. $form['comment_output_below']['#weight'] = 100;
  1916. return $form;
  1917. }
  1918. /**
  1919. * Validate comment form submissions.
  1920. */
  1921. function comment_form_validate($form, &$form_state) {
  1922. global $user;
  1923. entity_form_field_validate('comment', $form, $form_state);
  1924. if (!empty($form_state['values']['cid'])) {
  1925. // Verify the name in case it is being changed from being anonymous.
  1926. $account = user_load_by_name($form_state['values']['name']);
  1927. $form_state['values']['uid'] = $account ? $account->uid : 0;
  1928. if ($form_state['values']['date'] && strtotime($form_state['values']['date']) === FALSE) {
  1929. form_set_error('date', t('You have to specify a valid date.'));
  1930. }
  1931. if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) {
  1932. form_set_error('name', t('You have to specify a valid author.'));
  1933. }
  1934. }
  1935. elseif ($form_state['values']['is_anonymous']) {
  1936. // Validate anonymous comment author fields (if given). If the (original)
  1937. // author of this comment was an anonymous user, verify that no registered
  1938. // user with this name exists.
  1939. if ($form_state['values']['name']) {
  1940. $query = db_select('users', 'u');
  1941. $query->addField('u', 'uid', 'uid');
  1942. $taken = $query
  1943. ->condition('name', db_like($form_state['values']['name']), 'LIKE')
  1944. ->countQuery()
  1945. ->execute()
  1946. ->fetchField();
  1947. if ($taken) {
  1948. form_set_error('name', t('The name you used belongs to a registered user.'));
  1949. }
  1950. }
  1951. }
  1952. if ($form_state['values']['mail'] && !valid_email_address($form_state['values']['mail'])) {
  1953. form_set_error('mail', t('The e-mail address you specified is not valid.'));
  1954. }
  1955. if ($form_state['values']['homepage'] && !valid_url($form_state['values']['homepage'], TRUE)) {
  1956. 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>.'));
  1957. }
  1958. }
  1959. /**
  1960. * Prepare a comment for submission.
  1961. */
  1962. function comment_submit($comment) {
  1963. // @todo Legacy support. Remove in Drupal 8.
  1964. if (is_array($comment)) {
  1965. $comment += array('subject' => '');
  1966. $comment = (object) $comment;
  1967. }
  1968. if (empty($comment->date)) {
  1969. $comment->date = 'now';
  1970. }
  1971. $comment->created = strtotime($comment->date);
  1972. $comment->changed = REQUEST_TIME;
  1973. // If the comment was posted by a registered user, assign the author's ID.
  1974. // @todo Too fragile. Should be prepared and stored in comment_form() already.
  1975. if (!$comment->is_anonymous && !empty($comment->name) && ($account = user_load_by_name($comment->name))) {
  1976. $comment->uid = $account->uid;
  1977. }
  1978. // If the comment was posted by an anonymous user and no author name was
  1979. // required, use "Anonymous" by default.
  1980. if ($comment->is_anonymous && (!isset($comment->name) || $comment->name === '')) {
  1981. $comment->name = variable_get('anonymous', t('Anonymous'));
  1982. }
  1983. // Validate the comment's subject. If not specified, extract from comment body.
  1984. if (trim($comment->subject) == '') {
  1985. // The body may be in any format, so:
  1986. // 1) Filter it into HTML
  1987. // 2) Strip out all HTML tags
  1988. // 3) Convert entities back to plain-text.
  1989. $comment_body = $comment->comment_body[LANGUAGE_NONE][0];
  1990. if (isset($comment_body['format'])) {
  1991. $comment_text = check_markup($comment_body['value'], $comment_body['format']);
  1992. }
  1993. else {
  1994. $comment_text = check_plain($comment_body['value']);
  1995. }
  1996. $comment->subject = truncate_utf8(trim(decode_entities(strip_tags($comment_text))), 29, TRUE);
  1997. // Edge cases where the comment body is populated only by HTML tags will
  1998. // require a default subject.
  1999. if ($comment->subject == '') {
  2000. $comment->subject = t('(No subject)');
  2001. }
  2002. }
  2003. return $comment;
  2004. }
  2005. /**
  2006. * Updates the form state's comment entity by processing this submission's values.
  2007. *
  2008. * This is the default builder function for the comment form. It is called
  2009. * during the "Save" and "Preview" submit handlers to retrieve the entity to
  2010. * save or preview. This function can also be called by a "Next" button of a
  2011. * wizard to update the form state's entity with the current step's values
  2012. * before proceeding to the next step.
  2013. *
  2014. * @see comment_form()
  2015. */
  2016. function comment_form_submit_build_comment($form, &$form_state) {
  2017. $comment = $form_state['comment'];
  2018. entity_form_submit_build_entity('comment', $comment, $form, $form_state);
  2019. comment_submit($comment);
  2020. return $comment;
  2021. }
  2022. /**
  2023. * Process comment form submissions; prepare the comment, store it, and set a redirection target.
  2024. */
  2025. function comment_form_submit($form, &$form_state) {
  2026. $node = node_load($form_state['values']['nid']);
  2027. $comment = comment_form_submit_build_comment($form, $form_state);
  2028. if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
  2029. // Save the anonymous user information to a cookie for reuse.
  2030. if (user_is_anonymous()) {
  2031. user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
  2032. }
  2033. comment_save($comment);
  2034. $form_state['values']['cid'] = $comment->cid;
  2035. // Add an entry to the watchdog log.
  2036. watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)));
  2037. // Explain the approval queue if necessary.
  2038. if ($comment->status == COMMENT_NOT_PUBLISHED) {
  2039. if (!user_access('administer comments')) {
  2040. drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
  2041. }
  2042. }
  2043. else {
  2044. drupal_set_message(t('Your comment has been posted.'));
  2045. }
  2046. $query = array();
  2047. // Find the current display page for this comment.
  2048. $page = comment_get_display_page($comment->cid, $node->type);
  2049. if ($page > 0) {
  2050. $query['page'] = $page;
  2051. }
  2052. // Redirect to the newly posted comment.
  2053. $redirect = array('node/' . $node->nid, array('query' => $query, 'fragment' => 'comment-' . $comment->cid));
  2054. }
  2055. else {
  2056. watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject), WATCHDOG_WARNING);
  2057. drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject)), 'error');
  2058. // Redirect the user to the node they are commenting on.
  2059. $redirect = 'node/' . $node->nid;
  2060. }
  2061. $form_state['redirect'] = $redirect;
  2062. // Clear the block and page caches so that anonymous users see the comment
  2063. // they have posted.
  2064. cache_clear_all();
  2065. }
  2066. /**
  2067. * Process variables for comment.tpl.php.
  2068. *
  2069. * @see comment.tpl.php
  2070. */
  2071. function template_preprocess_comment(&$variables) {
  2072. $comment = $variables['elements']['#comment'];
  2073. $node = $variables['elements']['#node'];
  2074. $variables['comment'] = $comment;
  2075. $variables['node'] = $node;
  2076. $variables['author'] = theme('username', array('account' => $comment));
  2077. $variables['created'] = format_date($comment->created);
  2078. $variables['changed'] = format_date($comment->changed);
  2079. $variables['new'] = !empty($comment->new) ? t('new') : '';
  2080. $variables['picture'] = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $comment)) : '';
  2081. $variables['signature'] = $comment->signature;
  2082. $uri = entity_uri('comment', $comment);
  2083. $uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  2084. $variables['title'] = l($comment->subject, $uri['path'], $uri['options']);
  2085. $variables['permalink'] = l(t('Permalink'), $uri['path'], $uri['options']);
  2086. $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['author'], '!datetime' => $variables['created']));
  2087. // Preprocess fields.
  2088. field_attach_preprocess('comment', $comment, $variables['elements'], $variables);
  2089. // Helpful $content variable for templates.
  2090. foreach (element_children($variables['elements']) as $key) {
  2091. $variables['content'][$key] = $variables['elements'][$key];
  2092. }
  2093. // Set status to a string representation of comment->status.
  2094. if (isset($comment->in_preview)) {
  2095. $variables['status'] = 'comment-preview';
  2096. }
  2097. else {
  2098. $variables['status'] = ($comment->status == COMMENT_NOT_PUBLISHED) ? 'comment-unpublished' : 'comment-published';
  2099. }
  2100. // Gather comment classes.
  2101. // 'comment-published' class is not needed, it is either 'comment-preview' or
  2102. // 'comment-unpublished'.
  2103. if ($variables['status'] != 'comment-published') {
  2104. $variables['classes_array'][] = $variables['status'];
  2105. }
  2106. if ($variables['new']) {
  2107. $variables['classes_array'][] = 'comment-new';
  2108. }
  2109. if (!$comment->uid) {
  2110. $variables['classes_array'][] = 'comment-by-anonymous';
  2111. }
  2112. else {
  2113. if ($comment->uid == $variables['node']->uid) {
  2114. $variables['classes_array'][] = 'comment-by-node-author';
  2115. }
  2116. if ($comment->uid == $variables['user']->uid) {
  2117. $variables['classes_array'][] = 'comment-by-viewer';
  2118. }
  2119. }
  2120. }
  2121. /**
  2122. * Returns HTML for a "you can't post comments" notice.
  2123. *
  2124. * @param $variables
  2125. * An associative array containing:
  2126. * - node: The comment node.
  2127. *
  2128. * @ingroup themeable
  2129. */
  2130. function theme_comment_post_forbidden($variables) {
  2131. $node = $variables['node'];
  2132. global $user;
  2133. // Since this is expensive to compute, we cache it so that a page with many
  2134. // comments only has to query the database once for all the links.
  2135. $authenticated_post_comments = &drupal_static(__FUNCTION__, NULL);
  2136. if (!$user->uid) {
  2137. if (!isset($authenticated_post_comments)) {
  2138. // We only output a link if we are certain that users will get permission
  2139. // to post comments by logging in.
  2140. $comment_roles = user_roles(TRUE, 'post comments');
  2141. $authenticated_post_comments = isset($comment_roles[DRUPAL_AUTHENTICATED_RID]);
  2142. }
  2143. if ($authenticated_post_comments) {
  2144. // We cannot use drupal_get_destination() because these links
  2145. // sometimes appear on /node and taxonomy listing pages.
  2146. if (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW) == COMMENT_FORM_SEPARATE_PAGE) {
  2147. $destination = array('destination' => "comment/reply/$node->nid#comment-form");
  2148. }
  2149. else {
  2150. $destination = array('destination' => "node/$node->nid#comment-form");
  2151. }
  2152. if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
  2153. // Users can register themselves.
  2154. 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))));
  2155. }
  2156. else {
  2157. // Only admins can add new users, no public registration.
  2158. return t('<a href="@login">Log in</a> to post comments', array('@login' => url('user/login', array('query' => $destination))));
  2159. }
  2160. }
  2161. }
  2162. }
  2163. /**
  2164. * Process variables for comment-wrapper.tpl.php.
  2165. *
  2166. * @see comment-wrapper.tpl.php
  2167. * @see theme_comment_wrapper()
  2168. */
  2169. function template_preprocess_comment_wrapper(&$variables) {
  2170. // Provide contextual information.
  2171. $variables['node'] = $variables['content']['#node'];
  2172. $variables['display_mode'] = variable_get('comment_default_mode_' . $variables['node']->type, COMMENT_MODE_THREADED);
  2173. // The comment form is optional and may not exist.
  2174. $variables['content'] += array('comment_form' => array());
  2175. }
  2176. /**
  2177. * Return an array of viewing modes for comment listings.
  2178. *
  2179. * We can't use a global variable array because the locale system
  2180. * is not initialized yet when the comment module is loaded.
  2181. */
  2182. function _comment_get_modes() {
  2183. return array(
  2184. COMMENT_MODE_FLAT => t('Flat list'),
  2185. COMMENT_MODE_THREADED => t('Threaded list')
  2186. );
  2187. }
  2188. /**
  2189. * Return an array of "comments per page" settings from which the user
  2190. * can choose.
  2191. */
  2192. function _comment_per_page() {
  2193. return drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300));
  2194. }
  2195. /**
  2196. * Updates the comment statistics for a given node. This should be called any
  2197. * time a comment is added, deleted, or updated.
  2198. *
  2199. * The following fields are contained in the node_comment_statistics table.
  2200. * - last_comment_timestamp: the timestamp of the last comment for this node or the node create stamp if no comments exist for the node.
  2201. * - last_comment_name: the name of the anonymous poster for the last comment
  2202. * - 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.
  2203. * - comment_count: the total number of approved/published comments on this node.
  2204. */
  2205. function _comment_update_node_statistics($nid) {
  2206. // Allow bulk updates and inserts to temporarily disable the
  2207. // maintenance of the {node_comment_statistics} table.
  2208. if (!variable_get('comment_maintain_node_statistics', TRUE)) {
  2209. return;
  2210. }
  2211. $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE nid = :nid AND status = :status', array(
  2212. ':nid' => $nid,
  2213. ':status' => COMMENT_PUBLISHED,
  2214. ))->fetchField();
  2215. if ($count > 0) {
  2216. // Comments exist.
  2217. $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(
  2218. ':nid' => $nid,
  2219. ':status' => COMMENT_PUBLISHED,
  2220. ))->fetchObject();
  2221. db_update('node_comment_statistics')
  2222. ->fields(array(
  2223. 'cid' => $last_reply->cid,
  2224. 'comment_count' => $count,
  2225. 'last_comment_timestamp' => $last_reply->changed,
  2226. 'last_comment_name' => $last_reply->uid ? '' : $last_reply->name,
  2227. 'last_comment_uid' => $last_reply->uid,
  2228. ))
  2229. ->condition('nid', $nid)
  2230. ->execute();
  2231. }
  2232. else {
  2233. // Comments do not exist.
  2234. $node = db_query('SELECT uid, created FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();
  2235. db_update('node_comment_statistics')
  2236. ->fields(array(
  2237. 'cid' => 0,
  2238. 'comment_count' => 0,
  2239. 'last_comment_timestamp' => $node->created,
  2240. 'last_comment_name' => '',
  2241. 'last_comment_uid' => $node->uid,
  2242. ))
  2243. ->condition('nid', $nid)
  2244. ->execute();
  2245. }
  2246. }
  2247. /**
  2248. * Generate vancode.
  2249. *
  2250. * Consists of a leading character indicating length, followed by N digits
  2251. * with a numerical value in base 36. Vancodes can be sorted as strings
  2252. * without messing up numerical order.
  2253. *
  2254. * It goes:
  2255. * 00, 01, 02, ..., 0y, 0z,
  2256. * 110, 111, ... , 1zy, 1zz,
  2257. * 2100, 2101, ..., 2zzy, 2zzz,
  2258. * 31000, 31001, ...
  2259. */
  2260. function int2vancode($i = 0) {
  2261. $num = base_convert((int) $i, 10, 36);
  2262. $length = strlen($num);
  2263. return chr($length + ord('0') - 1) . $num;
  2264. }
  2265. /**
  2266. * Decode vancode back to an integer.
  2267. */
  2268. function vancode2int($c = '00') {
  2269. return base_convert(substr($c, 1), 36, 10);
  2270. }
  2271. /**
  2272. * Implements hook_action_info().
  2273. */
  2274. function comment_action_info() {
  2275. return array(
  2276. 'comment_publish_action' => array(
  2277. 'label' => t('Publish comment'),
  2278. 'type' => 'comment',
  2279. 'configurable' => FALSE,
  2280. 'behavior' => array('changes_property'),
  2281. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  2282. ),
  2283. 'comment_unpublish_action' => array(
  2284. 'label' => t('Unpublish comment'),
  2285. 'type' => 'comment',
  2286. 'configurable' => FALSE,
  2287. 'behavior' => array('changes_property'),
  2288. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  2289. ),
  2290. 'comment_unpublish_by_keyword_action' => array(
  2291. 'label' => t('Unpublish comment containing keyword(s)'),
  2292. 'type' => 'comment',
  2293. 'configurable' => TRUE,
  2294. 'behavior' => array('changes_property'),
  2295. 'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
  2296. ),
  2297. 'comment_save_action' => array(
  2298. 'label' => t('Save comment'),
  2299. 'type' => 'comment',
  2300. 'configurable' => FALSE,
  2301. 'triggers' => array('comment_insert', 'comment_update'),
  2302. ),
  2303. );
  2304. }
  2305. /**
  2306. * Publishes a comment.
  2307. *
  2308. * @param $comment
  2309. * An optional comment object.
  2310. * @param array $context
  2311. * Array with components:
  2312. * - 'cid': Comment ID. Required if $comment is not given.
  2313. *
  2314. * @ingroup actions
  2315. */
  2316. function comment_publish_action($comment, $context = array()) {
  2317. if (isset($comment->subject)) {
  2318. $subject = $comment->subject;
  2319. $comment->status = COMMENT_PUBLISHED;
  2320. }
  2321. else {
  2322. $cid = $context['cid'];
  2323. $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(':cid' => $cid))->fetchField();
  2324. db_update('comment')
  2325. ->fields(array('status' => COMMENT_PUBLISHED))
  2326. ->condition('cid', $cid)
  2327. ->execute();
  2328. }
  2329. watchdog('action', 'Published comment %subject.', array('%subject' => $subject));
  2330. }
  2331. /**
  2332. * Unpublishes a comment.
  2333. *
  2334. * @param $comment
  2335. * An optional comment object.
  2336. * @param array $context
  2337. * Array with components:
  2338. * - 'cid': Comment ID. Required if $comment is not given.
  2339. *
  2340. * @ingroup actions
  2341. */
  2342. function comment_unpublish_action($comment, $context = array()) {
  2343. if (isset($comment->subject)) {
  2344. $subject = $comment->subject;
  2345. $comment->status = COMMENT_NOT_PUBLISHED;
  2346. }
  2347. else {
  2348. $cid = $context['cid'];
  2349. $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(':cid' => $cid))->fetchField();
  2350. db_update('comment')
  2351. ->fields(array('status' => COMMENT_NOT_PUBLISHED))
  2352. ->condition('cid', $cid)
  2353. ->execute();
  2354. }
  2355. watchdog('action', 'Unpublished comment %subject.', array('%subject' => $subject));
  2356. }
  2357. /**
  2358. * Unpublishes a comment if it contains certain keywords.
  2359. *
  2360. * @param $comment
  2361. * Comment object to modify.
  2362. * @param array $context
  2363. * Array with components:
  2364. * - 'keywords': Keywords to look for. If the comment contains at least one
  2365. * of the keywords, it is unpublished.
  2366. *
  2367. * @ingroup actions
  2368. * @see comment_unpublish_by_keyword_action_form()
  2369. * @see comment_unpublish_by_keyword_action_submit()
  2370. */
  2371. function comment_unpublish_by_keyword_action($comment, $context) {
  2372. foreach ($context['keywords'] as $keyword) {
  2373. $text = drupal_render($comment);
  2374. if (strpos($text, $keyword) !== FALSE) {
  2375. $comment->status = COMMENT_NOT_PUBLISHED;
  2376. watchdog('action', 'Unpublished comment %subject.', array('%subject' => $comment->subject));
  2377. break;
  2378. }
  2379. }
  2380. }
  2381. /**
  2382. * Form builder; Prepare a form for blacklisted keywords.
  2383. *
  2384. * @ingroup forms
  2385. * @see comment_unpublish_by_keyword_action()
  2386. * @see comment_unpublish_by_keyword_action_submit()
  2387. */
  2388. function comment_unpublish_by_keyword_action_form($context) {
  2389. $form['keywords'] = array(
  2390. '#title' => t('Keywords'),
  2391. '#type' => 'textarea',
  2392. '#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."'),
  2393. '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  2394. );
  2395. return $form;
  2396. }
  2397. /**
  2398. * Process comment_unpublish_by_keyword_action_form form submissions.
  2399. *
  2400. * @see comment_unpublish_by_keyword_action()
  2401. */
  2402. function comment_unpublish_by_keyword_action_submit($form, $form_state) {
  2403. return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
  2404. }
  2405. /**
  2406. * Saves a comment.
  2407. *
  2408. * @ingroup actions
  2409. */
  2410. function comment_save_action($comment) {
  2411. comment_save($comment);
  2412. cache_clear_all();
  2413. watchdog('action', 'Saved comment %title', array('%title' => $comment->subject));
  2414. }
  2415. /**
  2416. * Implements hook_ranking().
  2417. */
  2418. function comment_ranking() {
  2419. return array(
  2420. 'comments' => array(
  2421. 'title' => t('Number of comments'),
  2422. 'join' => array(
  2423. 'type' => 'LEFT',
  2424. 'table' => 'node_comment_statistics',
  2425. 'alias' => 'node_comment_statistics',
  2426. 'on' => 'node_comment_statistics.nid = i.sid',
  2427. ),
  2428. // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
  2429. 'score' => '2.0 - 2.0 / (1.0 + node_comment_statistics.comment_count * CAST(:scale AS DECIMAL))',
  2430. 'arguments' => array(':scale' => variable_get('node_cron_comments_scale', 0)),
  2431. ),
  2432. );
  2433. }
  2434. /**
  2435. * Implements hook_rdf_mapping().
  2436. */
  2437. function comment_rdf_mapping() {
  2438. return array(
  2439. array(
  2440. 'type' => 'comment',
  2441. 'bundle' => RDF_DEFAULT_BUNDLE,
  2442. 'mapping' => array(
  2443. 'rdftype' => array('sioc:Post', 'sioct:Comment'),
  2444. 'title' => array(
  2445. 'predicates' => array('dc:title'),
  2446. ),
  2447. 'created' => array(
  2448. 'predicates' => array('dc:date', 'dc:created'),
  2449. 'datatype' => 'xsd:dateTime',
  2450. 'callback' => 'date_iso8601',
  2451. ),
  2452. 'changed' => array(
  2453. 'predicates' => array('dc:modified'),
  2454. 'datatype' => 'xsd:dateTime',
  2455. 'callback' => 'date_iso8601',
  2456. ),
  2457. 'comment_body' => array(
  2458. 'predicates' => array('content:encoded'),
  2459. ),
  2460. 'pid' => array(
  2461. 'predicates' => array('sioc:reply_of'),
  2462. 'type' => 'rel',
  2463. ),
  2464. 'uid' => array(
  2465. 'predicates' => array('sioc:has_creator'),
  2466. 'type' => 'rel',
  2467. ),
  2468. 'name' => array(
  2469. 'predicates' => array('foaf:name'),
  2470. ),
  2471. ),
  2472. ),
  2473. );
  2474. }
  2475. /**
  2476. * Implements hook_file_download_access().
  2477. */
  2478. function comment_file_download_access($field, $entity_type, $entity) {
  2479. if ($entity_type == 'comment') {
  2480. if (user_access('access comments') && $entity->status == COMMENT_PUBLISHED || user_access('administer comments')) {
  2481. $node = node_load($entity->nid);
  2482. return node_access('view', $node);
  2483. }
  2484. return FALSE;
  2485. }
  2486. }