devel_node_access.module 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. <?php
  2. /**
  3. * @file
  4. * Functions for debugging node access permissions.
  5. *
  6. * This module gives developers feedback as to what their node_access table
  7. * contains, and which nodes are protected or visible to the public.
  8. *
  9. */
  10. define('DNA_ACCESS_VIEW', 'view devel_node_access information');
  11. /**
  12. * Implements hook_permission().
  13. */
  14. function devel_node_access_permission() {
  15. return array(
  16. 'view devel_node_access information' => array(
  17. 'description' => t('View the node access information blocks on node pages and the summary page.'),
  18. 'title' => t('Access DNA information'),
  19. 'restrict access' => TRUE,
  20. ),
  21. );
  22. }
  23. /**
  24. * Implements hook_help().
  25. */
  26. function devel_node_access_help($path, $arg) {
  27. switch ($path) {
  28. case 'admin/settings/modules#description':
  29. return t('Development helper for node_access table');
  30. break;
  31. case 'admin/help#devel_node_access':
  32. $output = '<p>' . t('This module helps in site development. Specifically, when an access control module is used to limit access to some or all nodes, this module provides some feedback showing the node_access table in the database.') . "</p>\n";
  33. $output .= '<p>' . t('The node_access table is one method Drupal provides to hide content from some users while displaying it to others. By default, Drupal shows all nodes to all users. There are a number of optional modules which may be installed to hide content from some users.') . "</p>\n";
  34. $output .= '<p>' . t('If you have not installed any of these modules, you really have no need for the devel_node_access module. This module is intended for use during development, so that developers and admins can confirm that the node_access table is working as expected. You probably do not want this module enabled on a production site.') . "</p>\n";
  35. $output .= '<p>' . t('This module provides two blocks. One called Devel Node Access by User is visible when a single node is shown on a page. This block shows which users can view, update or delete the node shown. Note that this block uses an inefficient algorithm to produce its output. You should only enable this block on sites with very few user accounts.') . "</p>\n";
  36. $output .= '<p>' . t('The second block provided by this module shows the entries in the node_access table for any nodes shown on the current page. You can enable the debug mode on the <a href="@settings_page">settings page</a> to display much more information, but this can cause considerable overhead. Because the tables shown are wide, it is recommended to enable the blocks in the page footer rather than a sidebar.',
  37. array('@settings_page' => url('admin/config/development/devel', array('fragment' => 'edit-devel-node-access')))
  38. ) . "</p>\n";
  39. $output .= '<p>' . t('This module also provides a <a href="@summary_page">summary page</a> which shows general information about your node_access table. If you have installed the Views module, you may browse node_access by realm.',
  40. array('@summary_page' => url('devel/node_access/summary'))
  41. ) . "</p>\n";
  42. return $output;
  43. }
  44. }
  45. /**
  46. * Implements hook_menu().
  47. */
  48. function devel_node_access_menu() {
  49. $items = array();
  50. if (!module_exists('devel')) {
  51. if (!menu_load('devel')) {
  52. // We have to create the 'devel' menu ourselves.
  53. $menu = array(
  54. 'menu_name' => 'devel',
  55. 'title' => 'Development',
  56. 'description' => 'Development link',
  57. );
  58. menu_save($menu);
  59. }
  60. // We have to create the 'Devel settings' menu item ourselves.
  61. $items['admin/config/development/devel'] = array(
  62. 'title' => 'Devel settings',
  63. 'description' => 'Helper pages and blocks to assist Drupal developers and admins with node_access. The devel blocks can be managed via the <a href="/admin/structure/block">block administration</a> page.',
  64. 'page callback' => 'drupal_get_form',
  65. 'page arguments' => array('devel_node_access_admin_settings'),
  66. 'access arguments' => array('administer site configuration'),
  67. );
  68. $items['devel/settings'] = $items['admin/config/development/devel'] + array(
  69. 'menu_name' => 'devel',
  70. );
  71. }
  72. // Create a callback for use by devel_node_access_user_ajax().
  73. $items['devel/node_access/by_user/%/%'] = array(
  74. 'page callback' => 'devel_node_access_user_ajax',
  75. 'page arguments' => array(3, 4),
  76. 'access arguments' => array(DNA_ACCESS_VIEW),
  77. 'type' => MENU_CALLBACK,
  78. );
  79. // Add this to the custom menu 'devel' created by the devel module.
  80. $items['devel/node_access/summary'] = array(
  81. 'title' => 'Node_access summary',
  82. 'page callback' => 'dna_summary',
  83. 'access arguments' => array(DNA_ACCESS_VIEW),
  84. 'menu_name' => 'devel',
  85. );
  86. return $items;
  87. }
  88. /**
  89. * Form constructor for Devel node access settings.
  90. *
  91. * @see devel_node_access_form_alter()
  92. *
  93. * @ingroup forms
  94. */
  95. function devel_node_access_admin_settings() {
  96. $form = array();
  97. return system_settings_form($form);
  98. }
  99. /**
  100. * Implements hook_form_alter().
  101. *
  102. * Adds form elements to devel_admin_settings() and
  103. * devel_node_access_admin_settings().
  104. */
  105. function devel_node_access_form_alter(&$form, $form_state, $form_id) {
  106. $tr = 't';
  107. if ($form_id == 'devel_admin_settings' || $form_id == 'devel_node_access_admin_settings') {
  108. $form['devel_node_access'] = array(
  109. '#type' => 'fieldset',
  110. '#title' => t('Devel Node Access'),
  111. '#collapsible' => TRUE,
  112. );
  113. $form['devel_node_access']['devel_node_access_debug_mode'] = array(
  114. '#type' => 'checkbox',
  115. '#title' => t('Debug mode'),
  116. '#default_value' => variable_get('devel_node_access_debug_mode', FALSE),
  117. '#description' => t('Debug mode verifies the grant records in the node_access table against those that would be set by running !Rebuild_permissions, and displays them all; this can cause considerable overhead.<br />For even more information enable the <a href="@link">%DNAbU block</a>, too.', array(
  118. '!Rebuild_permissions' => l('[' . $tr('Rebuild permissions') . ']', 'admin/reports/status/rebuild'),
  119. '%DNAbU' => t('Devel Node Access by User'),
  120. '@link' => url('admin/structure/block/list'),
  121. )),
  122. );
  123. $form['devel_node_access']['devel_node_access_user_ajax'] = array(
  124. '#type' => 'checkbox',
  125. '#title' => t('Asynchronously populate the <em>Devel Node Access by User</em> block'),
  126. '#default_value' => variable_get('devel_node_access_user_ajax', FALSE),
  127. '#description' => t("Use Ajax to populate the second DNA block. This loads the initial page faster and uses dynamic calls to build the data in the table, one request at a time. It's especially useful during development, if some of the calls are failing.") . '<br />' . t('JavaScript must be enabled in your browser.'),
  128. );
  129. // push the Save button down
  130. $form['actions']['#weight'] = 10;
  131. }
  132. }
  133. /**
  134. * Page callback for the Devel node access summary.
  135. */
  136. function dna_summary() {
  137. // warn user if they have any entries that could grant access to all nodes
  138. $output = '';
  139. $result = db_query('SELECT DISTINCT realm FROM {node_access} WHERE nid = 0 AND gid = 0');
  140. $rows = array();
  141. foreach ($result as $row) {
  142. $rows[] = array($row->realm);
  143. }
  144. if (!empty($rows)) {
  145. $output .= '<h3>' . t('Access Granted to All Nodes (All Users)') . "</h3>\n";
  146. $output .= '<p>' . t('Your node_access table contains entries that may be granting all users access to all nodes. Depending on which access control module(s) you use, you may want to delete these entries. If you are not using an access control module, you should probably leave these entries as is.') . "</p>\n";
  147. $headers = array(t('realm'));
  148. $output .= theme('table', array('header' => $headers, 'rows' => $rows));
  149. $access_granted_to_all_nodes = TRUE;
  150. }
  151. // how many nodes are not represented in the node_access table
  152. $num = db_query('SELECT COUNT(n.nid) AS num_nodes FROM {node} n LEFT JOIN {node_access} na ON n.nid = na.nid WHERE na.nid IS NULL')->fetchField();
  153. if ($num) {
  154. $output .= '<h3>' . t('Legacy Nodes') . "</h3>\n";
  155. $output .= '<p>' .
  156. t('You have !num nodes in your node table which are not represented in your node_access table. If you have an access control module installed, these nodes may be hidden from all users. This could be caused by publishing nodes before enabling the access control module. If this is the case, manually updating each node should add it to the node_access table and fix the problem.', array('!num' => l($num, 'devel/node_access/view/NULL')))
  157. . "</p>\n";
  158. if (!empty($access_granted_to_all_nodes)) {
  159. $output .= '<p>' .
  160. t('This issue may be masked by the one above, so look into the former first.')
  161. . "</p>\n";
  162. }
  163. }
  164. else {
  165. $output .= '<h3>' . t('All Nodes Represented') . "</h3>\n";
  166. $output .= '<p>' . t('All nodes are represented in the node_access table.') . "</p>\n";
  167. }
  168. // a similar warning to the one above, but slightly more specific
  169. $result = db_query('SELECT DISTINCT realm FROM {node_access} WHERE nid = 0 AND gid <> 0');
  170. $rows = array();
  171. foreach ($result as $row) {
  172. $rows[] = array($row->realm);
  173. }
  174. if (!empty($rows)) {
  175. $output .= '<h3>' . t('Access Granted to All Nodes (Some Users)') . "</h3>\n";
  176. $output .= '<p>' . t('Your node_access table contains entries that may be granting some users access to all nodes. This may be perfectly normal, depending on which access control module(s) you use.') . "</p>\n";
  177. $headers = array(t('realm'));
  178. $output .= theme('table', array('header' => $headers, 'rows' => $rows));
  179. }
  180. // find specific nodes which may be visible to all users
  181. $result = db_query('SELECT DISTINCT realm, COUNT(DISTINCT nid) as node_count FROM {node_access} WHERE gid = 0 AND nid > 0 GROUP BY realm');
  182. $rows = array();
  183. foreach ($result as $row) {
  184. $rows[] = array(
  185. $row->realm,
  186. array(
  187. 'data' => $row->node_count,
  188. 'align' => 'center',
  189. ),
  190. );
  191. }
  192. if (!empty($rows)) {
  193. $output .= '<h3>' . t('Access Granted to Some Nodes') . "</h3>\n";
  194. $output .= '<p>' .
  195. t('The following realms appear to grant all users access to some specific nodes. This may be perfectly normal, if some of your content is available to the public.')
  196. . "</p>\n";
  197. $headers = array(t('realm'), t('public nodes'));
  198. $output .= theme('table', array('header' => $headers, 'rows' => $rows, 'caption' => t('Public Nodes')));
  199. }
  200. // find specific nodes protected by node_access table
  201. $result = db_query('SELECT DISTINCT realm, COUNT(DISTINCT nid) as node_count FROM {node_access} WHERE gid <> 0 AND nid > 0 GROUP BY realm');
  202. $rows = array();
  203. foreach ($result as $row) {
  204. // no Views yet:
  205. //$rows[] = array(l($row->realm, "devel/node_access/view/$row->realm"),
  206. $rows[] = array(
  207. $row->realm,
  208. array(
  209. 'data' => $row->node_count,
  210. 'align' => 'center',
  211. ),
  212. );
  213. }
  214. if (!empty($rows)) {
  215. $output .= '<h3>' . t('Summary by Realm') . "</h3>\n";
  216. $output .= '<p>' . t('The following realms grant limited access to some specific nodes.') . "</p>\n";
  217. $headers = array(t('realm'), t('private nodes'));
  218. $output .= theme('table', array('header' => $headers, 'rows' => $rows, 'caption' => t('Protected Nodes')));
  219. }
  220. return $output;
  221. }
  222. /**
  223. * Retreives the nodes visible in the current menu entry.
  224. *
  225. * @param integer $nid
  226. * (optional) A node ID to add to the list.
  227. *
  228. * @return array
  229. * An associative array of Node ID's that this function has been called with
  230. * keyed by Node ID.
  231. */
  232. function dna_visible_nodes($nid = NULL) {
  233. static $nids = array();
  234. if ($nid) {
  235. $nids[$nid] = $nid;
  236. }
  237. elseif (empty($nids)) {
  238. $menu_item = menu_get_item();
  239. $map = $menu_item['original_map'];
  240. if ($map[0] == 'node' && isset($map[1]) && is_numeric($map[1]) && !isset($map[2])) {
  241. // show DNA information on node/NID even if access is denied (IF the user has the 'view devel_node_access information' permission)!
  242. return array($map[1]);
  243. }
  244. }
  245. return $nids;
  246. }
  247. /**
  248. * Implements hook_node_view().
  249. */
  250. function devel_node_access_node_view($node, $build_mode) {
  251. // remember this node, for display in our block
  252. dna_visible_nodes($node->nid);
  253. }
  254. /**
  255. * Invokes a hook.
  256. *
  257. * @return
  258. * The results of the hook invocation keyed by the machine name of the
  259. * implementing module.
  260. */
  261. function _devel_node_access_module_invoke_all() { // array and scalar returns
  262. $args = func_get_args();
  263. $hook = $args[0];
  264. unset($args[0]);
  265. $return = array();
  266. foreach (module_implements($hook) as $module) {
  267. $function = $module . '_' . $hook;
  268. if (function_exists($function)) {
  269. $result = call_user_func_array($function, $args);
  270. if (isset($result)) {
  271. if (is_array($result)) {
  272. foreach ($result as $key => $value) {
  273. // Add name of module that returned the value.
  274. $result[$key]['#module'] = $module;
  275. }
  276. }
  277. else {
  278. // Build array with result keyed by $module.
  279. $result = array($module => $result);
  280. }
  281. $return = array_merge_recursive($return, $result);
  282. }
  283. }
  284. }
  285. return $return;
  286. }
  287. /**
  288. * Builds an associative array of grant records and their history.
  289. *
  290. * If there are duplicate records, display an error message.
  291. *
  292. * @param $grants
  293. * An indexed array of grant records, augmented by the '#module' key, as
  294. * created by _devel_node_access_module_invoke_all('node_access_records').
  295. *
  296. * @param $node
  297. * The node that the grant records belong to.
  298. *
  299. * @param $function
  300. * The name of the hook that produced the grants array, in case we need to
  301. * display an error message.
  302. *
  303. * @return
  304. * See _devel_node_access_nar_alter() for the description of the result.
  305. */
  306. function _devel_node_access_build_nar_data($grants, $node, $function) {
  307. $data = array();
  308. $duplicates = array();
  309. foreach ($grants as $grant) {
  310. if (empty($data[$grant['realm']][$grant['gid']])) {
  311. $data[$grant['realm']][$grant['gid']] = array('original' => $grant, 'current' => $grant, 'changes' => array());
  312. }
  313. else {
  314. if (empty($duplicates[$grant['realm']][$grant['gid']])) {
  315. $duplicates[$grant['realm']][$grant['gid']][] = $data[$grant['realm']][$grant['gid']]['original'];
  316. }
  317. $duplicates[$grant['realm']][$grant['gid']][] = $grant;
  318. }
  319. }
  320. if (!empty($duplicates)) {
  321. // generate an error message
  322. $msg = t('Devel Node Access has detected duplicate records returned from %function:', array('%function' => $function));
  323. $msg .= '<ul>';
  324. foreach ($duplicates as $realm => $data_by_realm) {
  325. foreach ($data_by_realm as $gid => $data_by_realm_gid) {
  326. $msg .= '<li><ul>';
  327. foreach ($data_by_realm_gid as $grant) {
  328. $msg .= "<li>$node->nid/$realm/$gid/" . ($grant['grant_view'] ? 1 : 0) . ($grant['grant_update'] ? 1 : 0) . ($grant['grant_delete'] ? 1 : 0) . ' by ' . $grant['#module'] . '</li>';
  329. }
  330. $msg .= '</ul></li>';
  331. }
  332. }
  333. $msg .= '</ul>';
  334. drupal_set_message($msg, 'error', FALSE);
  335. }
  336. return $data;
  337. }
  338. /**
  339. * Mimics hook_node_access_records_alter() and traces what each module does with it.
  340. *
  341. * @param object $grants
  342. * An indexed array of grant records, augmented by the '#module' key,
  343. * as created by _devel_node_access_module_invoke_all('node_access_records').
  344. * This array is updated by the hook_node_access_records_alter()
  345. * implementations.
  346. *
  347. * @param $node
  348. * The node that the grant records belong to.
  349. *
  350. * @return
  351. * A tree representation of the grant records in $grants including their
  352. * history:
  353. * $data[$realm][$gid]
  354. * ['original'] - grant record before processing
  355. * ['current'] - grant record after processing (if still present)
  356. * ['changes'][]['op'] - change message (add/change/delete by $module)
  357. * ['grant'] - grant record after change (unless deleted)
  358. */
  359. function _devel_node_access_nar_alter(&$grants, $node) {
  360. //dpm($grants, '_devel_node_access_nar_alter(): grants IN');
  361. $dummy = array();
  362. drupal_alter('node_access_records', $dummy, $node);
  363. static $drupal_static = array();
  364. isset($drupal_static['drupal_alter']) || ($drupal_static['drupal_alter'] = &drupal_static('drupal_alter'));
  365. $functions = $drupal_static['drupal_alter'];
  366. // Build the initial tree (and check for duplicates).
  367. $data = _devel_node_access_build_nar_data($grants, $node, 'hook_node_access_records()');
  368. // Simulate drupal_alter('node_access_records', $grants, $node);
  369. foreach ($functions['node_access_records'] as $function) {
  370. // Call hook_node_access_records_alter() for one module at a time and
  371. // analyze.
  372. $function($grants, $node); // <==
  373. $module = substr($function, 0, strlen($function) - 26);
  374. foreach ($grants as $i => $grant) {
  375. if (empty($data[$grant['realm']][$grant['gid']]['current'])) {
  376. // It's an added grant.
  377. $data[$grant['realm']][$grant['gid']]['current'] = $grant;
  378. $data[$grant['realm']][$grant['gid']]['current']['#module'] = $module;
  379. $data[$grant['realm']][$grant['gid']]['changes'][] = array(
  380. 'op' => 'added by ' . $module,
  381. 'grant' => $grant,
  382. );
  383. $grants[$i]['#module'] = $module;
  384. }
  385. else {
  386. // It's an existing grant, check for changes.
  387. $view = $update = $delete = FALSE;
  388. foreach (array('view', 'update', 'delete') as $op) {
  389. $$op = $grant["grant_$op"] - $data[$grant['realm']][$grant['gid']]['current']["grant_$op"];
  390. }
  391. $priority = $grant['priority'] - $data[$grant['realm']][$grant['gid']]['current']['priority'];
  392. if ($view || $update || $delete || $priority) {
  393. // It was changed.
  394. $data[$grant['realm']][$grant['gid']]['current'] = $grant;
  395. $data[$grant['realm']][$grant['gid']]['current']['#module'] = $module;
  396. $data[$grant['realm']][$grant['gid']]['changes'][] = array(
  397. 'op' => 'altered by ' . $module,
  398. 'grant' => $grant,
  399. );
  400. $grants[$i]['#module'] = $module;
  401. }
  402. }
  403. $data[$grant['realm']][$grant['gid']]['found'] = TRUE;
  404. }
  405. // Check for newly introduced duplicates.
  406. _devel_node_access_build_nar_data($grants, $node, 'hook_node_access_records_alter()');
  407. // Look for grant records that have disappeared.
  408. foreach ($data as $realm => $data2) {
  409. foreach ($data2 as $gid => $data3) {
  410. if (empty($data[$realm][$gid]['found']) && isset($data[$realm][$gid]['current'])) {
  411. unset($data[$realm][$gid]['current']);
  412. $data[$realm][$gid]['changes'][] = array('op' => 'removed by ' . $module);
  413. }
  414. else {
  415. unset($data[$realm][$gid]['found']);
  416. }
  417. }
  418. }
  419. }
  420. //dpm($data, '_devel_node_access_nar_alter() returns');
  421. //dpm($grants, '_devel_node_access_nar_alter(): grants OUT');
  422. return $data;
  423. }
  424. /**
  425. * Mimics hook_node_grants_alter() and traces what each module does with it.
  426. *
  427. * @param object $grants
  428. * An indexed array of grant records, augmented by the '#module' key, as
  429. * created by _devel_node_access_module_invoke_all('node_grants'). This array
  430. * is updated by the hook_node_grants_alter() implementations.
  431. *
  432. * @param $node
  433. * The node that the grant records belong to.
  434. *
  435. * @return
  436. * A tree representation of the grant records in $grants including their
  437. * history:
  438. * $data[$realm][$gid]
  439. * - ['cur']: TRUE or FALSE whether the gid is present or not
  440. * - ['ori'][]: An array of module names that contributed this grant (if
  441. * any)
  442. * - ['chg'][]: An array of changes, such as
  443. * - 'added' if module name is a prefix if the $realm,
  444. * - 'added by module' otherwise, or
  445. * - 'removed by module'
  446. */
  447. function _devel_node_access_ng_alter(&$grants, $account, $op) {
  448. //dpm($grants, '_devel_node_access_ng_alter(): grants IN');
  449. $dummy = array();
  450. drupal_alter('node_grants', $dummy, $account, $op);
  451. static $drupal_static = array();
  452. isset($drupal_static['drupal_alter']) || ($drupal_static['drupal_alter'] = &drupal_static('drupal_alter'));
  453. $functions = $drupal_static['drupal_alter'];
  454. // Build the initial structure.
  455. $data = array();
  456. foreach ($grants as $realm => $gids) {
  457. foreach ($gids as $i => $gid) {
  458. if ($i !== '#module') {
  459. $data[$realm][$gid]['cur'] = TRUE;
  460. $data[$realm][$gid]['ori'][] = $gids['#module'];
  461. }
  462. }
  463. unset($grants[$realm]['#module']);
  464. }
  465. // Simulate drupal_alter('node_grants', $grants, $account, $op);
  466. foreach ($functions['node_grants'] as $function) {
  467. // Call hook_node_grants_alter() for one module at a time and analyze.
  468. $function($grants, $account, $op); // <==
  469. $module = substr($function, 0, strlen($function) - 18);
  470. // Check for new gids.
  471. foreach ($grants as $realm => $gids) {
  472. foreach ($gids as $i => $gid) {
  473. if (empty($data[$realm][$gid]['cur'])) {
  474. $data[$realm][$gid]['cur'] = TRUE;
  475. $data[$realm][$gid]['chg'][] = 'added by ' . $module;
  476. }
  477. }
  478. }
  479. // Check for removed gids.
  480. foreach ($data as $realm => $gids) {
  481. foreach ($gids as $gid => $history) {
  482. if ($history['cur'] && array_search($gid, $grants[$realm]) === FALSE) {
  483. $data[$realm][$gid]['cur'] = FALSE;
  484. $data[$realm][$gid]['chg'][] = 'removed by ' . $module;
  485. }
  486. }
  487. }
  488. }
  489. //dpm($data, '_devel_node_access_ng_alter() returns');
  490. //dpm($grants, '_devel_node_access_ng_alter(): grants OUT');
  491. return $data;
  492. }
  493. /**
  494. * Implements hook_block_info().
  495. */
  496. function devel_node_access_block_info() {
  497. $blocks['dna_node'] = array(
  498. 'info' => t('Devel Node Access'),
  499. 'region' => 'footer',
  500. 'status' => 1,
  501. 'cache' => DRUPAL_NO_CACHE,
  502. );
  503. $blocks['dna_user'] = array(
  504. 'info' => t('Devel Node Access by User'),
  505. 'region' => 'footer',
  506. 'status' => 0,
  507. 'cache' => DRUPAL_NO_CACHE,
  508. );
  509. return $blocks;
  510. }
  511. /**
  512. * Implements hook_block_view().
  513. */
  514. function devel_node_access_block_view($delta) {
  515. global $user;
  516. global $theme_key;
  517. static $block1_visible, $hint = '';
  518. if (!isset($block1_visible)) {
  519. $block1_visible = db_query("SELECT status FROM {block} WHERE module = 'devel_node_access' AND delta = 'dna_user' AND theme = :theme", array(
  520. ':theme' => $theme_key,
  521. ))->fetchField();
  522. if (!$block1_visible) {
  523. $hint = t('For per-user access permissions enable the <a href="@link">%DNAbU block</a>.', array('@link' => url('admin/structure/block'), '%DNAbU' => t('Devel Node Access by User')));
  524. }
  525. }
  526. if (!user_access(DNA_ACCESS_VIEW)) {
  527. return;
  528. }
  529. $output = array();
  530. switch ($delta) {
  531. case 'dna_node':
  532. if (!count(dna_visible_nodes())) {
  533. return;
  534. }
  535. // include rows where nid == 0
  536. $nids = array_merge(array(0 => 0), dna_visible_nodes());
  537. $query = db_select('node_access', 'na');
  538. $query
  539. ->fields('na')
  540. ->condition('na.nid', $nids, 'IN')
  541. ->orderBy('na.nid')
  542. ->orderBy('na.realm')
  543. ->orderBy('na.gid');
  544. $nodes = node_load_multiple($nids);
  545. if (!variable_get('devel_node_access_debug_mode', FALSE)) {
  546. $headers = array(t('node'), t('realm'), t('gid'), t('view'), t('update'), t('delete'), t('explained'));
  547. $rows = array();
  548. foreach ($query->execute() as $row) {
  549. $explained = module_invoke_all('node_access_explain', $row);
  550. $rows[] = array(
  551. (empty($row->nid) ? '0' : '<a href="#node-' . $row->nid . '">' . _devel_node_access_get_node_title($nodes[$row->nid], TRUE) . '</a>'),
  552. $row->realm,
  553. $row->gid,
  554. $row->grant_view,
  555. $row->grant_update,
  556. $row->grant_delete,
  557. implode('<br />', $explained),
  558. );
  559. }
  560. $output[] = array(
  561. '#theme' => 'table',
  562. '#header' => $headers,
  563. '#rows' => $rows,
  564. '#attributes' => array('style' => 'text-align: left')
  565. );
  566. $hint = t('To see more details enable <a href="@debug_mode">debug mode</a>.', array('@debug_mode' => url('admin/config/development/devel', array('fragment' => 'edit-devel-node-access')))) . (empty($hint) ? '' : ' ' . $hint);
  567. }
  568. else {
  569. $tr = 't';
  570. $variables = array('!na' => '{node_access}');
  571. $states = array(
  572. 'default' => array(t('default'), 'ok', t('Default grant supplied by core in the absence of any other non-empty grants; in !na.', $variables)),
  573. 'ok' => array(t('ok'), 'ok', t('Highest priority grant; in !na.', $variables)),
  574. 'removed' => array(t('removed'), '', t('Was removed in @func; not in !na.', $variables + array('@func' => 'hook_node_access_records_alter()'))),
  575. 'static' => array(t('static'), 'ok', t('Non-standard grant in !na.', $variables)),
  576. 'unexpected' => array(t('unexpected'), 'warning', t('The 0/all/0/... grant applies to all nodes and all users -- usually it should not be present in !na if any node access module is active!')),
  577. 'ignored' => array(t('ignored'), 'warning', t('Lower priority grant; not in !na and thus ignored.', $variables)),
  578. 'empty' => array(t('empty'), 'warning', t('Does not grant any access, but could block lower priority grants; not in !na.', $variables)),
  579. 'wrong' => array(t('wrong'), 'error', t('Is rightfully in !na but at least one access flag is wrong!', $variables)),
  580. 'missing' => array(t('missing'), 'error', t("Should be in !na but isn't!", $variables)),
  581. 'removed!' => array(t('removed!'), 'error', t('Was removed in @func; should NOT be in !na!', $variables + array('@func' => 'hook_node_access_records_alter()'))),
  582. 'illegitimate' => array(t('illegitimate'), 'error', t('Should NOT be in !na because of lower priority!', $variables)),
  583. 'alien' => array(t('alien'), 'error', t('Should NOT be in !na because of unknown origin!', $variables)),
  584. );
  585. $active_states = array('default', 'ok', 'static', 'unexpected', 'wrong', 'illegitimate', 'alien');
  586. $headers = array(t('node'), t('prio'), t('status'), t('realm'), t('gid'), t('view'), t('update'), t('delete'), t('explained'));
  587. $headers = _devel_node_access_format_row($headers);
  588. $active_grants = array();
  589. foreach ($query->execute() as $active_grant) {
  590. $active_grants[$active_grant->nid][$active_grant->realm][$active_grant->gid] = $active_grant;
  591. }
  592. $all_grants = $checked_grants = $published_nid = array();
  593. foreach ($nids as $nid) {
  594. $acquired_grants_nid = array();
  595. if ($node = node_load($nid)) {
  596. // Check node_access_acquire_grants().
  597. $grants = _devel_node_access_module_invoke_all('node_access_records', $node);
  598. // Check drupal_alter('node_access_records').
  599. $data = _devel_node_access_nar_alter($grants, $node);
  600. /* (This was the D6 implementation that didn't analyze the hook_node_access_records_alter() details.)
  601. if (!empty($grants)) {
  602. $top_priority = NULL;
  603. foreach ($grants as $grant) {
  604. $priority = intval($grant['priority']);
  605. $top_priority = (isset($top_priority) ? max($top_priority, $priority) : $priority);
  606. $grant['priority'] = (isset($grant['priority']) ? $priority : '&ndash;&nbsp;');
  607. $acquired_grants_nid[$priority][$grant['realm']][$grant['gid']] = $grant + array(
  608. '#title' => _devel_node_access_get_node_title($node, TRUE),
  609. '#module' => (isset($grant['#module']) ? $grant['#module'] : ''),
  610. );
  611. }
  612. krsort($acquired_grants_nid);
  613. }
  614. /*/
  615. // (This is the new D7 implementation; it retains backward compatibility.)
  616. if (!empty($data)) {
  617. foreach ($data as $data_by_realm) {
  618. foreach ($data_by_realm as $data_by_realm_gid) { // by gid
  619. if (isset($data_by_realm_gid['current'])) {
  620. $grant = $data_by_realm_gid['current'];
  621. }
  622. elseif (isset($data_by_realm_gid['original'])) {
  623. $grant = $data_by_realm_gid['original'];
  624. $grant['#removed'] = 1;
  625. }
  626. else {
  627. continue;
  628. }
  629. $priority = intval($grant['priority']);
  630. $top_priority = (isset($top_priority) ? max($top_priority, $priority) : $priority);
  631. $grant['priority'] = (isset($grant['priority']) ? $priority : '&ndash;&nbsp;');
  632. $grant['history'] = $data_by_realm_gid;
  633. $acquired_grants_nid[$priority][$grant['realm']][$grant['gid']] = $grant + array(
  634. '#title' => _devel_node_access_get_node_title($node),
  635. '#module' => (isset($grant['#module']) ? $grant['#module'] : ''),
  636. );
  637. }
  638. }
  639. krsort($acquired_grants_nid);
  640. }
  641. /**/
  642. //dpm($acquired_grants_nid, "acquired_grants_nid =");
  643. // Check node_access_grants().
  644. $published_nid[$nid] = $node->status;
  645. if ($node->nid) {
  646. foreach (array('view', 'update', 'delete') as $op) {
  647. $grants = _devel_node_access_module_invoke_all('node_grants', $user, $op);
  648. // Call all hook_node_grants_alter() implementations.
  649. $ng_alter_datas[$op] = _devel_node_access_ng_alter($grants, $user, $op);
  650. $checked_grants[$nid][$op] = array_merge(array('all' => array(0)), $grants);
  651. }
  652. }
  653. }
  654. // Check for grants in the node_access table that aren't returned by
  655. // node_access_acquire_grants().
  656. if (isset($active_grants[$nid])) {
  657. foreach ($active_grants[$nid] as $realm => $active_grants_realm) {
  658. foreach ($active_grants_realm as $gid => $active_grant) {
  659. $found = FALSE;
  660. $count_nonempty_grants = 0;
  661. foreach ($acquired_grants_nid as $priority => $acquired_grants_nid_priority) {
  662. if (isset($acquired_grants_nid_priority[$realm][$gid])) {
  663. $found = TRUE;
  664. }
  665. }
  666. if ($acquired_grants_nid_priority = reset($acquired_grants_nid)) { // highest priority only
  667. foreach ($acquired_grants_nid_priority as $acquired_grants_nid_priority_realm) {
  668. foreach ($acquired_grants_nid_priority_realm as $acquired_grants_nid_priority_realm_gid) {
  669. $count_nonempty_grants += (!empty($acquired_grants_nid_priority_realm_gid['grant_view']) || !empty($acquired_grants_nid_priority_realm_gid['grant_update']) || !empty($acquired_grants_nid_priority_realm_gid['grant_delete']));
  670. }
  671. }
  672. }
  673. $fixed_grant = (array) $active_grant;
  674. if ($count_nonempty_grants == 0 && $realm == 'all' && $gid == 0) {
  675. $fixed_grant += array(
  676. 'priority' => '&ndash;',
  677. 'state' => 'default',
  678. );
  679. }
  680. elseif (!$found) {
  681. $acknowledged = _devel_node_access_module_invoke_all('node_access_acknowledge', $fixed_grant);
  682. if (empty($acknowledged)) {
  683. // No module acknowledged this record, mark it as alien.
  684. $fixed_grant += array(
  685. 'priority' => '?',
  686. 'state' => 'alien',
  687. );
  688. }
  689. else {
  690. // At least one module acknowledged the record. Attribute it
  691. // to the first one.
  692. $acknowledged_keys = array_keys($acknowledged);
  693. $fixed_grant += array(
  694. 'priority' => '&ndash;',
  695. 'state' => 'static',
  696. '#module' => reset($acknowledged_keys),
  697. );
  698. }
  699. }
  700. else {
  701. continue;
  702. }
  703. $fixed_grant += array(
  704. 'nid' => $nid,
  705. '#title' => _devel_node_access_get_node_title($node),
  706. );
  707. $all_grants[] = $fixed_grant;
  708. }
  709. }
  710. }
  711. // Order grants and evaluate their status.
  712. foreach ($acquired_grants_nid as $priority => $acquired_grants_priority) {
  713. ksort($acquired_grants_priority);
  714. foreach ($acquired_grants_priority as $realm => $acquired_grants_realm) {
  715. ksort($acquired_grants_realm);
  716. foreach ($acquired_grants_realm as $gid => $acquired_grant) {
  717. if ($priority == $top_priority) {
  718. if (empty($acquired_grant['grant_view']) && empty($acquired_grant['grant_update']) && empty($acquired_grant['grant_delete'])) {
  719. $acquired_grant['state'] = 'empty';
  720. }
  721. else {
  722. if (isset($active_grants[$nid][$realm][$gid])) {
  723. $acquired_grant['state'] = (isset($acquired_grant['#removed']) ? 'removed!' : 'ok');
  724. }
  725. else {
  726. $acquired_grant['state'] = (isset($acquired_grant['#removed']) ? 'removed' : 'missing');
  727. }
  728. if ($acquired_grant['state'] == 'ok') {
  729. foreach (array('view', 'update', 'delete') as $op) {
  730. $active_grant = (array) $active_grants[$nid][$realm][$gid];
  731. if (empty($acquired_grant["grant_$op"]) != empty($active_grant["grant_$op"])) {
  732. $acquired_grant["grant_$op!"] = $active_grant["grant_$op"];
  733. }
  734. }
  735. }
  736. }
  737. }
  738. else {
  739. $acquired_grant['state'] = (isset($active_grants[$nid][$realm][$gid]) ? 'illegitimate' : 'ignored');
  740. }
  741. $all_grants[] = $acquired_grant + array('nid' => $nid);
  742. }
  743. }
  744. }
  745. }
  746. // Fill in the table rows.
  747. $rows = array();
  748. $error_count = 0;
  749. foreach ($all_grants as $grant) {
  750. $row = new stdClass();
  751. $row->nid = $grant['nid'];
  752. $row->title = $grant['#title'];
  753. $row->priority = $grant['priority'];
  754. $row->state = array('data' => $states[$grant['state']][0], 'title' => $states[$grant['state']][2]);
  755. $row->realm = $grant['realm'];
  756. $row->gid = $grant['gid'];
  757. $row->grant_view = $grant['grant_view'];
  758. $row->grant_update = $grant['grant_update'];
  759. $row->grant_delete = $grant['grant_delete'];
  760. $row->explained = implode('<br />', module_invoke_all('node_access_explain', $row));
  761. unset($row->title); // possibly needed above
  762. if ($row->nid == 0 && $row->gid == 0 && $row->realm == 'all' && count($all_grants) > 1) {
  763. $row->state = array('data' => $states['unexpected'][0], 'title' => $states['unexpected'][2]);
  764. $class = $states['unexpected'][1];
  765. }
  766. else {
  767. $class = $states[$grant['state']][1];
  768. }
  769. $row = (array) $row;
  770. foreach (array('view', 'update', 'delete') as $op) {
  771. $row["grant_$op"] = array('data' => $row["grant_$op"]);
  772. if ((isset($checked_grants[$grant['nid']][$op][$grant['realm']]) && in_array($grant['gid'], $checked_grants[$grant['nid']][$op][$grant['realm']]) || ($row['nid'] == 0 && $row['gid'] == 0 && $row['realm'] == 'all')) && !empty($row["grant_$op"]['data']) && in_array($grant['state'], $active_states)) {
  773. $row["grant_$op"]['data'] .= '&prime;';
  774. $row["grant_$op"]['title'] = t('This entry grants access to this node to this user.');
  775. }
  776. if (isset($grant["grant_$op!"])) {
  777. $row["grant_$op"]['data'] = $grant["grant_$op!"] . '&gt;' . (!$row["grant_$op"]['data'] ? 0 : $row["grant_$op"]['data']);
  778. $row["grant_$op"]['class'][] = 'error';
  779. if ($class == 'ok') {
  780. $row['state'] = array('data' => $states['wrong'][0], 'title' => $states['wrong'][2]);
  781. $class = $states['wrong'][1];
  782. }
  783. }
  784. }
  785. $error_count += ($class == 'error');
  786. $row['nid'] = array(
  787. 'data' => '<a href="#node-' . $grant['nid'] . '">' . $row['nid'] . '</a>',
  788. 'title' => $grant['#title'],
  789. );
  790. if (empty($grant['#module']) || strpos($grant['realm'], $grant['#module']) === 0) {
  791. $row['realm'] = $grant['realm'];
  792. }
  793. else {
  794. $row['realm'] = array(
  795. 'data' => $grant['#module'] . ':<br />' . $grant['realm'],
  796. 'title' => t("The '@module' module fails to adhere to the best practice of naming its realm(s) after itself.", array('@module' => $grant['#module'])),
  797. );
  798. }
  799. // Prepend information from the D7 hook_node_access_records_alter().
  800. $next_style = array();
  801. if (isset($grant['history'])) {
  802. $history = $grant['history'];
  803. if (($num_changes = count($history['changes']) - empty($history['current'])) > 0) {
  804. $first_row = TRUE;
  805. while (isset($history['original']) || $num_changes--) {
  806. if (isset($history['original'])) {
  807. $this_grant = $history['original'];
  808. $this_action = '[ Original by ' . $this_grant['#module'] . ':';
  809. unset($history['original']);
  810. }
  811. else {
  812. $change = $history['changes'][0];
  813. $this_grant = $change['grant'];
  814. $this_action = ($first_row ? '[ ' : '') . $change['op'] . ':';
  815. array_shift($history['changes']);
  816. }
  817. $rows[] = array(
  818. 'data' => array(
  819. 'data' => array(
  820. 'data' => $this_action,
  821. 'style' => array('padding-bottom: 0;'),
  822. ),
  823. ),
  824. 'style' => array_merge(($first_row ? array() : array('border-top-style: dashed;', 'border-top-width: 1px;')), array('border-bottom-style: none;')),
  825. );
  826. $next_style = array('border-top-style: none;');
  827. if (count($history['changes'])) {
  828. $g = $this_grant;
  829. $rows[] = array(
  830. 'data' => array('v', $g['priority'], '', $g['realm'], $g['gid'], $g['grant_view'], $g['grant_update'], $g['grant_delete'], 'v'),
  831. 'style' => array('border-top-style: none;', 'border-bottom-style: dashed;'),
  832. );
  833. $next_style = array('border-top-style: dashed;');
  834. }
  835. $first_row = FALSE;
  836. }
  837. }
  838. }
  839. // Fix up the main row cells with the proper class (needed for
  840. // Bartik).
  841. foreach ($row as $key => $value) {
  842. if (!is_array($value)) {
  843. $row[$key] = array('data' => $value);
  844. }
  845. $row[$key]['class'] = array($class);
  846. }
  847. // Add the main row.
  848. $will_append = empty($history['current']) && !empty($history['changes']);
  849. $rows[] = array(
  850. 'data' => array_values($row),
  851. 'class' => array($class),
  852. 'style' => array_merge($next_style, ($will_append ? array('border-bottom-style: none;') : array())),
  853. );
  854. // Append information from the D7 hook_node_access_records_alter().
  855. if ($will_append) {
  856. $last_change = end($history['changes']);
  857. $rows[] = array(
  858. 'data' => array(
  859. 'data' => array(
  860. 'data' => $last_change['op'] . ' ]',
  861. 'style' => array('padding-top: 0;'),
  862. ),
  863. ),
  864. 'style' => array('border-top-style: none;'),
  865. );
  866. }
  867. }
  868. foreach ($rows as $i => $row) {
  869. $rows[$i] = _devel_node_access_format_row($row);
  870. }
  871. $output[] = array(
  872. '#theme' => 'table',
  873. '#header' => $headers,
  874. '#rows' => $rows,
  875. '#attributes' => array(
  876. 'class' => array('system-status-report'),
  877. 'style' => 'text-align: left;',
  878. ),
  879. );
  880. $output[] = array(
  881. '#theme' => 'form_element',
  882. '#description' => t('(Some of the table elements provide additional information if you hover your mouse over them.)'),
  883. );
  884. if ($error_count > 0) {
  885. $variables['!Rebuild_permissions'] = '<a href="' . url('admin/reports/status/rebuild') . '">' . $tr('Rebuild permissions') . '</a>';
  886. $output[] = array(
  887. '#prefix' => "\n<div class=\"error\">",
  888. '#markup' => t("You have errors in your !na table! You may be able to fix these for now by running !Rebuild_permissions, but this is likely to destroy the evidence and make it impossible to identify the underlying issues. If you don't fix those, the errors will probably come back again. <br /> DON'T do this just yet if you intend to ask for help with this situation.", $variables),
  889. '#suffix' => "</div><br />\n",
  890. );
  891. }
  892. // Explain whether access is granted or denied, and why (using code from
  893. // node_access()).
  894. $tr = 't';
  895. array_shift($nids); // remove the 0
  896. $accounts = array();
  897. $variables += array(
  898. '!username' => '<em class="placeholder">' . theme('username', array('account' => $user)) . '</em>',
  899. '%uid' => $user->uid,
  900. );
  901. if (user_access('bypass node access')) {
  902. $variables['%bypass_node_access'] = $tr('bypass node access');
  903. $output[] = array(
  904. '#markup' => t('!username has the %bypass_node_access permission and thus full access to all nodes.', $variables),
  905. '#suffix' => '<br />&nbsp;',
  906. );
  907. }
  908. else {
  909. $variables['!list'] = '<div style="margin-left: 2em">' . _devel_node_access_get_grant_list($nid, $ng_alter_datas['view']) . '</div>';
  910. $variables['%access'] = 'view';
  911. $output[] = array(
  912. '#prefix' => "\n<div style='text-align: left' title='" . t('These are the grants returned by hook_node_grants() for this user.') . "'>",
  913. '#markup' => t('!username (user %uid) can use these grants (if they are present above) for %access access: !list', $variables),
  914. '#suffix' => "</div>\n",
  915. );
  916. $accounts[] = $user;
  917. }
  918. $menu_item = menu_get_item();
  919. $map = $menu_item['original_map'];
  920. if ($map[0] == 'node' && isset($map[1]) && is_numeric($map[1]) && !isset($map[2]) && !$block1_visible) {
  921. // Only for single nodes.
  922. if (user_is_logged_in()) {
  923. $accounts[] = user_load(0); // Anonymous, too
  924. }
  925. foreach ($accounts as $account) {
  926. $account_items = array();
  927. $nid_items = array();
  928. foreach ($nids as $nid) {
  929. $op_items = array();
  930. foreach (array('create', 'view', 'update', 'delete') as $op) {
  931. $explain = _devel_node_access_explain_access($op, $nid, $account);
  932. $op_items[] = "<div style='width: 5em; display: inline-block'>" . t('%op:', array('%op' => $op)) . ' </div>' . $explain[2];
  933. }
  934. $nid_items[] = array(
  935. '#theme' => 'item_list',
  936. '#items' => $op_items,
  937. '#type' => 'ul',
  938. '#prefix' => t('to node !nid:', array('!nid' => l($nid, 'node/' . $nid))) . "\n<div style='margin-left: 2em'>",
  939. '#suffix' => '</div>',
  940. );
  941. }
  942. if (count($nid_items) == 1) {
  943. $account_items = $nid_items[0];
  944. }
  945. else {
  946. $account_items = array(
  947. '#theme' => 'item_list',
  948. '#items' => $nid_items,
  949. '#type' => 'ul',
  950. '#prefix' => "\n<div style='margin-left: 2em'>",
  951. '#suffix' => '</div>',
  952. );
  953. }
  954. $variables['!username'] = '<em class="placeholder">' . theme('username', array('account' => $account)) . '</em>';
  955. $output[] = array(
  956. '#prefix' => "\n<div style='text-align: left'>",
  957. '#type' => 'item',
  958. 'lead-in' => array('#markup' => t("!username has the following access", $variables) . ' '),
  959. 'items' => $account_items,
  960. '#suffix' => "\n</div>\n",
  961. );
  962. }
  963. }
  964. }
  965. if (!empty($hint)) {
  966. $output[] = array(
  967. '#theme' => 'form_element',
  968. '#description' => '(' . $hint . ')',
  969. );
  970. }
  971. $output[]['#markup'] = '<br /><br />';
  972. $subject = t('node_access entries for nodes shown on this page');
  973. return array('subject' => $subject, 'content' => $output);
  974. case 'dna_user':
  975. // Show which users can access this node.
  976. $menu_item = menu_get_item();
  977. $map = $menu_item['original_map'];
  978. if ($map[0] != 'node' || !isset($map[1]) || !is_numeric($map[1]) || isset($map[2])) {
  979. // Ignore anything but node/%.
  980. return;
  981. }
  982. if (isset($menu_item['map'][1]) && is_object($node = $menu_item['map'][1])) {
  983. // We have the node.
  984. }
  985. elseif (is_numeric($menu_item['original_map'][1])) {
  986. $node = node_load($menu_item['original_map'][1]);
  987. }
  988. if (isset($node)) {
  989. $nid = $node->nid;
  990. $node_type = node_type_get_type($node);
  991. $variables = array('@Node_type' => ($node_type ? $node_type->name : $node->type));
  992. $create_header = '<span title="' . t("Create nodes of the '@Node_type' type.", $variables) . '">' . t('create') . '</span>';
  993. if (!$node_type) {
  994. $create_header .= '<br /><span class="error">' . t("(missing type: '@Node_type')", $variables) . '</span>';
  995. }
  996. $headers = array(t('username'), $create_header, t('view'), t('update'), t('delete'));
  997. $rows = array();
  998. // Determine whether to use Ajax or prepopulate the tables.
  999. if ($ajax = variable_get('devel_node_access_user_ajax', FALSE)) {
  1000. drupal_add_js(drupal_get_path('module', 'devel_node_access') . '/devel_node_access.js');
  1001. }
  1002. // Find all users. The following operations are very inefficient, so we
  1003. // limit the number of users returned. It would be better to make a
  1004. // pager query, or at least make the number of users configurable. If
  1005. // anyone is up for that please submit a patch.
  1006. $query = db_select('users', 'u')
  1007. ->fields('u', array('uid'))
  1008. ->orderBy('u.access', 'DESC')
  1009. ->range(0, 9);
  1010. $uids = $query->execute()->fetchCol();
  1011. array_unshift($uids, 0);
  1012. $accounts = user_load_multiple($uids);
  1013. foreach ($accounts as $account) {
  1014. $username = theme('username', array('account' => $account));
  1015. if ($account->uid == $user->uid) {
  1016. $username = '<strong>' . $username . '</strong>';
  1017. }
  1018. $rows[] = array(
  1019. $username,
  1020. array(
  1021. 'id' => 'create-' . $nid . '-' . $account->uid,
  1022. 'class' => 'dna-permission',
  1023. 'data' => $ajax ? NULL : theme('dna_permission', array('permission' => _devel_node_access_explain_access('create', $nid, $account))),
  1024. ),
  1025. array(
  1026. 'id' => 'view-' . $nid . '-' . $account->uid,
  1027. 'class' => 'dna-permission',
  1028. 'data' => $ajax ? NULL : theme('dna_permission', array('permission' => _devel_node_access_explain_access('view', $nid, $account))),
  1029. ),
  1030. array(
  1031. 'id' => 'update-' . $nid . '-' . $account->uid,
  1032. 'class' => 'dna-permission',
  1033. 'data' => $ajax ? NULL : theme('dna_permission', array('permission' => _devel_node_access_explain_access('update', $nid, $account))),
  1034. ),
  1035. array(
  1036. 'id' => 'delete-' . $nid . '-' . $account->uid,
  1037. 'class' => 'dna-permission',
  1038. 'data' => $ajax ? NULL : theme('dna_permission', array('permission' => _devel_node_access_explain_access('delete', $nid, $account))),
  1039. ),
  1040. );
  1041. }
  1042. if (count($rows)) {
  1043. $output[] = array(
  1044. '#theme' => 'table',
  1045. '#header' => $headers,
  1046. '#rows' => $rows,
  1047. '#attributes' => array('style' => 'text-align: left'),
  1048. );
  1049. $output[] = array(
  1050. '#theme' => 'form_element',
  1051. '#description' => t('(This table lists the most-recently active users. Hover your mouse over each result for more details.)'),
  1052. );
  1053. return array(
  1054. 'subject' => t('Access permissions by user'),
  1055. 'content' => $output,
  1056. );
  1057. }
  1058. }
  1059. break;
  1060. }
  1061. }
  1062. /**
  1063. * Page callback for node access by user block ajax.
  1064. */
  1065. function devel_node_access_user_ajax($data_type, $cell) {
  1066. list($op, $nid, $uid) = explode('-', $cell);
  1067. $account = user_load($uid);
  1068. $output = array(
  1069. '#theme' => 'dna_permission',
  1070. '#permission' => _devel_node_access_explain_access($op, $nid, $account),
  1071. );
  1072. // JSON output for Ajax callbacks.
  1073. if ($data_type == 'json') {
  1074. drupal_json_output(drupal_render($output));
  1075. exit;
  1076. }
  1077. // HTML output for error message click-throughs.
  1078. if ($node = node_load($nid)) {
  1079. $node_title = l($node->title, 'node/' . $node->nid);
  1080. }
  1081. else {
  1082. $node_title = t('unknown node %nid', array('%nid' => $nid));
  1083. }
  1084. drupal_set_title(
  1085. t(
  1086. 'Devel node access: %op permission for !user on !node',
  1087. array(
  1088. '%op' => $op,
  1089. '!user' => theme('username', array('account' => $account)),
  1090. '!node' => $node_title,
  1091. )
  1092. ),
  1093. PASS_THROUGH
  1094. );
  1095. return $output;
  1096. }
  1097. /**
  1098. * Helper function that mimicks node.module's node_access() function.
  1099. *
  1100. * Unfortunately, this needs to be updated manually whenever node.module
  1101. * changes!
  1102. *
  1103. * @return
  1104. * An array suitable for theming with theme_dna_permission().
  1105. */
  1106. function _devel_node_access_explain_access($op, $node, $account = NULL) {
  1107. global $user;
  1108. if (is_numeric($node) && !($node = node_load($node))) {
  1109. return array(
  1110. FALSE,
  1111. '???',
  1112. t('Unable to load the node &ndash; this should never happen!'),
  1113. );
  1114. }
  1115. if (!in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
  1116. return array(
  1117. FALSE,
  1118. t('!NO: invalid $op', array('!NO' => t('NO'))),
  1119. t("'@op' is an invalid operation!", array('@op' => $op)),
  1120. );
  1121. }
  1122. if ($op == 'create' && is_object($node)) {
  1123. $node = $node->type;
  1124. }
  1125. if (!empty($account)) {
  1126. // To try to get the most authentic result we impersonate the given user!
  1127. // This may reveal bugs in other modules, leading to contradictory results.
  1128. $saved_user = $user;
  1129. drupal_save_session(FALSE);
  1130. $user = $account;
  1131. $result = _devel_node_access_explain_access($op, $node, NULL);
  1132. $user = $saved_user;
  1133. drupal_save_session(TRUE);
  1134. $second_opinion = node_access($op, $node, $account);
  1135. if ($second_opinion != $result[0]) {
  1136. $result[1] .= '<span class="' . ($second_opinion ? 'ok' : 'error') . '" title="Core seems to disagree on this item. This is a bug in either DNA or Core and should be fixed! Try to look at this node as this user and check whether there is still disagreement.">*</span>';
  1137. }
  1138. return $result;
  1139. }
  1140. $variables = array(
  1141. '!NO' => t('NO'),
  1142. '!YES' => t('YES'),
  1143. '!bypass_node_access' => t('bypass node access'),
  1144. '!access_content' => t('access content'),
  1145. );
  1146. if (user_access('bypass node access')) {
  1147. return array(
  1148. TRUE,
  1149. t('!YES: bypass node access', $variables),
  1150. t("!YES: This user has the '!bypass_node_access' permission and may do everything with nodes.", $variables),
  1151. );
  1152. }
  1153. if (!user_access('access content')) {
  1154. return array(
  1155. FALSE,
  1156. t('!NO: access content', $variables),
  1157. t("!NO: This user does not have the '!access_content' permission and is denied doing anything with content.", $variables),
  1158. );
  1159. }
  1160. foreach (module_implements('node_access') as $module) {
  1161. $function = $module . '_node_access';
  1162. if (function_exists($function)) {
  1163. $result = $function($node, $op, $user);
  1164. if ($module == 'node') {
  1165. $module = 'node (permissions)';
  1166. }
  1167. if (isset($result)) {
  1168. if ($result === NODE_ACCESS_DENY) {
  1169. $denied_by[] = $module;
  1170. }
  1171. elseif ($result === NODE_ACCESS_ALLOW) {
  1172. $allowed_by[] = $module;
  1173. }
  1174. $access[] = $result;
  1175. }
  1176. }
  1177. }
  1178. $variables += array(
  1179. '@deniers' => (empty($denied_by) ? NULL : implode(', ', $denied_by)),
  1180. '@allowers' => (empty($allowed_by) ? NULL : implode(', ', $allowed_by)),
  1181. );
  1182. if (!empty($denied_by)) {
  1183. $variables += array(
  1184. '%module' => $denied_by[0] . (count($denied_by) > 1 ? '+' : ''),
  1185. );
  1186. return array(
  1187. FALSE,
  1188. t('!NO: by %module', $variables),
  1189. empty($allowed_by)
  1190. ? t("!NO: hook_node_access() of the following module(s) denies this: @deniers.", $variables)
  1191. : t("!NO: hook_node_access() of the following module(s) denies this: @deniers &ndash; even though the following module(s) would allow it: @allowers.", $variables),
  1192. );
  1193. }
  1194. if (!empty($allowed_by)) {
  1195. $variables += array(
  1196. '%module' => $allowed_by[0] . (count($allowed_by) > 1 ? '+' : ''),
  1197. '!view_own_unpublished_content' => t('view own unpublished content'),
  1198. );
  1199. return array(
  1200. TRUE,
  1201. t('!YES: by %module', $variables),
  1202. t("!YES: hook_node_access() of the following module(s) allows this: @allowers.", $variables),
  1203. );
  1204. }
  1205. if ($op == 'view' && !$node->status && user_access('view own unpublished content') && $user->uid == $node->uid && $user->uid != 0) {
  1206. return array(
  1207. TRUE,
  1208. t('!YES: view own unpublished content', $variables),
  1209. t("!YES: The node is unpublished, but the user has the '!view_own_unpublished_content' permission.", $variables),
  1210. );
  1211. }
  1212. if ($op != 'create' && $node->nid) {
  1213. if (node_access($op, $node)) { // delegate this part
  1214. $variables['@node_access_table'] = '{node_access}';
  1215. return array(
  1216. TRUE,
  1217. t('!YES: @node_access_table', $variables),
  1218. t('!YES: Node access allows this based on one or more records in the @node_access_table table (see the other DNA block!).', $variables),
  1219. );
  1220. }
  1221. }
  1222. return array(
  1223. FALSE,
  1224. t('!NO: no reason', $variables),
  1225. t("!NO: None of the checks resulted in allowing this, so it's denied.", $variables)
  1226. . ($op == 'create' ? ' ' . t('This is most likely due to a withheld permission.') : ''),
  1227. );
  1228. }
  1229. /**
  1230. * Creates a list of the grants returned by hook_node_grants().
  1231. *
  1232. * @param integer $nid
  1233. * @param array $ng_alter_data
  1234. *
  1235. * @return
  1236. * A themed item list of grants.
  1237. */
  1238. function _devel_node_access_get_grant_list($nid, $ng_alter_data) {
  1239. //dpm($ng_alter_data, "_devel_node_access_get_grant_list($nid,");
  1240. $ng_alter_data = array_merge(array('all' => array(0 => array('cur' => TRUE, 'ori' => array('all')))), $ng_alter_data);
  1241. $items = array();
  1242. if (count($ng_alter_data)) {
  1243. foreach ($ng_alter_data as $realm => $gids) {
  1244. ksort($gids);
  1245. $gs = array();
  1246. foreach ($gids as $gid => $history) {
  1247. if ($history['cur']) {
  1248. if (isset($history['ori'])) {
  1249. $g = $gid; // original grant, still active
  1250. }
  1251. else {
  1252. $g = '<u>' . $gid . '</u>'; // new grant, still active
  1253. }
  1254. }
  1255. else {
  1256. $g = '<del>' . $gid . '</del>'; // deleted grant
  1257. }
  1258. $ghs = array();
  1259. if (isset($history['ori']) && strpos($realm, $history['ori'][0]) !== 0) {
  1260. $ghs[] = 'by ' . $history['ori'][0];
  1261. }
  1262. if (isset($history['chg'])) {
  1263. foreach ($history['chg'] as $h) {
  1264. $ghs[] = $h;
  1265. }
  1266. }
  1267. if (!empty($ghs)) {
  1268. $g .= ' (' . implode(', ', $ghs) . ')';
  1269. }
  1270. $gs[] = $g;
  1271. }
  1272. $items[] = $realm . ': ' . implode(', ', $gs);
  1273. }
  1274. if (!empty($items)) {
  1275. return theme('item_list', array('items' => $items, 'type' => 'ul'));
  1276. }
  1277. }
  1278. }
  1279. /**
  1280. * Implements hook_node_access_explain().
  1281. */
  1282. function devel_node_access_node_access_explain($row) {
  1283. if ($row->gid == 0 && $row->realm == 'all') {
  1284. foreach (array('view', 'update', 'delete') as $op) {
  1285. $gop = 'grant_' . $op;
  1286. if (!empty($row->$gop)) {
  1287. $ops[] = $op;
  1288. }
  1289. }
  1290. if (empty($ops)) {
  1291. return '(No access granted to ' . ($row->nid == 0 ? 'any nodes.)' : 'this node.)');
  1292. }
  1293. else {
  1294. return 'All users may ' . implode('/', $ops) . ($row->nid == 0 ? ' all nodes.' : ' this node.');
  1295. }
  1296. }
  1297. }
  1298. /**
  1299. * Return a sanitized node title.
  1300. *
  1301. * @param $node
  1302. * The node from which to get the title.
  1303. * @param boolean $clip_and_decorate
  1304. * (optional) Set to TRUE to limit the length of the returned title and to add
  1305. * markup to make it easier to style.
  1306. *
  1307. * @return string
  1308. * The sanitized node title.
  1309. */
  1310. function _devel_node_access_get_node_title($node, $clip_and_decorate = FALSE) {
  1311. if (isset($node)) {
  1312. if (isset($node->title)) {
  1313. $node_title = check_plain(!is_array($node->title) ? $node->title : $node->title[LANGUAGE_NONE][0]['value']);
  1314. if ($clip_and_decorate) {
  1315. if (drupal_strlen($node_title) > 20) {
  1316. $node_title = "<span title='node/$node->nid: $node_title'>" . drupal_substr($node_title, 0, 15) . '...</span>';
  1317. }
  1318. $node_title = '<span title="node/' . $node->nid . '">' . $node_title . '</span>';
  1319. }
  1320. return $node_title;
  1321. }
  1322. elseif (isset($node->nid)) {
  1323. return $node->nid;
  1324. }
  1325. }
  1326. return '&mdash;';
  1327. }
  1328. /**
  1329. * Applies common formatting to a debug-mode table row.
  1330. *
  1331. * @param array $row
  1332. * The row to format.
  1333. * @param boolean $may_unpack
  1334. * (optional) Indicates if $row['data'] needs be formatted rather than $row
  1335. * itself. Default is TRUE.
  1336. */
  1337. function _devel_node_access_format_row($row, $may_unpack = TRUE) {
  1338. if ($may_unpack && isset($row['data'])) {
  1339. $row['data'] = _devel_node_access_format_row($row['data'], FALSE);
  1340. $row['class'][] = 'even';
  1341. return $row;
  1342. }
  1343. if (count($row) == 1) {
  1344. if (is_scalar($row['data'])) {
  1345. $row['data'] = array('data' => $row['data']);
  1346. }
  1347. $row['data']['colspan'] = 9;
  1348. }
  1349. else {
  1350. $row = array_values($row);
  1351. foreach (array(0, 1, 4) as $j) { // node, prio, gid
  1352. if (is_scalar($row[$j])) {
  1353. $row[$j] = array('data' => $row[$j]);
  1354. }
  1355. $row[$j]['style'][] = 'text-align: right;';
  1356. }
  1357. }
  1358. return $row;
  1359. }
  1360. /**
  1361. * Implements hook_theme().
  1362. */
  1363. function devel_node_access_theme() {
  1364. return array(
  1365. 'dna_permission' => array(
  1366. 'variables' => array(
  1367. 'permission' => NULL,
  1368. ),
  1369. ),
  1370. );
  1371. }
  1372. /**
  1373. * Returns HTML to indicate if a user has a permission.
  1374. *
  1375. * @param array $variables
  1376. * An associative array containing:
  1377. * - permission: An indexed array containing:
  1378. * - 0: A value indicating if the user has permission.
  1379. * - 1: The text of the message to display.
  1380. * - 2: The title to display containing additional information.
  1381. */
  1382. function theme_dna_permission($variables) {
  1383. $permission = &$variables['permission'];
  1384. return '<span class="' . ($permission[0] ? 'ok' : 'error') . '" title="' . $permission[2] . '">' . $permission[1] . '</span>';
  1385. }