comment.module 91 KB

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