node.module 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179
  1. <?php
  2. /**
  3. * @file
  4. * The core that allows content to be submitted to the site. Modules and
  5. * scripts may programmatically submit nodes using the usual form API pattern.
  6. */
  7. /**
  8. * Node is not published.
  9. */
  10. define('NODE_NOT_PUBLISHED', 0);
  11. /**
  12. * Node is published.
  13. */
  14. define('NODE_PUBLISHED', 1);
  15. /**
  16. * Node is not promoted to front page.
  17. */
  18. define('NODE_NOT_PROMOTED', 0);
  19. /**
  20. * Node is promoted to front page.
  21. */
  22. define('NODE_PROMOTED', 1);
  23. /**
  24. * Node is not sticky at top of the page.
  25. */
  26. define('NODE_NOT_STICKY', 0);
  27. /**
  28. * Node is sticky at top of the page.
  29. */
  30. define('NODE_STICKY', 1);
  31. /**
  32. * Nodes changed before this time are always marked as read.
  33. *
  34. * Nodes changed after this time may be marked new, updated, or read, depending
  35. * on their state for the current user. Defaults to 30 days ago.
  36. */
  37. define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
  38. /**
  39. * Modules should return this value from hook_node_access() to allow access to a node.
  40. */
  41. define('NODE_ACCESS_ALLOW', 'allow');
  42. /**
  43. * Modules should return this value from hook_node_access() to deny access to a node.
  44. */
  45. define('NODE_ACCESS_DENY', 'deny');
  46. /**
  47. * Modules should return this value from hook_node_access() to not affect node access.
  48. */
  49. define('NODE_ACCESS_IGNORE', NULL);
  50. /**
  51. * Implements hook_help().
  52. */
  53. function node_help($path, $arg) {
  54. // Remind site administrators about the {node_access} table being flagged
  55. // for rebuild. We don't need to issue the message on the confirm form, or
  56. // while the rebuild is being processed.
  57. if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
  58. && user_access('access administration pages') && node_access_needs_rebuild()) {
  59. if ($path == 'admin/reports/status') {
  60. $message = t('The content access permissions need to be rebuilt.');
  61. }
  62. else {
  63. $message = t('The content access permissions need to be rebuilt. <a href="@node_access_rebuild">Rebuild permissions</a>.', array('@node_access_rebuild' => url('admin/reports/status/rebuild')));
  64. }
  65. drupal_set_message($message, 'error');
  66. }
  67. switch ($path) {
  68. case 'admin/help#node':
  69. $output = '';
  70. $output .= '<h3>' . t('About') . '</h3>';
  71. $output .= '<p>' . t('The Node module manages the creation, editing, deletion, settings, and display of the main site content. Content items managed by the Node module are typically displayed as pages on your site, and include a title, some meta-data (author, creation time, content type, etc.), and optional fields containing text or other data (fields are managed by the <a href="@field">Field module</a>). For more information, see the online handbook entry for <a href="@node">Node module</a>.', array('@node' => 'http://drupal.org/documentation/modules/node', '@field' => url('admin/help/field'))) . '</p>';
  72. $output .= '<h3>' . t('Uses') . '</h3>';
  73. $output .= '<dl>';
  74. $output .= '<dt>' . t('Creating content') . '</dt>';
  75. $output .= '<dd>' . t('When new content is created, the Node module records basic information about the content, including the author, date of creation, and the <a href="@content-type">Content type</a>. It also manages the <em>publishing options</em>, which define whether or not the content is published, promoted to the front page of the site, and/or sticky at the top of content lists. Default settings can be configured for each <a href="@content-type">type of content</a> on your site.', array('@content-type' => url('admin/structure/types'))) . '</dd>';
  76. $output .= '<dt>' . t('Creating custom content types') . '</dt>';
  77. $output .= '<dd>' . t('The Node module gives users with the <em>Administer content types</em> permission the ability to <a href="@content-new">create new content types</a> in addition to the default ones already configured. Creating custom content types allows you the flexibility to add <a href="@field">fields</a> and configure default settings that suit the differing needs of various site content.', array('@content-new' => url('admin/structure/types/add'), '@field' => url('admin/help/field'))) . '</dd>';
  78. $output .= '<dt>' . t('Administering content') . '</dt>';
  79. $output .= '<dd>' . t('The <a href="@content">Content administration page</a> allows you to review and bulk manage your site content.', array('@content' => url('admin/content'))) . '</dd>';
  80. $output .= '<dt>' . t('Creating revisions') . '</dt>';
  81. $output .= '<dd>' . t('The Node module also enables you to create multiple versions of any content, and revert to older versions using the <em>Revision information</em> settings.') . '</dd>';
  82. $output .= '<dt>' . t('User permissions') . '</dt>';
  83. $output .= '<dd>' . t('The Node module makes a number of permissions available for each content type, which can be set by role on the <a href="@permissions">permissions page</a>.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-node')))) . '</dd>';
  84. $output .= '</dl>';
  85. return $output;
  86. case 'admin/structure/types/add':
  87. return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
  88. case 'admin/structure/types/manage/%/display':
  89. return '<p>' . t('Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. <em>Teaser</em> is a short format that is typically used in lists of multiple content items. <em>Full content</em> is typically used when the content is displayed on its own page.') . '</p>' .
  90. '<p>' . t('Here, you can define which fields are shown and hidden when %type content is displayed in each view mode, and define how the fields are displayed in each view mode.', array('%type' => node_type_get_name($arg[4]))) . '</p>';
  91. case 'node/%/revisions':
  92. return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert back to older versions.') . '</p>';
  93. case 'node/%/edit':
  94. $node = node_load($arg[1]);
  95. $type = node_type_get_type($node);
  96. return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
  97. }
  98. if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
  99. $type = node_type_get_type(str_replace('-', '_', $arg[2]));
  100. return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
  101. }
  102. }
  103. /**
  104. * Implements hook_theme().
  105. */
  106. function node_theme() {
  107. return array(
  108. 'node' => array(
  109. 'render element' => 'elements',
  110. 'template' => 'node',
  111. ),
  112. 'node_search_admin' => array(
  113. 'render element' => 'form',
  114. ),
  115. 'node_add_list' => array(
  116. 'variables' => array('content' => NULL),
  117. 'file' => 'node.pages.inc',
  118. ),
  119. 'node_preview' => array(
  120. 'variables' => array('node' => NULL),
  121. 'file' => 'node.pages.inc',
  122. ),
  123. 'node_admin_overview' => array(
  124. 'variables' => array('name' => NULL, 'type' => NULL),
  125. 'file' => 'content_types.inc',
  126. ),
  127. 'node_recent_block' => array(
  128. 'variables' => array('nodes' => NULL),
  129. ),
  130. 'node_recent_content' => array(
  131. 'variables' => array('node' => NULL),
  132. ),
  133. );
  134. }
  135. /**
  136. * Implements hook_cron().
  137. */
  138. function node_cron() {
  139. db_delete('history')
  140. ->condition('timestamp', NODE_NEW_LIMIT, '<')
  141. ->execute();
  142. }
  143. /**
  144. * Implements hook_entity_info().
  145. */
  146. function node_entity_info() {
  147. $return = array(
  148. 'node' => array(
  149. 'label' => t('Node'),
  150. 'controller class' => 'NodeController',
  151. 'base table' => 'node',
  152. 'revision table' => 'node_revision',
  153. 'uri callback' => 'node_uri',
  154. 'fieldable' => TRUE,
  155. 'entity keys' => array(
  156. 'id' => 'nid',
  157. 'revision' => 'vid',
  158. 'bundle' => 'type',
  159. 'label' => 'title',
  160. 'language' => 'language',
  161. ),
  162. 'bundle keys' => array(
  163. 'bundle' => 'type',
  164. ),
  165. 'bundles' => array(),
  166. 'view modes' => array(
  167. 'full' => array(
  168. 'label' => t('Full content'),
  169. 'custom settings' => FALSE,
  170. ),
  171. 'teaser' => array(
  172. 'label' => t('Teaser'),
  173. 'custom settings' => TRUE,
  174. ),
  175. 'rss' => array(
  176. 'label' => t('RSS'),
  177. 'custom settings' => FALSE,
  178. ),
  179. ),
  180. ),
  181. );
  182. // Search integration is provided by node.module, so search-related view modes
  183. // for nodes are defined here and not in search.module.
  184. if (module_exists('search')) {
  185. $return['node']['view modes'] += array(
  186. 'search_index' => array(
  187. 'label' => t('Search index'),
  188. 'custom settings' => FALSE,
  189. ),
  190. 'search_result' => array(
  191. 'label' => t('Search result'),
  192. 'custom settings' => FALSE,
  193. ),
  194. );
  195. }
  196. // Bundles must provide a human readable name so we can create help and error
  197. // messages, and the path to attach Field admin pages to.
  198. foreach (node_type_get_names() as $type => $name) {
  199. $return['node']['bundles'][$type] = array(
  200. 'label' => $name,
  201. 'admin' => array(
  202. 'path' => 'admin/structure/types/manage/%node_type',
  203. 'real path' => 'admin/structure/types/manage/' . str_replace('_', '-', $type),
  204. 'bundle argument' => 4,
  205. 'access arguments' => array('administer content types'),
  206. ),
  207. );
  208. }
  209. return $return;
  210. }
  211. /**
  212. * Implements hook_field_display_ENTITY_TYPE_alter().
  213. */
  214. function node_field_display_node_alter(&$display, $context) {
  215. // Hide field labels in search index.
  216. if ($context['view_mode'] == 'search_index') {
  217. $display['label'] = 'hidden';
  218. }
  219. }
  220. /**
  221. * Entity URI callback.
  222. *
  223. * @param $node
  224. * A node entity.
  225. *
  226. * @return array
  227. * An array with 'path' as the key and the path to the node as its value.
  228. */
  229. function node_uri($node) {
  230. return array(
  231. 'path' => 'node/' . $node->nid,
  232. );
  233. }
  234. /**
  235. * Implements hook_admin_paths().
  236. */
  237. function node_admin_paths() {
  238. if (variable_get('node_admin_theme')) {
  239. $paths = array(
  240. 'node/*/edit' => TRUE,
  241. 'node/*/delete' => TRUE,
  242. 'node/*/revisions' => TRUE,
  243. 'node/*/revisions/*/revert' => TRUE,
  244. 'node/*/revisions/*/delete' => TRUE,
  245. 'node/add' => TRUE,
  246. 'node/add/*' => TRUE,
  247. );
  248. return $paths;
  249. }
  250. }
  251. /**
  252. * Gathers a listing of links to nodes.
  253. *
  254. * @param $result
  255. * A database result object from a query to fetch node entities. If your
  256. * query joins the {node_comment_statistics} table so that the comment_count
  257. * field is available, a title attribute will be added to show the number of
  258. * comments.
  259. * @param $title
  260. * A heading for the resulting list.
  261. *
  262. * @return
  263. * A renderable array containing a list of linked node titles fetched from
  264. * $result, or FALSE if there are no rows in $result.
  265. */
  266. function node_title_list($result, $title = NULL) {
  267. $items = array();
  268. $num_rows = FALSE;
  269. foreach ($result as $node) {
  270. $items[] = l($node->title, 'node/' . $node->nid, !empty($node->comment_count) ? array('attributes' => array('title' => format_plural($node->comment_count, '1 comment', '@count comments'))) : array());
  271. $num_rows = TRUE;
  272. }
  273. return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
  274. }
  275. /**
  276. * Updates the 'last viewed' timestamp of the specified node for current user.
  277. *
  278. * @param $node
  279. * A node object.
  280. */
  281. function node_tag_new($node) {
  282. global $user;
  283. if ($user->uid) {
  284. db_merge('history')
  285. ->key(array(
  286. 'uid' => $user->uid,
  287. 'nid' => $node->nid,
  288. ))
  289. ->fields(array('timestamp' => REQUEST_TIME))
  290. ->execute();
  291. }
  292. }
  293. /**
  294. * Retrieves the timestamp for the current user's last view of a specified node.
  295. *
  296. * @param $nid
  297. * A node ID.
  298. *
  299. * @return
  300. * If a node has been previously viewed by the user, the timestamp in seconds
  301. * of when the last view occurred; otherwise, zero.
  302. */
  303. function node_last_viewed($nid) {
  304. global $user;
  305. $history = &drupal_static(__FUNCTION__, array());
  306. if (!isset($history[$nid])) {
  307. $history[$nid] = db_query("SELECT timestamp FROM {history} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $nid))->fetchObject();
  308. }
  309. return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
  310. }
  311. /**
  312. * Determines the type of marker to be displayed for a given node.
  313. *
  314. * @param $nid
  315. * Node ID whose history supplies the "last viewed" timestamp.
  316. * @param $timestamp
  317. * Time which is compared against node's "last viewed" timestamp.
  318. *
  319. * @return
  320. * One of the MARK constants.
  321. */
  322. function node_mark($nid, $timestamp) {
  323. global $user;
  324. $cache = &drupal_static(__FUNCTION__, array());
  325. if (!$user->uid) {
  326. return MARK_READ;
  327. }
  328. if (!isset($cache[$nid])) {
  329. $cache[$nid] = node_last_viewed($nid);
  330. }
  331. if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
  332. return MARK_NEW;
  333. }
  334. elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
  335. return MARK_UPDATED;
  336. }
  337. return MARK_READ;
  338. }
  339. /**
  340. * Extracts the type name.
  341. *
  342. * @param $node
  343. * Either a string or object, containing the node type information.
  344. *
  345. * @return
  346. * Node type of the passed-in data.
  347. */
  348. function _node_extract_type($node) {
  349. return is_object($node) ? $node->type : $node;
  350. }
  351. /**
  352. * Returns a list of all the available node types.
  353. *
  354. * This list can include types that are queued for addition or deletion.
  355. * See _node_types_build() for details.
  356. *
  357. * @return
  358. * An array of node types, as objects, keyed by the type.
  359. *
  360. * @see node_type_get_type()
  361. */
  362. function node_type_get_types() {
  363. return _node_types_build()->types;
  364. }
  365. /**
  366. * Returns the node type of the passed node or node type string.
  367. *
  368. * @param $node
  369. * A node object or string that indicates the node type to return.
  370. *
  371. * @return
  372. * A single node type, as an object, or FALSE if the node type is not found.
  373. * The node type is an object containing fields from hook_node_info() return
  374. * values, as well as the field 'type' (the machine-readable type) and other
  375. * fields used internally and defined in _node_types_build(),
  376. * hook_node_info(), and node_type_set_defaults().
  377. */
  378. function node_type_get_type($node) {
  379. $type = _node_extract_type($node);
  380. $types = _node_types_build()->types;
  381. return isset($types[$type]) ? $types[$type] : FALSE;
  382. }
  383. /**
  384. * Returns the node type base of the passed node or node type string.
  385. *
  386. * The base indicates which module implements this node type and is used to
  387. * execute node-type-specific hooks. For types defined in the user interface
  388. * and managed by node.module, the base is 'node_content'.
  389. *
  390. * @param $node
  391. * A node object or string that indicates the node type to return.
  392. *
  393. * @return
  394. * The node type base or FALSE if the node type is not found.
  395. *
  396. * @see node_invoke()
  397. */
  398. function node_type_get_base($node) {
  399. $type = _node_extract_type($node);
  400. $types = _node_types_build()->types;
  401. return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE;
  402. }
  403. /**
  404. * Returns a list of available node type names.
  405. *
  406. * This list can include types that are queued for addition or deletion.
  407. * See _node_types_build() for details.
  408. *
  409. * @return
  410. * An array of node type names, keyed by the type.
  411. */
  412. function node_type_get_names() {
  413. return _node_types_build()->names;
  414. }
  415. /**
  416. * Returns the node type name of the passed node or node type string.
  417. *
  418. * @param $node
  419. * A node object or string that indicates the node type to return.
  420. *
  421. * @return
  422. * The node type name or FALSE if the node type is not found.
  423. */
  424. function node_type_get_name($node) {
  425. $type = _node_extract_type($node);
  426. $types = _node_types_build()->names;
  427. return isset($types[$type]) ? $types[$type] : FALSE;
  428. }
  429. /**
  430. * Updates the database cache of node types.
  431. *
  432. * All new module-defined node types are saved to the database via a call to
  433. * node_type_save(), and obsolete ones are deleted via a call to
  434. * node_type_delete(). See _node_types_build() for an explanation of the new
  435. * and obsolete types.
  436. *
  437. * @see _node_types_build()
  438. */
  439. function node_types_rebuild() {
  440. _node_types_build(TRUE);
  441. }
  442. /**
  443. * Menu argument loader: loads a node type by string.
  444. *
  445. * @param $name
  446. * The machine-readable name of a node type to load, where '_' is replaced
  447. * with '-'.
  448. *
  449. * @return
  450. * A node type object or FALSE if $name does not exist.
  451. */
  452. function node_type_load($name) {
  453. return node_type_get_type(strtr($name, array('-' => '_')));
  454. }
  455. /**
  456. * Saves a node type to the database.
  457. *
  458. * @param object $info
  459. * The node type to save; an object with the following properties:
  460. * - type: A string giving the machine name of the node type.
  461. * - name: A string giving the human-readable name of the node type.
  462. * - base: A string that indicates the base string for hook functions. For
  463. * example, 'node_content' is the value used by the UI when creating a new
  464. * node type.
  465. * - description: A string that describes the node type.
  466. * - help: A string giving the help information shown to the user when
  467. * creating a node of this type.
  468. * - custom: TRUE or FALSE indicating whether this type is defined by a module
  469. * (FALSE) or by a user (TRUE) via Add Content Type.
  470. * - modified: TRUE or FALSE indicating whether this type has been modified by
  471. * an administrator. Currently not used in any way.
  472. * - locked: TRUE or FALSE indicating whether the administrator can change the
  473. * machine name of this type.
  474. * - disabled: TRUE or FALSE indicating whether this type has been disabled.
  475. * - has_title: TRUE or FALSE indicating whether this type uses the node title
  476. * field.
  477. * - title_label: A string containing the label for the title.
  478. * - module: A string giving the module defining this type of node.
  479. * - orig_type: A string giving the original machine-readable name of this
  480. * node type. This may be different from the current type name if the
  481. * 'locked' key is FALSE.
  482. *
  483. * @return int
  484. * A status flag indicating the outcome of the operation, either SAVED_NEW or
  485. * SAVED_UPDATED.
  486. */
  487. function node_type_save($info) {
  488. $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
  489. $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
  490. $type = node_type_set_defaults($info);
  491. $fields = array(
  492. 'type' => (string) $type->type,
  493. 'name' => (string) $type->name,
  494. 'base' => (string) $type->base,
  495. 'has_title' => (int) $type->has_title,
  496. 'title_label' => (string) $type->title_label,
  497. 'description' => (string) $type->description,
  498. 'help' => (string) $type->help,
  499. 'custom' => (int) $type->custom,
  500. 'modified' => (int) $type->modified,
  501. 'locked' => (int) $type->locked,
  502. 'disabled' => (int) $type->disabled,
  503. 'module' => $type->module,
  504. );
  505. if ($is_existing) {
  506. db_update('node_type')
  507. ->fields($fields)
  508. ->condition('type', $existing_type)
  509. ->execute();
  510. if (!empty($type->old_type) && $type->old_type != $type->type) {
  511. field_attach_rename_bundle('node', $type->old_type, $type->type);
  512. }
  513. module_invoke_all('node_type_update', $type);
  514. $status = SAVED_UPDATED;
  515. }
  516. else {
  517. $fields['orig_type'] = (string) $type->orig_type;
  518. db_insert('node_type')
  519. ->fields($fields)
  520. ->execute();
  521. field_attach_create_bundle('node', $type->type);
  522. module_invoke_all('node_type_insert', $type);
  523. $status = SAVED_NEW;
  524. }
  525. // Clear the node type cache.
  526. node_type_cache_reset();
  527. return $status;
  528. }
  529. /**
  530. * Adds default body field to a node type.
  531. *
  532. * @param $type
  533. * A node type object.
  534. * @param $label
  535. * The label for the body instance.
  536. *
  537. * @return
  538. * Body field instance.
  539. */
  540. function node_add_body_field($type, $label = 'Body') {
  541. // Add or remove the body field, as needed.
  542. $field = field_info_field('body');
  543. $instance = field_info_instance('node', 'body', $type->type);
  544. if (empty($field)) {
  545. $field = array(
  546. 'field_name' => 'body',
  547. 'type' => 'text_with_summary',
  548. 'entity_types' => array('node'),
  549. );
  550. $field = field_create_field($field);
  551. }
  552. if (empty($instance)) {
  553. $instance = array(
  554. 'field_name' => 'body',
  555. 'entity_type' => 'node',
  556. 'bundle' => $type->type,
  557. 'label' => $label,
  558. 'widget' => array('type' => 'text_textarea_with_summary'),
  559. 'settings' => array('display_summary' => TRUE),
  560. 'display' => array(
  561. 'default' => array(
  562. 'label' => 'hidden',
  563. 'type' => 'text_default',
  564. ),
  565. 'teaser' => array(
  566. 'label' => 'hidden',
  567. 'type' => 'text_summary_or_trimmed',
  568. ),
  569. ),
  570. );
  571. $instance = field_create_instance($instance);
  572. }
  573. return $instance;
  574. }
  575. /**
  576. * Implements hook_field_extra_fields().
  577. */
  578. function node_field_extra_fields() {
  579. $extra = array();
  580. foreach (node_type_get_types() as $type) {
  581. if ($type->has_title) {
  582. $extra['node'][$type->type] = array(
  583. 'form' => array(
  584. 'title' => array(
  585. 'label' => $type->title_label,
  586. 'description' => t('Node module element'),
  587. 'weight' => -5,
  588. ),
  589. ),
  590. );
  591. }
  592. }
  593. return $extra;
  594. }
  595. /**
  596. * Deletes a node type from the database.
  597. *
  598. * @param $type
  599. * The machine-readable name of the node type to be deleted.
  600. */
  601. function node_type_delete($type) {
  602. $info = node_type_get_type($type);
  603. db_delete('node_type')
  604. ->condition('type', $type)
  605. ->execute();
  606. field_attach_delete_bundle('node', $type);
  607. module_invoke_all('node_type_delete', $info);
  608. // Clear the node type cache.
  609. node_type_cache_reset();
  610. }
  611. /**
  612. * Updates all nodes of one type to be of another type.
  613. *
  614. * @param $old_type
  615. * The current node type of the nodes.
  616. * @param $type
  617. * The new node type of the nodes.
  618. *
  619. * @return
  620. * The number of nodes whose node type field was modified.
  621. */
  622. function node_type_update_nodes($old_type, $type) {
  623. return db_update('node')
  624. ->fields(array('type' => $type))
  625. ->condition('type', $old_type)
  626. ->execute();
  627. }
  628. /**
  629. * Builds and returns the list of available node types.
  630. *
  631. * The list of types is built by invoking hook_node_info() on all modules and
  632. * comparing this information with the node types in the {node_type} table.
  633. * These two information sources are not synchronized during module installation
  634. * until node_types_rebuild() is called.
  635. *
  636. * @param $rebuild
  637. * TRUE to rebuild node types. Equivalent to calling node_types_rebuild().
  638. *
  639. * @return
  640. * An object with two properties:
  641. * - names: Associative array of the names of node types, keyed by the type.
  642. * - types: Associative array of node type objects, keyed by the type.
  643. * Both of these arrays will include new types that have been defined by
  644. * hook_node_info() implementations but not yet saved in the {node_type}
  645. * table. These are indicated in the type object by $type->is_new being set
  646. * to the value 1. These arrays will also include obsolete types: types that
  647. * were previously defined by modules that have now been disabled, or for
  648. * whatever reason are no longer being defined in hook_node_info()
  649. * implementations, but are still in the database. These are indicated in the
  650. * type object by $type->disabled being set to TRUE.
  651. */
  652. function _node_types_build($rebuild = FALSE) {
  653. $cid = 'node_types:' . $GLOBALS['language']->language;
  654. if (!$rebuild) {
  655. $_node_types = &drupal_static(__FUNCTION__);
  656. if (isset($_node_types)) {
  657. return $_node_types;
  658. }
  659. if ($cache = cache_get($cid)) {
  660. $_node_types = $cache->data;
  661. return $_node_types;
  662. }
  663. }
  664. $_node_types = (object) array('types' => array(), 'names' => array());
  665. foreach (module_implements('node_info') as $module) {
  666. $info_array = module_invoke($module, 'node_info');
  667. foreach ($info_array as $type => $info) {
  668. $info['type'] = $type;
  669. $_node_types->types[$type] = node_type_set_defaults($info);
  670. $_node_types->types[$type]->module = $module;
  671. $_node_types->names[$type] = $info['name'];
  672. }
  673. }
  674. $query = db_select('node_type', 'nt')
  675. ->addTag('translatable')
  676. ->addTag('node_type_access')
  677. ->fields('nt')
  678. ->orderBy('nt.type', 'ASC');
  679. if (!$rebuild) {
  680. $query->condition('disabled', 0);
  681. }
  682. foreach ($query->execute() as $type_object) {
  683. $type_db = $type_object->type;
  684. // Original disabled value.
  685. $disabled = $type_object->disabled;
  686. // Check for node types from disabled modules and mark their types for removal.
  687. // Types defined by the node module in the database (rather than by a separate
  688. // module using hook_node_info) have a base value of 'node_content'. The isset()
  689. // check prevents errors on old (pre-Drupal 7) databases.
  690. if (isset($type_object->base) && $type_object->base != 'node_content' && empty($_node_types->types[$type_db])) {
  691. $type_object->disabled = TRUE;
  692. }
  693. if (isset($_node_types->types[$type_db])) {
  694. $type_object->disabled = FALSE;
  695. }
  696. if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
  697. $_node_types->types[$type_db] = $type_object;
  698. $_node_types->names[$type_db] = $type_object->name;
  699. if ($type_db != $type_object->orig_type) {
  700. unset($_node_types->types[$type_object->orig_type]);
  701. unset($_node_types->names[$type_object->orig_type]);
  702. }
  703. }
  704. $_node_types->types[$type_db]->disabled = $type_object->disabled;
  705. $_node_types->types[$type_db]->disabled_changed = $disabled != $type_object->disabled;
  706. }
  707. if ($rebuild) {
  708. foreach ($_node_types->types as $type => $type_object) {
  709. if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
  710. node_type_save($type_object);
  711. }
  712. }
  713. }
  714. asort($_node_types->names);
  715. cache_set($cid, $_node_types);
  716. return $_node_types;
  717. }
  718. /**
  719. * Clears the node type cache.
  720. */
  721. function node_type_cache_reset() {
  722. cache_clear_all('node_types:', 'cache', TRUE);
  723. drupal_static_reset('_node_types_build');
  724. }
  725. /**
  726. * Sets the default values for a node type.
  727. *
  728. * The defaults are appropriate for a type defined through hook_node_info(),
  729. * since 'custom' is TRUE for types defined in the user interface, and FALSE
  730. * for types defined by modules. (The 'custom' flag prevents types from being
  731. * deleted through the user interface.) Also, the default for 'locked' is TRUE,
  732. * which prevents users from changing the machine name of the type.
  733. *
  734. * @param $info
  735. * (optional) An object or array containing values to override the defaults.
  736. * See hook_node_info() for details on what the array elements mean. Defaults
  737. * to an empty array.
  738. *
  739. * @return
  740. * A node type object, with missing values in $info set to their defaults.
  741. */
  742. function node_type_set_defaults($info = array()) {
  743. $info = (array) $info;
  744. $new_type = $info + array(
  745. 'type' => '',
  746. 'name' => '',
  747. 'base' => '',
  748. 'description' => '',
  749. 'help' => '',
  750. 'custom' => 0,
  751. 'modified' => 0,
  752. 'locked' => 1,
  753. 'disabled' => 0,
  754. 'is_new' => 1,
  755. 'has_title' => 1,
  756. 'title_label' => 'Title',
  757. );
  758. $new_type = (object) $new_type;
  759. // If the type has no title, set an empty label.
  760. if (!$new_type->has_title) {
  761. $new_type->title_label = '';
  762. }
  763. if (empty($new_type->module)) {
  764. $new_type->module = $new_type->base == 'node_content' ? 'node' : '';
  765. }
  766. $new_type->orig_type = isset($info['type']) ? $info['type'] : '';
  767. return $new_type;
  768. }
  769. /**
  770. * Implements hook_rdf_mapping().
  771. */
  772. function node_rdf_mapping() {
  773. return array(
  774. array(
  775. 'type' => 'node',
  776. 'bundle' => RDF_DEFAULT_BUNDLE,
  777. 'mapping' => array(
  778. 'rdftype' => array('sioc:Item', 'foaf:Document'),
  779. 'title' => array(
  780. 'predicates' => array('dc:title'),
  781. ),
  782. 'created' => array(
  783. 'predicates' => array('dc:date', 'dc:created'),
  784. 'datatype' => 'xsd:dateTime',
  785. 'callback' => 'date_iso8601',
  786. ),
  787. 'changed' => array(
  788. 'predicates' => array('dc:modified'),
  789. 'datatype' => 'xsd:dateTime',
  790. 'callback' => 'date_iso8601',
  791. ),
  792. 'body' => array(
  793. 'predicates' => array('content:encoded'),
  794. ),
  795. 'uid' => array(
  796. 'predicates' => array('sioc:has_creator'),
  797. 'type' => 'rel',
  798. ),
  799. 'name' => array(
  800. 'predicates' => array('foaf:name'),
  801. ),
  802. 'comment_count' => array(
  803. 'predicates' => array('sioc:num_replies'),
  804. 'datatype' => 'xsd:integer',
  805. ),
  806. 'last_activity' => array(
  807. 'predicates' => array('sioc:last_activity_date'),
  808. 'datatype' => 'xsd:dateTime',
  809. 'callback' => 'date_iso8601',
  810. ),
  811. ),
  812. ),
  813. );
  814. }
  815. /**
  816. * Determines whether a node hook exists.
  817. *
  818. * @param $node
  819. * A node object or a string containing the node type.
  820. * @param $hook
  821. * A string containing the name of the hook.
  822. *
  823. * @return
  824. * TRUE if the $hook exists in the node type of $node.
  825. */
  826. function node_hook($node, $hook) {
  827. $base = node_type_get_base($node);
  828. return module_hook($base, $hook);
  829. }
  830. /**
  831. * Invokes a node hook.
  832. *
  833. * @param $node
  834. * A node object or a string containing the node type.
  835. * @param $hook
  836. * A string containing the name of the hook.
  837. * @param $a2, $a3, $a4
  838. * Arguments to pass on to the hook, after the $node argument.
  839. *
  840. * @return
  841. * The returned value of the invoked hook.
  842. */
  843. function node_invoke($node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
  844. if (node_hook($node, $hook)) {
  845. $base = node_type_get_base($node);
  846. $function = $base . '_' . $hook;
  847. return ($function($node, $a2, $a3, $a4));
  848. }
  849. }
  850. /**
  851. * Loads node entities from the database.
  852. *
  853. * This function should be used whenever you need to load more than one node
  854. * from the database. Nodes are loaded into memory and will not require database
  855. * access if loaded again during the same page request.
  856. *
  857. * @see entity_load()
  858. * @see EntityFieldQuery
  859. *
  860. * @param $nids
  861. * An array of node IDs.
  862. * @param $conditions
  863. * (deprecated) An associative array of conditions on the {node}
  864. * table, where the keys are the database fields and the values are the
  865. * values those fields must have. Instead, it is preferable to use
  866. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  867. * this function.
  868. * @param $reset
  869. * Whether to reset the internal node_load cache.
  870. *
  871. * @return
  872. * An array of node objects indexed by nid.
  873. *
  874. * @todo Remove $conditions in Drupal 8.
  875. */
  876. function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) {
  877. return entity_load('node', $nids, $conditions, $reset);
  878. }
  879. /**
  880. * Loads a node object from the database.
  881. *
  882. * @param $nid
  883. * The node ID.
  884. * @param $vid
  885. * The revision ID.
  886. * @param $reset
  887. * Whether to reset the node_load_multiple cache.
  888. *
  889. * @return
  890. * A fully-populated node object, or FALSE if the node is not found.
  891. */
  892. function node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
  893. $nids = (isset($nid) ? array($nid) : array());
  894. $conditions = (isset($vid) ? array('vid' => $vid) : array());
  895. $node = node_load_multiple($nids, $conditions, $reset);
  896. return $node ? reset($node) : FALSE;
  897. }
  898. /**
  899. * Prepares a node object for editing.
  900. *
  901. * Fills in a few default values, and then invokes hook_prepare() on the node
  902. * type module, and hook_node_prepare() on all modules.
  903. *
  904. * @param $node
  905. * A node object.
  906. */
  907. function node_object_prepare($node) {
  908. // Set up default values, if required.
  909. $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
  910. // If this is a new node, fill in the default values.
  911. if (!isset($node->nid) || isset($node->is_new)) {
  912. foreach (array('status', 'promote', 'sticky') as $key) {
  913. // Multistep node forms might have filled in something already.
  914. if (!isset($node->$key)) {
  915. $node->$key = (int) in_array($key, $node_options);
  916. }
  917. }
  918. global $user;
  919. $node->uid = $user->uid;
  920. $node->created = REQUEST_TIME;
  921. }
  922. else {
  923. $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
  924. // Remove the log message from the original node object.
  925. $node->log = NULL;
  926. }
  927. // Always use the default revision setting.
  928. $node->revision = in_array('revision', $node_options);
  929. node_invoke($node, 'prepare');
  930. module_invoke_all('node_prepare', $node);
  931. }
  932. /**
  933. * Implements hook_validate().
  934. *
  935. * Performs validation checks on the given node.
  936. */
  937. function node_validate($node, $form, &$form_state) {
  938. if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  939. form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  940. }
  941. // Validate the "authored by" field.
  942. if (!empty($node->name) && !($account = user_load_by_name($node->name))) {
  943. // The use of empty() is mandatory in the context of usernames
  944. // as the empty string denotes the anonymous user. In case we
  945. // are dealing with an anonymous user we set the user ID to 0.
  946. form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
  947. }
  948. // Validate the "authored on" field.
  949. if (!empty($node->date) && strtotime($node->date) === FALSE) {
  950. form_set_error('date', t('You have to specify a valid date.'));
  951. }
  952. // Invoke hook_validate() for node type specific validation and
  953. // hook_node_validate() for miscellaneous validation needed by modules. Can't
  954. // use node_invoke() or module_invoke_all(), because $form_state must be
  955. // receivable by reference.
  956. $function = node_type_get_base($node) . '_validate';
  957. if (function_exists($function)) {
  958. $function($node, $form, $form_state);
  959. }
  960. foreach (module_implements('node_validate') as $module) {
  961. $function = $module . '_node_validate';
  962. $function($node, $form, $form_state);
  963. }
  964. }
  965. /**
  966. * Prepares node for saving by populating author and creation date.
  967. *
  968. * @param $node
  969. * A node object.
  970. *
  971. * @return
  972. * An updated node object.
  973. */
  974. function node_submit($node) {
  975. // A user might assign the node author by entering a user name in the node
  976. // form, which we then need to translate to a user ID.
  977. if (isset($node->name)) {
  978. if ($account = user_load_by_name($node->name)) {
  979. $node->uid = $account->uid;
  980. }
  981. else {
  982. $node->uid = 0;
  983. }
  984. }
  985. $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
  986. $node->validated = TRUE;
  987. return $node;
  988. }
  989. /**
  990. * Saves changes to a node or adds a new node.
  991. *
  992. * @param $node
  993. * The $node object to be saved. If $node->nid is
  994. * omitted (or $node->is_new is TRUE), a new node will be added.
  995. */
  996. function node_save($node) {
  997. $transaction = db_transaction();
  998. try {
  999. // Load the stored entity, if any.
  1000. if (!empty($node->nid) && !isset($node->original)) {
  1001. $node->original = entity_load_unchanged('node', $node->nid);
  1002. }
  1003. field_attach_presave('node', $node);
  1004. global $user;
  1005. // Determine if we will be inserting a new node.
  1006. if (!isset($node->is_new)) {
  1007. $node->is_new = empty($node->nid);
  1008. }
  1009. // Set the timestamp fields.
  1010. if (empty($node->created)) {
  1011. $node->created = REQUEST_TIME;
  1012. }
  1013. // The changed timestamp is always updated for bookkeeping purposes,
  1014. // for example: revisions, searching, etc.
  1015. $node->changed = REQUEST_TIME;
  1016. $node->timestamp = REQUEST_TIME;
  1017. $update_node = TRUE;
  1018. // Let modules modify the node before it is saved to the database.
  1019. module_invoke_all('node_presave', $node);
  1020. module_invoke_all('entity_presave', $node, 'node');
  1021. if ($node->is_new || !empty($node->revision)) {
  1022. // When inserting either a new node or a new node revision, $node->log
  1023. // must be set because {node_revision}.log is a text column and therefore
  1024. // cannot have a default value. However, it might not be set at this
  1025. // point (for example, if the user submitting a node form does not have
  1026. // permission to create revisions), so we ensure that it is at least an
  1027. // empty string in that case.
  1028. // @todo: Make the {node_revision}.log column nullable so that we can
  1029. // remove this check.
  1030. if (!isset($node->log)) {
  1031. $node->log = '';
  1032. }
  1033. }
  1034. elseif (!isset($node->log) || $node->log === '') {
  1035. // If we are updating an existing node without adding a new revision, we
  1036. // need to make sure $node->log is unset whenever it is empty. As long as
  1037. // $node->log is unset, drupal_write_record() will not attempt to update
  1038. // the existing database column when re-saving the revision; therefore,
  1039. // this code allows us to avoid clobbering an existing log entry with an
  1040. // empty one.
  1041. unset($node->log);
  1042. }
  1043. // When saving a new node revision, unset any existing $node->vid so as to
  1044. // ensure that a new revision will actually be created, then store the old
  1045. // revision ID in a separate property for use by node hook implementations.
  1046. if (!$node->is_new && !empty($node->revision) && $node->vid) {
  1047. $node->old_vid = $node->vid;
  1048. unset($node->vid);
  1049. }
  1050. // Save the node and node revision.
  1051. if ($node->is_new) {
  1052. // For new nodes, save new records for both the node itself and the node
  1053. // revision.
  1054. drupal_write_record('node', $node);
  1055. _node_save_revision($node, $user->uid);
  1056. $op = 'insert';
  1057. }
  1058. else {
  1059. // For existing nodes, update the node record which matches the value of
  1060. // $node->nid.
  1061. drupal_write_record('node', $node, 'nid');
  1062. // Then, if a new node revision was requested, save a new record for
  1063. // that; otherwise, update the node revision record which matches the
  1064. // value of $node->vid.
  1065. if (!empty($node->revision)) {
  1066. _node_save_revision($node, $user->uid);
  1067. }
  1068. else {
  1069. _node_save_revision($node, $user->uid, 'vid');
  1070. $update_node = FALSE;
  1071. }
  1072. $op = 'update';
  1073. }
  1074. if ($update_node) {
  1075. db_update('node')
  1076. ->fields(array('vid' => $node->vid))
  1077. ->condition('nid', $node->nid)
  1078. ->execute();
  1079. }
  1080. // Call the node specific callback (if any). This can be
  1081. // node_invoke($node, 'insert') or
  1082. // node_invoke($node, 'update').
  1083. node_invoke($node, $op);
  1084. // Save fields.
  1085. $function = "field_attach_$op";
  1086. $function('node', $node);
  1087. module_invoke_all('node_' . $op, $node);
  1088. module_invoke_all('entity_' . $op, $node, 'node');
  1089. // Update the node access table for this node. There's no need to delete
  1090. // existing records if the node is new.
  1091. $delete = $op == 'update';
  1092. node_access_acquire_grants($node, $delete);
  1093. // Clear internal properties.
  1094. unset($node->is_new);
  1095. unset($node->original);
  1096. // Clear the static loading cache.
  1097. entity_get_controller('node')->resetCache(array($node->nid));
  1098. // Ignore slave server temporarily to give time for the
  1099. // saved node to be propagated to the slave.
  1100. db_ignore_slave();
  1101. }
  1102. catch (Exception $e) {
  1103. $transaction->rollback();
  1104. watchdog_exception('node', $e);
  1105. throw $e;
  1106. }
  1107. }
  1108. /**
  1109. * Helper function to save a revision with the uid of the current user.
  1110. *
  1111. * The resulting revision ID is available afterward in $node->vid.
  1112. *
  1113. * @param $node
  1114. * A node object.
  1115. * @param $uid
  1116. * The current user's UID.
  1117. * @param $update
  1118. * (optional) An array of primary keys' field names to update.
  1119. */
  1120. function _node_save_revision($node, $uid, $update = NULL) {
  1121. $temp_uid = $node->uid;
  1122. $node->uid = $uid;
  1123. if (isset($update)) {
  1124. drupal_write_record('node_revision', $node, $update);
  1125. }
  1126. else {
  1127. drupal_write_record('node_revision', $node);
  1128. }
  1129. // Have node object still show node owner's uid, not revision author's.
  1130. $node->uid = $temp_uid;
  1131. }
  1132. /**
  1133. * Deletes a node.
  1134. *
  1135. * @param $nid
  1136. * A node ID.
  1137. */
  1138. function node_delete($nid) {
  1139. node_delete_multiple(array($nid));
  1140. }
  1141. /**
  1142. * Deletes multiple nodes.
  1143. *
  1144. * @param $nids
  1145. * An array of node IDs.
  1146. */
  1147. function node_delete_multiple($nids) {
  1148. $transaction = db_transaction();
  1149. if (!empty($nids)) {
  1150. $nodes = node_load_multiple($nids, array());
  1151. try {
  1152. foreach ($nodes as $nid => $node) {
  1153. // Call the node-specific callback (if any):
  1154. node_invoke($node, 'delete');
  1155. module_invoke_all('node_delete', $node);
  1156. module_invoke_all('entity_delete', $node, 'node');
  1157. field_attach_delete('node', $node);
  1158. // Remove this node from the search index if needed.
  1159. // This code is implemented in node module rather than in search module,
  1160. // because node module is implementing search module's API, not the other
  1161. // way around.
  1162. if (module_exists('search')) {
  1163. search_reindex($nid, 'node');
  1164. }
  1165. }
  1166. // Delete after calling hooks so that they can query node tables as needed.
  1167. db_delete('node')
  1168. ->condition('nid', $nids, 'IN')
  1169. ->execute();
  1170. db_delete('node_revision')
  1171. ->condition('nid', $nids, 'IN')
  1172. ->execute();
  1173. db_delete('history')
  1174. ->condition('nid', $nids, 'IN')
  1175. ->execute();
  1176. db_delete('node_access')
  1177. ->condition('nid', $nids, 'IN')
  1178. ->execute();
  1179. }
  1180. catch (Exception $e) {
  1181. $transaction->rollback();
  1182. watchdog_exception('node', $e);
  1183. throw $e;
  1184. }
  1185. // Clear the page and block and node_load_multiple caches.
  1186. entity_get_controller('node')->resetCache();
  1187. }
  1188. }
  1189. /**
  1190. * Deletes a node revision.
  1191. *
  1192. * @param $revision_id
  1193. * The revision ID to delete.
  1194. */
  1195. function node_revision_delete($revision_id) {
  1196. if ($revision = node_load(NULL, $revision_id)) {
  1197. // Prevent deleting the current revision.
  1198. $node = node_load($revision->nid);
  1199. if ($revision_id == $node->vid) {
  1200. return FALSE;
  1201. }
  1202. db_delete('node_revision')
  1203. ->condition('nid', $revision->nid)
  1204. ->condition('vid', $revision->vid)
  1205. ->execute();
  1206. module_invoke_all('node_revision_delete', $revision);
  1207. field_attach_delete_revision('node', $revision);
  1208. return TRUE;
  1209. }
  1210. return FALSE;
  1211. }
  1212. /**
  1213. * Generates an array for rendering the given node.
  1214. *
  1215. * @param $node
  1216. * A node object.
  1217. * @param $view_mode
  1218. * View mode, e.g. 'full', 'teaser'...
  1219. * @param $langcode
  1220. * (optional) A language code to use for rendering. Defaults to the global
  1221. * content language of the current request.
  1222. *
  1223. * @return
  1224. * An array as expected by drupal_render().
  1225. */
  1226. function node_view($node, $view_mode = 'full', $langcode = NULL) {
  1227. if (!isset($langcode)) {
  1228. $langcode = $GLOBALS['language_content']->language;
  1229. }
  1230. // Populate $node->content with a render() array.
  1231. node_build_content($node, $view_mode, $langcode);
  1232. $build = $node->content;
  1233. // We don't need duplicate rendering info in node->content.
  1234. unset($node->content);
  1235. $build += array(
  1236. '#theme' => 'node',
  1237. '#node' => $node,
  1238. '#view_mode' => $view_mode,
  1239. '#language' => $langcode,
  1240. );
  1241. // Add contextual links for this node, except when the node is already being
  1242. // displayed on its own page. Modules may alter this behavior (for example,
  1243. // to restrict contextual links to certain view modes) by implementing
  1244. // hook_node_view_alter().
  1245. if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
  1246. $build['#contextual_links']['node'] = array('node', array($node->nid));
  1247. }
  1248. // Allow modules to modify the structured node.
  1249. $type = 'node';
  1250. drupal_alter(array('node_view', 'entity_view'), $build, $type);
  1251. return $build;
  1252. }
  1253. /**
  1254. * Builds a structured array representing the node's content.
  1255. *
  1256. * The content built for the node (field values, comments, file attachments or
  1257. * other node components) will vary depending on the $view_mode parameter.
  1258. *
  1259. * Drupal core defines the following view modes for nodes, with the following
  1260. * default use cases:
  1261. * - full (default): node is being displayed on its own page (node/123)
  1262. * - teaser: node is being displayed on the default home page listing, on
  1263. * taxonomy listing pages, or on blog listing pages.
  1264. * - rss: node displayed in an RSS feed.
  1265. * If search.module is enabled:
  1266. * - search_index: node is being indexed for search.
  1267. * - search_result: node is being displayed as a search result.
  1268. * If book.module is enabled:
  1269. * - print: node is being displayed in print-friendly mode.
  1270. * Contributed modules might define additional view modes, or use existing
  1271. * view modes in additional contexts.
  1272. *
  1273. * @param $node
  1274. * A node object.
  1275. * @param $view_mode
  1276. * View mode, e.g. 'full', 'teaser'...
  1277. * @param $langcode
  1278. * (optional) A language code to use for rendering. Defaults to the global
  1279. * content language of the current request.
  1280. */
  1281. function node_build_content($node, $view_mode = 'full', $langcode = NULL) {
  1282. if (!isset($langcode)) {
  1283. $langcode = $GLOBALS['language_content']->language;
  1284. }
  1285. // Remove previously built content, if exists.
  1286. $node->content = array();
  1287. // Allow modules to change the view mode.
  1288. $context = array(
  1289. 'entity_type' => 'node',
  1290. 'entity' => $node,
  1291. 'langcode' => $langcode,
  1292. );
  1293. drupal_alter('entity_view_mode', $view_mode, $context);
  1294. // The 'view' hook can be implemented to overwrite the default function
  1295. // to display nodes.
  1296. if (node_hook($node, 'view')) {
  1297. $node = node_invoke($node, 'view', $view_mode, $langcode);
  1298. }
  1299. // Build fields content.
  1300. // In case of a multiple view, node_view_multiple() already ran the
  1301. // 'prepare_view' step. An internal flag prevents the operation from running
  1302. // twice.
  1303. field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
  1304. entity_prepare_view('node', array($node->nid => $node), $langcode);
  1305. $node->content += field_attach_view('node', $node, $view_mode, $langcode);
  1306. // Always display a read more link on teasers because we have no way to know
  1307. // when a teaser view is different than a full view.
  1308. $links = array();
  1309. $node->content['links'] = array(
  1310. '#theme' => 'links__node',
  1311. '#pre_render' => array('drupal_pre_render_links'),
  1312. '#attributes' => array('class' => array('links', 'inline')),
  1313. );
  1314. if ($view_mode == 'teaser') {
  1315. $node_title_stripped = strip_tags($node->title);
  1316. $links['node-readmore'] = array(
  1317. 'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),
  1318. 'href' => 'node/' . $node->nid,
  1319. 'html' => TRUE,
  1320. 'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped),
  1321. );
  1322. }
  1323. $node->content['links']['node'] = array(
  1324. '#theme' => 'links__node__node',
  1325. '#links' => $links,
  1326. '#attributes' => array('class' => array('links', 'inline')),
  1327. );
  1328. // Allow modules to make their own additions to the node.
  1329. module_invoke_all('node_view', $node, $view_mode, $langcode);
  1330. module_invoke_all('entity_view', $node, 'node', $view_mode, $langcode);
  1331. // Make sure the current view mode is stored if no module has already
  1332. // populated the related key.
  1333. $node->content += array('#view_mode' => $view_mode);
  1334. }
  1335. /**
  1336. * Generates an array which displays a node detail page.
  1337. *
  1338. * @param $node
  1339. * A node object.
  1340. * @param $message
  1341. * A flag which sets a page title relevant to the revision being viewed.
  1342. *
  1343. * @return
  1344. * A $page element suitable for use by drupal_render().
  1345. */
  1346. function node_show($node, $message = FALSE) {
  1347. if ($message) {
  1348. drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
  1349. }
  1350. // For markup consistency with other pages, use node_view_multiple() rather than node_view().
  1351. $nodes = node_view_multiple(array($node->nid => $node), 'full');
  1352. // Update the history table, stating that this user viewed this node.
  1353. node_tag_new($node);
  1354. return $nodes;
  1355. }
  1356. /**
  1357. * Returns whether the current page is the full page view of the passed-in node.
  1358. *
  1359. * @param $node
  1360. * A node object.
  1361. *
  1362. * @return
  1363. * The ID of the node if this is a full page view, otherwise FALSE.
  1364. */
  1365. function node_is_page($node) {
  1366. $page_node = menu_get_object();
  1367. return (!empty($page_node) ? $page_node->nid == $node->nid : FALSE);
  1368. }
  1369. /**
  1370. * Processes variables for node.tpl.php
  1371. *
  1372. * Most themes utilize their own copy of node.tpl.php. The default is located
  1373. * inside "modules/node/node.tpl.php". Look in there for the full list of
  1374. * variables.
  1375. *
  1376. * The $variables array contains the following arguments:
  1377. * - $node
  1378. * - $view_mode
  1379. * - $page
  1380. *
  1381. * @see node.tpl.php
  1382. */
  1383. function template_preprocess_node(&$variables) {
  1384. $variables['view_mode'] = $variables['elements']['#view_mode'];
  1385. // Provide a distinct $teaser boolean.
  1386. $variables['teaser'] = $variables['view_mode'] == 'teaser';
  1387. $variables['node'] = $variables['elements']['#node'];
  1388. $node = $variables['node'];
  1389. $variables['date'] = format_date($node->created);
  1390. $variables['name'] = theme('username', array('account' => $node));
  1391. $uri = entity_uri('node', $node);
  1392. $variables['node_url'] = url($uri['path'], $uri['options']);
  1393. $variables['title'] = check_plain($node->title);
  1394. $variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);
  1395. // Flatten the node object's member fields.
  1396. $variables = array_merge((array) $node, $variables);
  1397. // Helpful $content variable for templates.
  1398. $variables += array('content' => array());
  1399. foreach (element_children($variables['elements']) as $key) {
  1400. $variables['content'][$key] = $variables['elements'][$key];
  1401. }
  1402. // Make the field variables available with the appropriate language.
  1403. field_attach_preprocess('node', $node, $variables['content'], $variables);
  1404. // Display post information only on certain node types.
  1405. if (variable_get('node_submitted_' . $node->type, TRUE)) {
  1406. $variables['display_submitted'] = TRUE;
  1407. $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  1408. $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
  1409. }
  1410. else {
  1411. $variables['display_submitted'] = FALSE;
  1412. $variables['submitted'] = '';
  1413. $variables['user_picture'] = '';
  1414. }
  1415. // Gather node classes.
  1416. $variables['classes_array'][] = drupal_html_class('node-' . $node->type);
  1417. if ($variables['promote']) {
  1418. $variables['classes_array'][] = 'node-promoted';
  1419. }
  1420. if ($variables['sticky']) {
  1421. $variables['classes_array'][] = 'node-sticky';
  1422. }
  1423. if (!$variables['status']) {
  1424. $variables['classes_array'][] = 'node-unpublished';
  1425. }
  1426. if ($variables['teaser']) {
  1427. $variables['classes_array'][] = 'node-teaser';
  1428. }
  1429. if (isset($variables['preview'])) {
  1430. $variables['classes_array'][] = 'node-preview';
  1431. }
  1432. // Clean up name so there are no underscores.
  1433. $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
  1434. $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
  1435. }
  1436. /**
  1437. * Implements hook_permission().
  1438. */
  1439. function node_permission() {
  1440. $perms = array(
  1441. 'bypass node access' => array(
  1442. 'title' => t('Bypass content access control'),
  1443. 'description' => t('View, edit and delete all content regardless of permission restrictions.'),
  1444. 'restrict access' => TRUE,
  1445. ),
  1446. 'administer content types' => array(
  1447. 'title' => t('Administer content types'),
  1448. 'restrict access' => TRUE,
  1449. ),
  1450. 'administer nodes' => array(
  1451. 'title' => t('Administer content'),
  1452. 'restrict access' => TRUE,
  1453. ),
  1454. 'access content overview' => array(
  1455. 'title' => t('Access the content overview page'),
  1456. ),
  1457. 'access content' => array(
  1458. 'title' => t('View published content'),
  1459. ),
  1460. 'view own unpublished content' => array(
  1461. 'title' => t('View own unpublished content'),
  1462. ),
  1463. 'view revisions' => array(
  1464. 'title' => t('View content revisions'),
  1465. ),
  1466. 'revert revisions' => array(
  1467. 'title' => t('Revert content revisions'),
  1468. ),
  1469. 'delete revisions' => array(
  1470. 'title' => t('Delete content revisions'),
  1471. ),
  1472. );
  1473. // Generate standard node permissions for all applicable node types.
  1474. foreach (node_permissions_get_configured_types() as $type) {
  1475. $perms += node_list_permissions($type);
  1476. }
  1477. return $perms;
  1478. }
  1479. /**
  1480. * Gathers the rankings from the the hook_ranking() implementations.
  1481. *
  1482. * @param $query
  1483. * A query object that has been extended with the Search DB Extender.
  1484. */
  1485. function _node_rankings(SelectQueryExtender $query) {
  1486. if ($ranking = module_invoke_all('ranking')) {
  1487. $tables = &$query->getTables();
  1488. foreach ($ranking as $rank => $values) {
  1489. if ($node_rank = variable_get('node_rank_' . $rank, 0)) {
  1490. // If the table defined in the ranking isn't already joined, then add it.
  1491. if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
  1492. $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
  1493. }
  1494. $arguments = isset($values['arguments']) ? $values['arguments'] : array();
  1495. $query->addScore($values['score'], $arguments, $node_rank);
  1496. }
  1497. }
  1498. }
  1499. }
  1500. /**
  1501. * Implements hook_search_info().
  1502. */
  1503. function node_search_info() {
  1504. return array(
  1505. 'title' => 'Content',
  1506. 'path' => 'node',
  1507. );
  1508. }
  1509. /**
  1510. * Implements hook_search_access().
  1511. */
  1512. function node_search_access() {
  1513. return user_access('access content');
  1514. }
  1515. /**
  1516. * Implements hook_search_reset().
  1517. */
  1518. function node_search_reset() {
  1519. db_update('search_dataset')
  1520. ->fields(array('reindex' => REQUEST_TIME))
  1521. ->condition('type', 'node')
  1522. ->execute();
  1523. }
  1524. /**
  1525. * Implements hook_search_status().
  1526. */
  1527. function node_search_status() {
  1528. $total = db_query('SELECT COUNT(*) FROM {node}')->fetchField();
  1529. $remaining = db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0")->fetchField();
  1530. return array('remaining' => $remaining, 'total' => $total);
  1531. }
  1532. /**
  1533. * Implements hook_search_admin().
  1534. */
  1535. function node_search_admin() {
  1536. // Output form for defining rank factor weights.
  1537. $form['content_ranking'] = array(
  1538. '#type' => 'fieldset',
  1539. '#title' => t('Content ranking'),
  1540. );
  1541. $form['content_ranking']['#theme'] = 'node_search_admin';
  1542. $form['content_ranking']['info'] = array(
  1543. '#value' => '<em>' . t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em>'
  1544. );
  1545. // Note: reversed to reflect that higher number = higher ranking.
  1546. $options = drupal_map_assoc(range(0, 10));
  1547. foreach (module_invoke_all('ranking') as $var => $values) {
  1548. $form['content_ranking']['factors']['node_rank_' . $var] = array(
  1549. '#title' => $values['title'],
  1550. '#type' => 'select',
  1551. '#options' => $options,
  1552. '#default_value' => variable_get('node_rank_' . $var, 0),
  1553. );
  1554. }
  1555. return $form;
  1556. }
  1557. /**
  1558. * Implements hook_search_execute().
  1559. */
  1560. function node_search_execute($keys = NULL, $conditions = NULL) {
  1561. // Build matching conditions
  1562. $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
  1563. $query->join('node', 'n', 'n.nid = i.sid');
  1564. $query
  1565. ->condition('n.status', 1)
  1566. ->addTag('node_access')
  1567. ->searchExpression($keys, 'node');
  1568. // Insert special keywords.
  1569. $query->setOption('type', 'n.type');
  1570. $query->setOption('language', 'n.language');
  1571. if ($query->setOption('term', 'ti.tid')) {
  1572. $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  1573. }
  1574. // Only continue if the first pass query matches.
  1575. if (!$query->executeFirstPass()) {
  1576. return array();
  1577. }
  1578. // Add the ranking expressions.
  1579. _node_rankings($query);
  1580. // Load results.
  1581. $find = $query
  1582. ->limit(10)
  1583. ->execute();
  1584. $results = array();
  1585. foreach ($find as $item) {
  1586. // Render the node.
  1587. $node = node_load($item->sid);
  1588. $build = node_view($node, 'search_result');
  1589. unset($build['#theme']);
  1590. $node->rendered = drupal_render($build);
  1591. // Fetch comments for snippet.
  1592. $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
  1593. $extra = module_invoke_all('node_search_result', $node);
  1594. $uri = entity_uri('node', $node);
  1595. $results[] = array(
  1596. 'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
  1597. 'type' => check_plain(node_type_get_name($node)),
  1598. 'title' => $node->title,
  1599. 'user' => theme('username', array('account' => $node)),
  1600. 'date' => $node->changed,
  1601. 'node' => $node,
  1602. 'extra' => $extra,
  1603. 'score' => $item->calculated_score,
  1604. 'snippet' => search_excerpt($keys, $node->rendered),
  1605. 'language' => entity_language('node', $node),
  1606. );
  1607. }
  1608. return $results;
  1609. }
  1610. /**
  1611. * Implements hook_ranking().
  1612. */
  1613. function node_ranking() {
  1614. // Create the ranking array and add the basic ranking options.
  1615. $ranking = array(
  1616. 'relevance' => array(
  1617. 'title' => t('Keyword relevance'),
  1618. // Average relevance values hover around 0.15
  1619. 'score' => 'i.relevance',
  1620. ),
  1621. 'sticky' => array(
  1622. 'title' => t('Content is sticky at top of lists'),
  1623. // The sticky flag is either 0 or 1, which is automatically normalized.
  1624. 'score' => 'n.sticky',
  1625. ),
  1626. 'promote' => array(
  1627. 'title' => t('Content is promoted to the front page'),
  1628. // The promote flag is either 0 or 1, which is automatically normalized.
  1629. 'score' => 'n.promote',
  1630. ),
  1631. );
  1632. // Add relevance based on creation or changed date.
  1633. if ($node_cron_last = variable_get('node_cron_last', 0)) {
  1634. $ranking['recent'] = array(
  1635. 'title' => t('Recently posted'),
  1636. // Exponential decay with half-life of 6 months, starting at last indexed node
  1637. 'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - :node_cron_last) * 6.43e-8)',
  1638. 'arguments' => array(':node_cron_last' => $node_cron_last),
  1639. );
  1640. }
  1641. return $ranking;
  1642. }
  1643. /**
  1644. * Implements hook_user_cancel().
  1645. */
  1646. function node_user_cancel($edit, $account, $method) {
  1647. switch ($method) {
  1648. case 'user_cancel_block_unpublish':
  1649. // Unpublish nodes (current revisions).
  1650. module_load_include('inc', 'node', 'node.admin');
  1651. $nodes = db_select('node', 'n')
  1652. ->fields('n', array('nid'))
  1653. ->condition('uid', $account->uid)
  1654. ->execute()
  1655. ->fetchCol();
  1656. node_mass_update($nodes, array('status' => 0));
  1657. break;
  1658. case 'user_cancel_reassign':
  1659. // Anonymize nodes (current revisions).
  1660. module_load_include('inc', 'node', 'node.admin');
  1661. $nodes = db_select('node', 'n')
  1662. ->fields('n', array('nid'))
  1663. ->condition('uid', $account->uid)
  1664. ->execute()
  1665. ->fetchCol();
  1666. node_mass_update($nodes, array('uid' => 0));
  1667. // Anonymize old revisions.
  1668. db_update('node_revision')
  1669. ->fields(array('uid' => 0))
  1670. ->condition('uid', $account->uid)
  1671. ->execute();
  1672. // Clean history.
  1673. db_delete('history')
  1674. ->condition('uid', $account->uid)
  1675. ->execute();
  1676. break;
  1677. }
  1678. }
  1679. /**
  1680. * Implements hook_user_delete().
  1681. */
  1682. function node_user_delete($account) {
  1683. // Delete nodes (current revisions).
  1684. // @todo Introduce node_mass_delete() or make node_mass_update() more flexible.
  1685. $nodes = db_select('node', 'n')
  1686. ->fields('n', array('nid'))
  1687. ->condition('uid', $account->uid)
  1688. ->execute()
  1689. ->fetchCol();
  1690. node_delete_multiple($nodes);
  1691. // Delete old revisions.
  1692. $revisions = db_query('SELECT vid FROM {node_revision} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
  1693. foreach ($revisions as $revision) {
  1694. node_revision_delete($revision);
  1695. }
  1696. // Clean history.
  1697. db_delete('history')
  1698. ->condition('uid', $account->uid)
  1699. ->execute();
  1700. }
  1701. /**
  1702. * Returns HTML for the content ranking part of the search settings admin page.
  1703. *
  1704. * @param $variables
  1705. * An associative array containing:
  1706. * - form: A render element representing the form.
  1707. *
  1708. * @see node_search_admin()
  1709. * @ingroup themeable
  1710. */
  1711. function theme_node_search_admin($variables) {
  1712. $form = $variables['form'];
  1713. $output = drupal_render($form['info']);
  1714. $header = array(t('Factor'), t('Weight'));
  1715. foreach (element_children($form['factors']) as $key) {
  1716. $row = array();
  1717. $row[] = $form['factors'][$key]['#title'];
  1718. $form['factors'][$key]['#title_display'] = 'invisible';
  1719. $row[] = drupal_render($form['factors'][$key]);
  1720. $rows[] = $row;
  1721. }
  1722. $output .= theme('table', array('header' => $header, 'rows' => $rows));
  1723. $output .= drupal_render_children($form);
  1724. return $output;
  1725. }
  1726. /**
  1727. * Access callback: Checks node revision access.
  1728. *
  1729. * @param $node
  1730. * The node to check.
  1731. * @param $op
  1732. * (optional) The specific operation being checked. Defaults to 'view.'
  1733. * @param object $account
  1734. * (optional) A user object representing the user for whom the operation is
  1735. * to be performed. Determines access for a user other than the current user.
  1736. *
  1737. * @return
  1738. * TRUE if the operation may be performed, FALSE otherwise.
  1739. *
  1740. * @see node_menu()
  1741. */
  1742. function _node_revision_access($node, $op = 'view', $account = NULL) {
  1743. $access = &drupal_static(__FUNCTION__, array());
  1744. $map = array(
  1745. 'view' => 'view revisions',
  1746. 'update' => 'revert revisions',
  1747. 'delete' => 'delete revisions',
  1748. );
  1749. if (!$node || !isset($map[$op])) {
  1750. // If there was no node to check against, or the $op was not one of the
  1751. // supported ones, we return access denied.
  1752. return FALSE;
  1753. }
  1754. if (!isset($account)) {
  1755. $account = $GLOBALS['user'];
  1756. }
  1757. // Statically cache access by revision ID, user account ID, and operation.
  1758. $cid = $node->vid . ':' . $account->uid . ':' . $op;
  1759. if (!isset($access[$cid])) {
  1760. // Perform basic permission checks first.
  1761. if (!user_access($map[$op], $account) && !user_access('administer nodes', $account)) {
  1762. return $access[$cid] = FALSE;
  1763. }
  1764. $node_current_revision = node_load($node->nid);
  1765. $is_current_revision = $node_current_revision->vid == $node->vid;
  1766. // There should be at least two revisions. If the vid of the given node and
  1767. // the vid of the current revision differ, then we already have two
  1768. // different revisions so there is no need for a separate database check.
  1769. // Also, if you try to revert to or delete the current revision, that's not
  1770. // good.
  1771. if ($is_current_revision && (db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField() == 1 || $op == 'update' || $op == 'delete')) {
  1772. $access[$cid] = FALSE;
  1773. }
  1774. elseif (user_access('administer nodes', $account)) {
  1775. $access[$cid] = TRUE;
  1776. }
  1777. else {
  1778. // First check the access to the current revision and finally, if the node
  1779. // passed in is not the current revision then access to that, too.
  1780. $access[$cid] = node_access($op, $node_current_revision, $account) && ($is_current_revision || node_access($op, $node, $account));
  1781. }
  1782. }
  1783. return $access[$cid];
  1784. }
  1785. /**
  1786. * Access callback: Checks whether the user has permission to add a node.
  1787. *
  1788. * @return
  1789. * TRUE if the user has add permission, otherwise FALSE.
  1790. *
  1791. * @see node_menu()
  1792. */
  1793. function _node_add_access() {
  1794. $types = node_type_get_types();
  1795. foreach ($types as $type) {
  1796. if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
  1797. return TRUE;
  1798. }
  1799. }
  1800. if (user_access('administer content types')) {
  1801. // There are no content types defined that the user has permission to create,
  1802. // but the user does have the permission to administer the content types, so
  1803. // grant them access to the page anyway.
  1804. return TRUE;
  1805. }
  1806. return FALSE;
  1807. }
  1808. /**
  1809. * Implements hook_menu().
  1810. */
  1811. function node_menu() {
  1812. $items['admin/content'] = array(
  1813. 'title' => 'Content',
  1814. 'description' => 'Find and manage content.',
  1815. 'page callback' => 'drupal_get_form',
  1816. 'page arguments' => array('node_admin_content'),
  1817. 'access arguments' => array('access content overview'),
  1818. 'weight' => -10,
  1819. 'file' => 'node.admin.inc',
  1820. );
  1821. $items['admin/content/node'] = array(
  1822. 'title' => 'Content',
  1823. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1824. 'weight' => -10,
  1825. );
  1826. $items['admin/reports/status/rebuild'] = array(
  1827. 'title' => 'Rebuild permissions',
  1828. 'page callback' => 'drupal_get_form',
  1829. 'page arguments' => array('node_configure_rebuild_confirm'),
  1830. // Any user than can potentially trigger a node_access_needs_rebuild(TRUE)
  1831. // has to be allowed access to the 'node access rebuild' confirm form.
  1832. 'access arguments' => array('access administration pages'),
  1833. 'type' => MENU_CALLBACK,
  1834. 'file' => 'node.admin.inc',
  1835. );
  1836. $items['admin/structure/types'] = array(
  1837. 'title' => 'Content types',
  1838. 'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
  1839. 'page callback' => 'node_overview_types',
  1840. 'access arguments' => array('administer content types'),
  1841. 'file' => 'content_types.inc',
  1842. );
  1843. $items['admin/structure/types/list'] = array(
  1844. 'title' => 'List',
  1845. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1846. 'weight' => -10,
  1847. );
  1848. $items['admin/structure/types/add'] = array(
  1849. 'title' => 'Add content type',
  1850. 'page callback' => 'drupal_get_form',
  1851. 'page arguments' => array('node_type_form'),
  1852. 'access arguments' => array('administer content types'),
  1853. 'type' => MENU_LOCAL_ACTION,
  1854. 'file' => 'content_types.inc',
  1855. );
  1856. $items['admin/structure/types/manage/%node_type'] = array(
  1857. 'title' => 'Edit content type',
  1858. 'title callback' => 'node_type_page_title',
  1859. 'title arguments' => array(4),
  1860. 'page callback' => 'drupal_get_form',
  1861. 'page arguments' => array('node_type_form', 4),
  1862. 'access arguments' => array('administer content types'),
  1863. 'file' => 'content_types.inc',
  1864. );
  1865. $items['admin/structure/types/manage/%node_type/edit'] = array(
  1866. 'title' => 'Edit',
  1867. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1868. );
  1869. $items['admin/structure/types/manage/%node_type/delete'] = array(
  1870. 'title' => 'Delete',
  1871. 'page arguments' => array('node_type_delete_confirm', 4),
  1872. 'access arguments' => array('administer content types'),
  1873. 'file' => 'content_types.inc',
  1874. );
  1875. $items['node'] = array(
  1876. 'page callback' => 'node_page_default',
  1877. 'access arguments' => array('access content'),
  1878. 'menu_name' => 'navigation',
  1879. 'type' => MENU_CALLBACK,
  1880. );
  1881. $items['node/add'] = array(
  1882. 'title' => 'Add content',
  1883. 'page callback' => 'node_add_page',
  1884. 'access callback' => '_node_add_access',
  1885. 'file' => 'node.pages.inc',
  1886. );
  1887. $items['rss.xml'] = array(
  1888. 'title' => 'RSS feed',
  1889. 'page callback' => 'node_feed',
  1890. 'access arguments' => array('access content'),
  1891. 'type' => MENU_CALLBACK,
  1892. // Pass a FALSE and array argument to ensure that additional path components
  1893. // are not passed to node_feed().
  1894. 'page arguments' => array(FALSE, array()),
  1895. );
  1896. // @todo Remove this loop when we have a 'description callback' property.
  1897. // Reset internal static cache of _node_types_build(), forces to rebuild the
  1898. // node type information.
  1899. node_type_cache_reset();
  1900. foreach (node_type_get_types() as $type) {
  1901. $type_url_str = str_replace('_', '-', $type->type);
  1902. $items['node/add/' . $type_url_str] = array(
  1903. 'title' => $type->name,
  1904. 'title callback' => 'check_plain',
  1905. 'page callback' => 'node_add',
  1906. 'page arguments' => array($type->type),
  1907. 'access callback' => 'node_access',
  1908. 'access arguments' => array('create', $type->type),
  1909. 'description' => $type->description,
  1910. 'file' => 'node.pages.inc',
  1911. );
  1912. }
  1913. $items['node/%node'] = array(
  1914. 'title callback' => 'node_page_title',
  1915. 'title arguments' => array(1),
  1916. // The page callback also invokes drupal_set_title() in case
  1917. // the menu router's title is overridden by a menu link.
  1918. 'page callback' => 'node_page_view',
  1919. 'page arguments' => array(1),
  1920. 'access callback' => 'node_access',
  1921. 'access arguments' => array('view', 1),
  1922. );
  1923. $items['node/%node/view'] = array(
  1924. 'title' => 'View',
  1925. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1926. 'weight' => -10,
  1927. );
  1928. $items['node/%node/edit'] = array(
  1929. 'title' => 'Edit',
  1930. 'page callback' => 'node_page_edit',
  1931. 'page arguments' => array(1),
  1932. 'access callback' => 'node_access',
  1933. 'access arguments' => array('update', 1),
  1934. 'weight' => 0,
  1935. 'type' => MENU_LOCAL_TASK,
  1936. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  1937. 'file' => 'node.pages.inc',
  1938. );
  1939. $items['node/%node/delete'] = array(
  1940. 'title' => 'Delete',
  1941. 'page callback' => 'drupal_get_form',
  1942. 'page arguments' => array('node_delete_confirm', 1),
  1943. 'access callback' => 'node_access',
  1944. 'access arguments' => array('delete', 1),
  1945. 'weight' => 1,
  1946. 'type' => MENU_LOCAL_TASK,
  1947. 'context' => MENU_CONTEXT_INLINE,
  1948. 'file' => 'node.pages.inc',
  1949. );
  1950. $items['node/%node/revisions'] = array(
  1951. 'title' => 'Revisions',
  1952. 'page callback' => 'node_revision_overview',
  1953. 'page arguments' => array(1),
  1954. 'access callback' => '_node_revision_access',
  1955. 'access arguments' => array(1),
  1956. 'weight' => 2,
  1957. 'type' => MENU_LOCAL_TASK,
  1958. 'file' => 'node.pages.inc',
  1959. );
  1960. $items['node/%node/revisions/%/view'] = array(
  1961. 'title' => 'Revisions',
  1962. 'load arguments' => array(3),
  1963. 'page callback' => 'node_show',
  1964. 'page arguments' => array(1, TRUE),
  1965. 'access callback' => '_node_revision_access',
  1966. 'access arguments' => array(1),
  1967. );
  1968. $items['node/%node/revisions/%/revert'] = array(
  1969. 'title' => 'Revert to earlier revision',
  1970. 'load arguments' => array(3),
  1971. 'page callback' => 'drupal_get_form',
  1972. 'page arguments' => array('node_revision_revert_confirm', 1),
  1973. 'access callback' => '_node_revision_access',
  1974. 'access arguments' => array(1, 'update'),
  1975. 'file' => 'node.pages.inc',
  1976. );
  1977. $items['node/%node/revisions/%/delete'] = array(
  1978. 'title' => 'Delete earlier revision',
  1979. 'load arguments' => array(3),
  1980. 'page callback' => 'drupal_get_form',
  1981. 'page arguments' => array('node_revision_delete_confirm', 1),
  1982. 'access callback' => '_node_revision_access',
  1983. 'access arguments' => array(1, 'delete'),
  1984. 'file' => 'node.pages.inc',
  1985. );
  1986. return $items;
  1987. }
  1988. /**
  1989. * Implements hook_menu_local_tasks_alter().
  1990. */
  1991. function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  1992. // Add action link to 'node/add' on 'admin/content' page.
  1993. if ($root_path == 'admin/content') {
  1994. $item = menu_get_item('node/add');
  1995. if ($item['access']) {
  1996. $data['actions']['output'][] = array(
  1997. '#theme' => 'menu_local_action',
  1998. '#link' => $item,
  1999. );
  2000. }
  2001. }
  2002. }
  2003. /**
  2004. * Title callback: Returns the unsanitized title of the node type edit form.
  2005. *
  2006. * @param $type
  2007. * The node type object.
  2008. *
  2009. * @return string
  2010. * An unsanitized string that is the title of the node type edit form.
  2011. *
  2012. * @see node_menu()
  2013. */
  2014. function node_type_page_title($type) {
  2015. return $type->name;
  2016. }
  2017. /**
  2018. * Title callback: Returns the title of the node.
  2019. *
  2020. * @param $node
  2021. * The node object.
  2022. *
  2023. * @return
  2024. * An unsanitized string that is the title of the node.
  2025. *
  2026. * @see node_menu()
  2027. */
  2028. function node_page_title($node) {
  2029. return $node->title;
  2030. }
  2031. /**
  2032. * Finds the last time a node was changed.
  2033. *
  2034. * @param $nid
  2035. * The ID of a node.
  2036. *
  2037. * @return
  2038. * A unix timestamp indicating the last time the node was changed.
  2039. */
  2040. function node_last_changed($nid) {
  2041. return db_query('SELECT changed FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetch()->changed;
  2042. }
  2043. /**
  2044. * Returns a list of all the existing revision numbers.
  2045. *
  2046. * @param Drupal\node\Node $node
  2047. * The node entity.
  2048. *
  2049. * @return
  2050. * An associative array keyed by node revision number.
  2051. */
  2052. function node_revision_list($node) {
  2053. $revisions = array();
  2054. $result = db_query('SELECT r.vid, r.title, r.log, r.uid, n.vid AS current_vid, r.timestamp, u.name FROM {node_revision} r LEFT JOIN {node} n ON n.vid = r.vid INNER JOIN {users} u ON u.uid = r.uid WHERE r.nid = :nid ORDER BY r.vid DESC', array(':nid' => $node->nid));
  2055. foreach ($result as $revision) {
  2056. $revisions[$revision->vid] = $revision;
  2057. }
  2058. return $revisions;
  2059. }
  2060. /**
  2061. * Implements hook_block_info().
  2062. */
  2063. function node_block_info() {
  2064. $blocks['syndicate']['info'] = t('Syndicate');
  2065. // Not worth caching.
  2066. $blocks['syndicate']['cache'] = DRUPAL_NO_CACHE;
  2067. $blocks['recent']['info'] = t('Recent content');
  2068. $blocks['recent']['properties']['administrative'] = TRUE;
  2069. return $blocks;
  2070. }
  2071. /**
  2072. * Implements hook_block_view().
  2073. */
  2074. function node_block_view($delta = '') {
  2075. $block = array();
  2076. switch ($delta) {
  2077. case 'syndicate':
  2078. $block['subject'] = t('Syndicate');
  2079. $block['content'] = theme('feed_icon', array('url' => 'rss.xml', 'title' => t('Syndicate')));
  2080. break;
  2081. case 'recent':
  2082. if (user_access('access content')) {
  2083. $block['subject'] = t('Recent content');
  2084. if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
  2085. $block['content'] = theme('node_recent_block', array(
  2086. 'nodes' => $nodes,
  2087. ));
  2088. } else {
  2089. $block['content'] = t('No content available.');
  2090. }
  2091. }
  2092. break;
  2093. }
  2094. return $block;
  2095. }
  2096. /**
  2097. * Implements hook_block_configure().
  2098. */
  2099. function node_block_configure($delta = '') {
  2100. $form = array();
  2101. if ($delta == 'recent') {
  2102. $form['node_recent_block_count'] = array(
  2103. '#type' => 'select',
  2104. '#title' => t('Number of recent content items to display'),
  2105. '#default_value' => variable_get('node_recent_block_count', 10),
  2106. '#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)),
  2107. );
  2108. }
  2109. return $form;
  2110. }
  2111. /**
  2112. * Implements hook_block_save().
  2113. */
  2114. function node_block_save($delta = '', $edit = array()) {
  2115. if ($delta == 'recent') {
  2116. variable_set('node_recent_block_count', $edit['node_recent_block_count']);
  2117. }
  2118. }
  2119. /**
  2120. * Finds the most recently changed nodes that are available to the current user.
  2121. *
  2122. * @param $number
  2123. * (optional) The maximum number of nodes to find. Defaults to 10.
  2124. *
  2125. * @return
  2126. * An array of node entities or an empty array if there are no recent nodes
  2127. * visible to the current user.
  2128. */
  2129. function node_get_recent($number = 10) {
  2130. $query = db_select('node', 'n');
  2131. if (!user_access('bypass node access')) {
  2132. // If the user is able to view their own unpublished nodes, allow them to
  2133. // see these in addition to published nodes. Check that they actually have
  2134. // some unpublished nodes to view before adding the condition.
  2135. if (user_access('view own unpublished content') && $own_unpublished = db_query('SELECT nid FROM {node} WHERE uid = :uid AND status = :status', array(':uid' => $GLOBALS['user']->uid, ':status' => NODE_NOT_PUBLISHED))->fetchCol()) {
  2136. $query->condition(db_or()
  2137. ->condition('n.status', NODE_PUBLISHED)
  2138. ->condition('n.nid', $own_unpublished, 'IN')
  2139. );
  2140. }
  2141. else {
  2142. // If not, restrict the query to published nodes.
  2143. $query->condition('n.status', NODE_PUBLISHED);
  2144. }
  2145. }
  2146. $nids = $query
  2147. ->fields('n', array('nid'))
  2148. ->orderBy('n.changed', 'DESC')
  2149. ->range(0, $number)
  2150. ->addTag('node_access')
  2151. ->execute()
  2152. ->fetchCol();
  2153. $nodes = node_load_multiple($nids);
  2154. return $nodes ? $nodes : array();
  2155. }
  2156. /**
  2157. * Returns HTML for a list of recent content.
  2158. *
  2159. * @param $variables
  2160. * An associative array containing:
  2161. * - nodes: An array of recent node objects.
  2162. *
  2163. * @ingroup themeable
  2164. */
  2165. function theme_node_recent_block($variables) {
  2166. $rows = array();
  2167. $output = '';
  2168. $l_options = array('query' => drupal_get_destination());
  2169. foreach ($variables['nodes'] as $node) {
  2170. $row = array();
  2171. $row[] = array(
  2172. 'data' => theme('node_recent_content', array('node' => $node)),
  2173. 'class' => 'title-author',
  2174. );
  2175. $row[] = array(
  2176. 'data' => node_access('update', $node) ? l(t('edit'), 'node/' . $node->nid . '/edit', $l_options) : '',
  2177. 'class' => 'edit',
  2178. );
  2179. $row[] = array(
  2180. 'data' => node_access('delete', $node) ? l(t('delete'), 'node/' . $node->nid . '/delete', $l_options) : '',
  2181. 'class' => 'delete',
  2182. );
  2183. $rows[] = $row;
  2184. }
  2185. if ($rows) {
  2186. $output = theme('table', array('rows' => $rows));
  2187. if (user_access('access content overview')) {
  2188. $output .= theme('more_link', array('url' => 'admin/content', 'title' => t('Show more content')));
  2189. }
  2190. }
  2191. return $output;
  2192. }
  2193. /**
  2194. * Returns HTML for a recent node to be displayed in the recent content block.
  2195. *
  2196. * @param $variables
  2197. * An associative array containing:
  2198. * - node: A node object.
  2199. *
  2200. * @ingroup themeable
  2201. */
  2202. function theme_node_recent_content($variables) {
  2203. $node = $variables['node'];
  2204. $output = '<div class="node-title">';
  2205. $output .= l($node->title, 'node/' . $node->nid);
  2206. $output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
  2207. $output .= '</div><div class="node-author">';
  2208. $output .= theme('username', array('account' => user_load($node->uid)));
  2209. $output .= '</div>';
  2210. return $output;
  2211. }
  2212. /**
  2213. * Implements hook_form_FORMID_alter().
  2214. *
  2215. * Adds node-type specific visibility options to add block form.
  2216. *
  2217. * @see block_add_block_form()
  2218. */
  2219. function node_form_block_add_block_form_alter(&$form, &$form_state) {
  2220. node_form_block_admin_configure_alter($form, $form_state);
  2221. }
  2222. /**
  2223. * Implements hook_form_FORMID_alter().
  2224. *
  2225. * Adds node-type specific visibility options to block configuration form.
  2226. *
  2227. * @see block_admin_configure()
  2228. */
  2229. function node_form_block_admin_configure_alter(&$form, &$form_state) {
  2230. $default_type_options = db_query("SELECT type FROM {block_node_type} WHERE module = :module AND delta = :delta", array(
  2231. ':module' => $form['module']['#value'],
  2232. ':delta' => $form['delta']['#value'],
  2233. ))->fetchCol();
  2234. $form['visibility']['node_type'] = array(
  2235. '#type' => 'fieldset',
  2236. '#title' => t('Content types'),
  2237. '#collapsible' => TRUE,
  2238. '#collapsed' => TRUE,
  2239. '#group' => 'visibility',
  2240. '#weight' => 5,
  2241. );
  2242. $form['visibility']['node_type']['types'] = array(
  2243. '#type' => 'checkboxes',
  2244. '#title' => t('Show block for specific content types'),
  2245. '#default_value' => $default_type_options,
  2246. '#options' => node_type_get_names(),
  2247. '#description' => t('Show this block only on pages that display content of the given type(s). If you select no types, there will be no type-specific limitation.'),
  2248. );
  2249. $form['#submit'][] = 'node_form_block_admin_configure_submit';
  2250. }
  2251. /**
  2252. * Form submission handler for node_form_block_admin_configure_alter().
  2253. *
  2254. * @see node_form_block_admin_configure_alter()
  2255. */
  2256. function node_form_block_admin_configure_submit($form, &$form_state) {
  2257. db_delete('block_node_type')
  2258. ->condition('module', $form_state['values']['module'])
  2259. ->condition('delta', $form_state['values']['delta'])
  2260. ->execute();
  2261. $query = db_insert('block_node_type')->fields(array('type', 'module', 'delta'));
  2262. foreach (array_filter($form_state['values']['types']) as $type) {
  2263. $query->values(array(
  2264. 'type' => $type,
  2265. 'module' => $form_state['values']['module'],
  2266. 'delta' => $form_state['values']['delta'],
  2267. ));
  2268. }
  2269. $query->execute();
  2270. }
  2271. /**
  2272. * Implements hook_form_FORMID_alter().
  2273. *
  2274. * Adds node specific submit handler to delete custom block form.
  2275. *
  2276. * @see block_custom_block_delete()
  2277. */
  2278. function node_form_block_custom_block_delete_alter(&$form, &$form_state) {
  2279. $form['#submit'][] = 'node_form_block_custom_block_delete_submit';
  2280. }
  2281. /**
  2282. * Form submission handler for node_form_block_custom_block_delete_alter().
  2283. *
  2284. * @see node_form_block_custom_block_delete_alter()
  2285. */
  2286. function node_form_block_custom_block_delete_submit($form, &$form_state) {
  2287. db_delete('block_node_type')
  2288. ->condition('module', 'block')
  2289. ->condition('delta', $form_state['values']['bid'])
  2290. ->execute();
  2291. }
  2292. /**
  2293. * Implements hook_modules_uninstalled().
  2294. *
  2295. * Cleanup {block_node_type} table from modules' blocks.
  2296. */
  2297. function node_modules_uninstalled($modules) {
  2298. db_delete('block_node_type')
  2299. ->condition('module', $modules, 'IN')
  2300. ->execute();
  2301. }
  2302. /**
  2303. * Implements hook_block_list_alter().
  2304. *
  2305. * Check the content type specific visibilty settings. Remove the block if the
  2306. * visibility conditions are not met.
  2307. */
  2308. function node_block_list_alter(&$blocks) {
  2309. global $theme_key;
  2310. // Build an array of node types for each block.
  2311. $block_node_types = array();
  2312. $result = db_query('SELECT module, delta, type FROM {block_node_type}');
  2313. foreach ($result as $record) {
  2314. $block_node_types[$record->module][$record->delta][$record->type] = TRUE;
  2315. }
  2316. $node = menu_get_object();
  2317. $node_types = node_type_get_types();
  2318. if (arg(0) == 'node' && arg(1) == 'add' && arg(2)) {
  2319. $node_add_arg = strtr(arg(2), '-', '_');
  2320. }
  2321. foreach ($blocks as $key => $block) {
  2322. if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
  2323. // This block was added by a contrib module, leave it in the list.
  2324. continue;
  2325. }
  2326. // If a block has no node types associated, it is displayed for every type.
  2327. // For blocks with node types associated, if the node type does not match
  2328. // the settings from this block, remove it from the block list.
  2329. if (isset($block_node_types[$block->module][$block->delta])) {
  2330. if (!empty($node)) {
  2331. // This is a node or node edit page.
  2332. if (!isset($block_node_types[$block->module][$block->delta][$node->type])) {
  2333. // This block should not be displayed for this node type.
  2334. unset($blocks[$key]);
  2335. continue;
  2336. }
  2337. }
  2338. elseif (isset($node_add_arg) && isset($node_types[$node_add_arg])) {
  2339. // This is a node creation page
  2340. if (!isset($block_node_types[$block->module][$block->delta][$node_add_arg])) {
  2341. // This block should not be displayed for this node type.
  2342. unset($blocks[$key]);
  2343. continue;
  2344. }
  2345. }
  2346. else {
  2347. // This is not a node page, remove the block.
  2348. unset($blocks[$key]);
  2349. continue;
  2350. }
  2351. }
  2352. }
  2353. }
  2354. /**
  2355. * Generates and prints an RSS feed.
  2356. *
  2357. * Generates an RSS feed from an array of node IDs, and prints it with an HTTP
  2358. * header, with Content Type set to RSS/XML.
  2359. *
  2360. * @param $nids
  2361. * An array of node IDs (nid). Defaults to FALSE so empty feeds can be
  2362. * generated with passing an empty array, if no items are to be added
  2363. * to the feed.
  2364. * @param $channel
  2365. * An associative array containing title, link, description and other keys,
  2366. * to be parsed by format_rss_channel() and format_xml_elements().
  2367. * A list of channel elements can be found at the
  2368. * @link http://cyber.law.harvard.edu/rss/rss.html RSS 2.0 Specification. @endlink
  2369. * The link should be an absolute URL.
  2370. */
  2371. function node_feed($nids = FALSE, $channel = array()) {
  2372. global $base_url, $language_content;
  2373. if ($nids === FALSE) {
  2374. $nids = db_select('node', 'n')
  2375. ->fields('n', array('nid', 'created'))
  2376. ->condition('n.promote', 1)
  2377. ->condition('n.status', 1)
  2378. ->orderBy('n.created', 'DESC')
  2379. ->range(0, variable_get('feed_default_items', 10))
  2380. ->addTag('node_access')
  2381. ->execute()
  2382. ->fetchCol();
  2383. }
  2384. $item_length = variable_get('feed_item_length', 'fulltext');
  2385. $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');
  2386. // Load all nodes to be rendered.
  2387. $nodes = node_load_multiple($nids);
  2388. $items = '';
  2389. foreach ($nodes as $node) {
  2390. $item_text = '';
  2391. $node->link = url("node/$node->nid", array('absolute' => TRUE));
  2392. $node->rss_namespaces = array();
  2393. $node->rss_elements = array(
  2394. array('key' => 'pubDate', 'value' => gmdate('r', $node->created)),
  2395. array('key' => 'dc:creator', 'value' => $node->name),
  2396. array('key' => 'guid', 'value' => $node->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))
  2397. );
  2398. // The node gets built and modules add to or modify $node->rss_elements
  2399. // and $node->rss_namespaces.
  2400. $build = node_view($node, 'rss');
  2401. unset($build['#theme']);
  2402. if (!empty($node->rss_namespaces)) {
  2403. $namespaces = array_merge($namespaces, $node->rss_namespaces);
  2404. }
  2405. if ($item_length != 'title') {
  2406. // We render node contents and force links to be last.
  2407. $build['links']['#weight'] = 1000;
  2408. $item_text .= drupal_render($build);
  2409. }
  2410. $items .= format_rss_item($node->title, $node->link, $item_text, $node->rss_elements);
  2411. }
  2412. $channel_defaults = array(
  2413. 'version' => '2.0',
  2414. 'title' => variable_get('site_name', 'Drupal'),
  2415. 'link' => $base_url,
  2416. 'description' => variable_get('feed_description', ''),
  2417. 'language' => $language_content->language
  2418. );
  2419. $channel_extras = array_diff_key($channel, $channel_defaults);
  2420. $channel = array_merge($channel_defaults, $channel);
  2421. $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  2422. $output .= "<rss version=\"" . $channel["version"] . "\" xml:base=\"" . $base_url . "\" " . drupal_attributes($namespaces) . ">\n";
  2423. $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language'], $channel_extras);
  2424. $output .= "</rss>\n";
  2425. drupal_add_http_header('Content-Type', 'application/rss+xml; charset=utf-8');
  2426. print $output;
  2427. }
  2428. /**
  2429. * Constructs a drupal_render() style array from an array of loaded nodes.
  2430. *
  2431. * @param $nodes
  2432. * An array of nodes as returned by node_load_multiple().
  2433. * @param $view_mode
  2434. * View mode, e.g. 'full', 'teaser'...
  2435. * @param $weight
  2436. * An integer representing the weight of the first node in the list.
  2437. * @param $langcode
  2438. * (optional) A language code to use for rendering. Defaults to NULL which is
  2439. * the global content language of the current request.
  2440. *
  2441. * @return
  2442. * An array in the format expected by drupal_render().
  2443. */
  2444. function node_view_multiple($nodes, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
  2445. field_attach_prepare_view('node', $nodes, $view_mode, $langcode);
  2446. entity_prepare_view('node', $nodes, $langcode);
  2447. $build = array();
  2448. foreach ($nodes as $node) {
  2449. $build['nodes'][$node->nid] = node_view($node, $view_mode, $langcode);
  2450. $build['nodes'][$node->nid]['#weight'] = $weight;
  2451. $weight++;
  2452. }
  2453. $build['nodes']['#sorted'] = TRUE;
  2454. return $build;
  2455. }
  2456. /**
  2457. * Menu callback: Generates a listing of promoted nodes.
  2458. *
  2459. * @return array
  2460. * An array in the format expected by drupal_render().
  2461. *
  2462. * @see node_menu()
  2463. */
  2464. function node_page_default() {
  2465. $select = db_select('node', 'n')
  2466. ->fields('n', array('nid', 'sticky', 'created'))
  2467. ->condition('n.promote', 1)
  2468. ->condition('n.status', 1)
  2469. ->orderBy('n.sticky', 'DESC')
  2470. ->orderBy('n.created', 'DESC')
  2471. ->extend('PagerDefault')
  2472. ->limit(variable_get('default_nodes_main', 10))
  2473. ->addTag('node_access');
  2474. $nids = $select->execute()->fetchCol();
  2475. if (!empty($nids)) {
  2476. $nodes = node_load_multiple($nids);
  2477. $build = node_view_multiple($nodes);
  2478. // 'rss.xml' is a path, not a file, registered in node_menu().
  2479. drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
  2480. $build['pager'] = array(
  2481. '#theme' => 'pager',
  2482. '#weight' => 5,
  2483. );
  2484. drupal_set_title('');
  2485. }
  2486. else {
  2487. drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);
  2488. $default_message = '<p>' . t('No front page content has been created yet.') . '</p>';
  2489. $default_links = array();
  2490. if (_node_add_access()) {
  2491. $default_links[] = l(t('Add new content'), 'node/add');
  2492. }
  2493. if (!empty($default_links)) {
  2494. $default_message .= theme('item_list', array('items' => $default_links));
  2495. }
  2496. $build['default_message'] = array(
  2497. '#markup' => $default_message,
  2498. '#prefix' => '<div id="first-time">',
  2499. '#suffix' => '</div>',
  2500. );
  2501. }
  2502. return $build;
  2503. }
  2504. /**
  2505. * Menu callback: Displays a single node.
  2506. *
  2507. * @param $node
  2508. * The node object.
  2509. *
  2510. * @return
  2511. * A page array suitable for use by drupal_render().
  2512. *
  2513. * @see node_menu()
  2514. */
  2515. function node_page_view($node) {
  2516. // If there is a menu link to this node, the link becomes the last part
  2517. // of the active trail, and the link name becomes the page title.
  2518. // Thus, we must explicitly set the page title to be the node title.
  2519. drupal_set_title($node->title);
  2520. $uri = entity_uri('node', $node);
  2521. // Set the node path as the canonical URL to prevent duplicate content.
  2522. drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  2523. // Set the non-aliased path as a default shortlink.
  2524. drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  2525. return node_show($node);
  2526. }
  2527. /**
  2528. * Implements hook_update_index().
  2529. */
  2530. function node_update_index() {
  2531. $limit = (int)variable_get('search_cron_limit', 100);
  2532. $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));
  2533. foreach ($result as $node) {
  2534. _node_index_node($node);
  2535. }
  2536. }
  2537. /**
  2538. * Indexes a single node.
  2539. *
  2540. * @param $node
  2541. * The node to index.
  2542. */
  2543. function _node_index_node($node) {
  2544. $node = node_load($node->nid);
  2545. // Save the changed time of the most recent indexed node, for the search
  2546. // results half-life calculation.
  2547. variable_set('node_cron_last', $node->changed);
  2548. // Render the node.
  2549. $build = node_view($node, 'search_index');
  2550. unset($build['#theme']);
  2551. $node->rendered = drupal_render($build);
  2552. $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;
  2553. // Fetch extra data normally not visible
  2554. $extra = module_invoke_all('node_update_index', $node);
  2555. foreach ($extra as $t) {
  2556. $text .= $t;
  2557. }
  2558. // Update index
  2559. search_index($node->nid, 'node', $text);
  2560. }
  2561. /**
  2562. * Implements hook_form_FORM_ID_alter().
  2563. */
  2564. function node_form_search_form_alter(&$form, $form_state) {
  2565. if (isset($form['module']) && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
  2566. // Keyword boxes:
  2567. $form['advanced'] = array(
  2568. '#type' => 'fieldset',
  2569. '#title' => t('Advanced search'),
  2570. '#collapsible' => TRUE,
  2571. '#collapsed' => TRUE,
  2572. '#attributes' => array('class' => array('search-advanced')),
  2573. );
  2574. $form['advanced']['keywords'] = array(
  2575. '#prefix' => '<div class="criterion">',
  2576. '#suffix' => '</div>',
  2577. );
  2578. $form['advanced']['keywords']['or'] = array(
  2579. '#type' => 'textfield',
  2580. '#title' => t('Containing any of the words'),
  2581. '#size' => 30,
  2582. '#maxlength' => 255,
  2583. );
  2584. $form['advanced']['keywords']['phrase'] = array(
  2585. '#type' => 'textfield',
  2586. '#title' => t('Containing the phrase'),
  2587. '#size' => 30,
  2588. '#maxlength' => 255,
  2589. );
  2590. $form['advanced']['keywords']['negative'] = array(
  2591. '#type' => 'textfield',
  2592. '#title' => t('Containing none of the words'),
  2593. '#size' => 30,
  2594. '#maxlength' => 255,
  2595. );
  2596. // Node types:
  2597. $types = array_map('check_plain', node_type_get_names());
  2598. $form['advanced']['type'] = array(
  2599. '#type' => 'checkboxes',
  2600. '#title' => t('Only of the type(s)'),
  2601. '#prefix' => '<div class="criterion">',
  2602. '#suffix' => '</div>',
  2603. '#options' => $types,
  2604. );
  2605. $form['advanced']['submit'] = array(
  2606. '#type' => 'submit',
  2607. '#value' => t('Advanced search'),
  2608. '#prefix' => '<div class="action">',
  2609. '#suffix' => '</div>',
  2610. '#weight' => 100,
  2611. );
  2612. // Languages:
  2613. $language_options = array();
  2614. foreach (language_list('language') as $key => $entity) {
  2615. if ($entity->enabled) {
  2616. $language_options[$key] = $entity->name;
  2617. }
  2618. }
  2619. if (count($language_options) > 1) {
  2620. $form['advanced']['language'] = array(
  2621. '#type' => 'checkboxes',
  2622. '#title' => t('Languages'),
  2623. '#prefix' => '<div class="criterion">',
  2624. '#suffix' => '</div>',
  2625. '#options' => $language_options,
  2626. );
  2627. }
  2628. $form['#validate'][] = 'node_search_validate';
  2629. }
  2630. }
  2631. /**
  2632. * Form validation handler for node_form_alter().
  2633. */
  2634. function node_search_validate($form, &$form_state) {
  2635. // Initialize using any existing basic search keywords.
  2636. $keys = $form_state['values']['processed_keys'];
  2637. // Insert extra restrictions into the search keywords string.
  2638. if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
  2639. // Retrieve selected types - Form API sets the value of unselected
  2640. // checkboxes to 0.
  2641. $form_state['values']['type'] = array_filter($form_state['values']['type']);
  2642. if (count($form_state['values']['type'])) {
  2643. $keys = search_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
  2644. }
  2645. }
  2646. if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
  2647. $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
  2648. }
  2649. if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
  2650. $languages = array_filter($form_state['values']['language']);
  2651. if (count($languages)) {
  2652. $keys = search_expression_insert($keys, 'language', implode(',', $languages));
  2653. }
  2654. }
  2655. if ($form_state['values']['or'] != '') {
  2656. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
  2657. $keys .= ' ' . implode(' OR ', $matches[1]);
  2658. }
  2659. }
  2660. if ($form_state['values']['negative'] != '') {
  2661. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
  2662. $keys .= ' -' . implode(' -', $matches[1]);
  2663. }
  2664. }
  2665. if ($form_state['values']['phrase'] != '') {
  2666. $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
  2667. }
  2668. if (!empty($keys)) {
  2669. form_set_value($form['basic']['processed_keys'], trim($keys), $form_state);
  2670. }
  2671. }
  2672. /**
  2673. * @defgroup node_access Node access rights
  2674. * @{
  2675. * The node access system determines who can do what to which nodes.
  2676. *
  2677. * In determining access rights for a node, node_access() first checks whether
  2678. * the user has the "bypass node access" permission. Such users have
  2679. * unrestricted access to all nodes. user 1 will always pass this check.
  2680. *
  2681. * Next, all implementations of hook_node_access() will be called. Each
  2682. * implementation may explicitly allow, explicitly deny, or ignore the access
  2683. * request. If at least one module says to deny the request, it will be rejected.
  2684. * If no modules deny the request and at least one says to allow it, the request
  2685. * will be permitted.
  2686. *
  2687. * If all modules ignore the access request, then the node_access table is used
  2688. * to determine access. All node access modules are queried using
  2689. * hook_node_grants() to assemble a list of "grant IDs" for the user. This list
  2690. * is compared against the table. If any row contains the node ID in question
  2691. * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a
  2692. * value of TRUE for the operation in question, then access is granted. Note
  2693. * that this table is a list of grants; any matching row is sufficient to
  2694. * grant access to the node.
  2695. *
  2696. * In node listings (lists of nodes generated from a select query, such as the
  2697. * default home page at path 'node', an RSS feed, a recent content block, etc.),
  2698. * the process above is followed except that hook_node_access() is not called on
  2699. * each node for performance reasons and for proper functioning of the pager
  2700. * system. When adding a node listing to your module, be sure to use a dynamic
  2701. * query created by db_select() and add a tag of "node_access". This will allow
  2702. * modules dealing with node access to ensure only nodes to which the user has
  2703. * access are retrieved, through the use of hook_query_TAG_alter().
  2704. *
  2705. * Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access()
  2706. * will block access to the node. Therefore, implementers should take care to
  2707. * not deny access unless they really intend to. Unless a module wishes to
  2708. * actively deny access it should return NODE_ACCESS_IGNORE (or simply return
  2709. * nothing) to allow other modules or the node_access table to control access.
  2710. *
  2711. * To see how to write a node access module of your own, see
  2712. * node_access_example.module.
  2713. */
  2714. /**
  2715. * Determines whether the current user may perform the operation on the node.
  2716. *
  2717. * @param $op
  2718. * The operation to be performed on the node. Possible values are:
  2719. * - "view"
  2720. * - "update"
  2721. * - "delete"
  2722. * - "create"
  2723. * @param $node
  2724. * The node object on which the operation is to be performed, or node type
  2725. * (e.g. 'forum') for "create" operation.
  2726. * @param $account
  2727. * Optional, a user object representing the user for whom the operation is to
  2728. * be performed. Determines access for a user other than the current user.
  2729. *
  2730. * @return
  2731. * TRUE if the operation may be performed, FALSE otherwise.
  2732. */
  2733. function node_access($op, $node, $account = NULL) {
  2734. $rights = &drupal_static(__FUNCTION__, array());
  2735. if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
  2736. // If there was no node to check against, or the $op was not one of the
  2737. // supported ones, we return access denied.
  2738. return FALSE;
  2739. }
  2740. // If no user object is supplied, the access check is for the current user.
  2741. if (empty($account)) {
  2742. $account = $GLOBALS['user'];
  2743. }
  2744. // $node may be either an object or a node type. Since node types cannot be
  2745. // an integer, use either nid or type as the static cache id.
  2746. $cid = is_object($node) ? $node->nid : $node;
  2747. // If we've already checked access for this node, user and op, return from
  2748. // cache.
  2749. if (isset($rights[$account->uid][$cid][$op])) {
  2750. return $rights[$account->uid][$cid][$op];
  2751. }
  2752. if (user_access('bypass node access', $account)) {
  2753. $rights[$account->uid][$cid][$op] = TRUE;
  2754. return TRUE;
  2755. }
  2756. if (!user_access('access content', $account)) {
  2757. $rights[$account->uid][$cid][$op] = FALSE;
  2758. return FALSE;
  2759. }
  2760. // We grant access to the node if both of the following conditions are met:
  2761. // - No modules say to deny access.
  2762. // - At least one module says to grant access.
  2763. // If no module specified either allow or deny, we fall back to the
  2764. // node_access table.
  2765. $access = module_invoke_all('node_access', $node, $op, $account);
  2766. if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
  2767. $rights[$account->uid][$cid][$op] = FALSE;
  2768. return FALSE;
  2769. }
  2770. elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
  2771. $rights[$account->uid][$cid][$op] = TRUE;
  2772. return TRUE;
  2773. }
  2774. // Check if authors can view their own unpublished nodes.
  2775. if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
  2776. $rights[$account->uid][$cid][$op] = TRUE;
  2777. return TRUE;
  2778. }
  2779. // If the module did not override the access rights, use those set in the
  2780. // node_access table.
  2781. if ($op != 'create' && $node->nid) {
  2782. if (module_implements('node_grants')) {
  2783. $query = db_select('node_access');
  2784. $query->addExpression('1');
  2785. $query->condition('grant_' . $op, 1, '>=');
  2786. $nids = db_or()->condition('nid', $node->nid);
  2787. if ($node->status) {
  2788. $nids->condition('nid', 0);
  2789. }
  2790. $query->condition($nids);
  2791. $query->range(0, 1);
  2792. $grants = db_or();
  2793. foreach (node_access_grants($op, $account) as $realm => $gids) {
  2794. foreach ($gids as $gid) {
  2795. $grants->condition(db_and()
  2796. ->condition('gid', $gid)
  2797. ->condition('realm', $realm)
  2798. );
  2799. }
  2800. }
  2801. if (count($grants) > 0) {
  2802. $query->condition($grants);
  2803. }
  2804. $result = (bool) $query
  2805. ->execute()
  2806. ->fetchField();
  2807. $rights[$account->uid][$cid][$op] = $result;
  2808. return $result;
  2809. }
  2810. elseif (is_object($node) && $op == 'view' && $node->status) {
  2811. // If no modules implement hook_node_grants(), the default behavior is to
  2812. // allow all users to view published nodes, so reflect that here.
  2813. $rights[$account->uid][$cid][$op] = TRUE;
  2814. return TRUE;
  2815. }
  2816. }
  2817. return FALSE;
  2818. }
  2819. /**
  2820. * Implements hook_node_access().
  2821. */
  2822. function node_node_access($node, $op, $account) {
  2823. $type = is_string($node) ? $node : $node->type;
  2824. if (in_array($type, node_permissions_get_configured_types())) {
  2825. if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
  2826. return NODE_ACCESS_ALLOW;
  2827. }
  2828. if ($op == 'update') {
  2829. if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
  2830. return NODE_ACCESS_ALLOW;
  2831. }
  2832. }
  2833. if ($op == 'delete') {
  2834. if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
  2835. return NODE_ACCESS_ALLOW;
  2836. }
  2837. }
  2838. }
  2839. return NODE_ACCESS_IGNORE;
  2840. }
  2841. /**
  2842. * Helper function to generate standard node permission list for a given type.
  2843. *
  2844. * @param $type
  2845. * The machine-readable name of the node type.
  2846. *
  2847. * @return array
  2848. * An array of permission names and descriptions.
  2849. */
  2850. function node_list_permissions($type) {
  2851. $info = node_type_get_type($type);
  2852. // Build standard list of node permissions for this type.
  2853. $perms = array(
  2854. "create $type content" => array(
  2855. 'title' => t('%type_name: Create new content', array('%type_name' => $info->name)),
  2856. ),
  2857. "edit own $type content" => array(
  2858. 'title' => t('%type_name: Edit own content', array('%type_name' => $info->name)),
  2859. ),
  2860. "edit any $type content" => array(
  2861. 'title' => t('%type_name: Edit any content', array('%type_name' => $info->name)),
  2862. ),
  2863. "delete own $type content" => array(
  2864. 'title' => t('%type_name: Delete own content', array('%type_name' => $info->name)),
  2865. ),
  2866. "delete any $type content" => array(
  2867. 'title' => t('%type_name: Delete any content', array('%type_name' => $info->name)),
  2868. ),
  2869. );
  2870. return $perms;
  2871. }
  2872. /**
  2873. * Returns an array of node types that should be managed by permissions.
  2874. *
  2875. * By default, this will include all node types in the system. To exclude a
  2876. * specific node from getting permissions defined for it, set the
  2877. * node_permissions_$type variable to 0. Core does not provide an interface for
  2878. * doing so. However, contrib modules may exclude their own nodes in
  2879. * hook_install(). Alternatively, contrib modules may configure all node types
  2880. * at once, or decide to apply some other hook_node_access() implementation to
  2881. * some or all node types.
  2882. *
  2883. * @return
  2884. * An array of node types managed by this module.
  2885. */
  2886. function node_permissions_get_configured_types() {
  2887. $configured_types = array();
  2888. foreach (node_type_get_types() as $type => $info) {
  2889. if (variable_get('node_permissions_' . $type, 1)) {
  2890. $configured_types[] = $type;
  2891. }
  2892. }
  2893. return $configured_types;
  2894. }
  2895. /**
  2896. * Fetches an array of permission IDs granted to the given user ID.
  2897. *
  2898. * The implementation here provides only the universal "all" grant. A node
  2899. * access module should implement hook_node_grants() to provide a grant list for
  2900. * the user.
  2901. *
  2902. * After the default grants have been loaded, we allow modules to alter the
  2903. * grants array by reference. This hook allows for complex business logic to be
  2904. * applied when integrating multiple node access modules.
  2905. *
  2906. * @param $op
  2907. * The operation that the user is trying to perform.
  2908. * @param $account
  2909. * The user object for the user performing the operation. If omitted, the
  2910. * current user is used.
  2911. *
  2912. * @return
  2913. * An associative array in which the keys are realms, and the values are
  2914. * arrays of grants for those realms.
  2915. */
  2916. function node_access_grants($op, $account = NULL) {
  2917. if (!isset($account)) {
  2918. $account = $GLOBALS['user'];
  2919. }
  2920. // Fetch node access grants from other modules.
  2921. $grants = module_invoke_all('node_grants', $account, $op);
  2922. // Allow modules to alter the assigned grants.
  2923. drupal_alter('node_grants', $grants, $account, $op);
  2924. return array_merge(array('all' => array(0)), $grants);
  2925. }
  2926. /**
  2927. * Determines whether the user has a global viewing grant for all nodes.
  2928. *
  2929. * Checks to see whether any module grants global 'view' access to a user
  2930. * account; global 'view' access is encoded in the {node_access} table as a
  2931. * grant with nid=0. If no node access modules are enabled, node.module defines
  2932. * such a global 'view' access grant.
  2933. *
  2934. * This function is called when a node listing query is tagged with
  2935. * 'node_access'; when this function returns TRUE, no node access joins are
  2936. * added to the query.
  2937. *
  2938. * @param $account
  2939. * The user object for the user whose access is being checked. If omitted,
  2940. * the current user is used.
  2941. *
  2942. * @return
  2943. * TRUE if 'view' access to all nodes is granted, FALSE otherwise.
  2944. *
  2945. * @see hook_node_grants()
  2946. * @see _node_query_node_access_alter()
  2947. */
  2948. function node_access_view_all_nodes($account = NULL) {
  2949. global $user;
  2950. if (!$account) {
  2951. $account = $user;
  2952. }
  2953. // Statically cache results in an array keyed by $account->uid.
  2954. $access = &drupal_static(__FUNCTION__);
  2955. if (isset($access[$account->uid])) {
  2956. return $access[$account->uid];
  2957. }
  2958. // If no modules implement the node access system, access is always TRUE.
  2959. if (!module_implements('node_grants')) {
  2960. $access[$account->uid] = TRUE;
  2961. }
  2962. else {
  2963. $query = db_select('node_access');
  2964. $query->addExpression('COUNT(*)');
  2965. $query
  2966. ->condition('nid', 0)
  2967. ->condition('grant_view', 1, '>=');
  2968. $grants = db_or();
  2969. foreach (node_access_grants('view', $account) as $realm => $gids) {
  2970. foreach ($gids as $gid) {
  2971. $grants->condition(db_and()
  2972. ->condition('gid', $gid)
  2973. ->condition('realm', $realm)
  2974. );
  2975. }
  2976. }
  2977. if (count($grants) > 0 ) {
  2978. $query->condition($grants);
  2979. }
  2980. $access[$account->uid] = $query
  2981. ->execute()
  2982. ->fetchField();
  2983. }
  2984. return $access[$account->uid];
  2985. }
  2986. /**
  2987. * Implements hook_query_TAG_alter().
  2988. *
  2989. * This is the hook_query_alter() for queries tagged with 'node_access'. It adds
  2990. * node access checks for the user account given by the 'account' meta-data (or
  2991. * global $user if not provided), for an operation given by the 'op' meta-data
  2992. * (or 'view' if not provided; other possible values are 'update' and 'delete').
  2993. */
  2994. function node_query_node_access_alter(QueryAlterableInterface $query) {
  2995. _node_query_node_access_alter($query, 'node');
  2996. }
  2997. /**
  2998. * Implements hook_query_TAG_alter().
  2999. *
  3000. * This function implements the same functionality as
  3001. * node_query_node_access_alter() for the SQL field storage engine. Node access
  3002. * conditions are added for field values belonging to nodes only.
  3003. */
  3004. function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
  3005. _node_query_node_access_alter($query, 'entity');
  3006. }
  3007. /**
  3008. * Helper for node access functions.
  3009. *
  3010. * @param $query
  3011. * The query to add conditions to.
  3012. * @param $type
  3013. * Either 'node' or 'entity' depending on what sort of query it is. See
  3014. * node_query_node_access_alter() and node_query_entity_field_access_alter()
  3015. * for more.
  3016. */
  3017. function _node_query_node_access_alter($query, $type) {
  3018. global $user;
  3019. // Read meta-data from query, if provided.
  3020. if (!$account = $query->getMetaData('account')) {
  3021. $account = $user;
  3022. }
  3023. if (!$op = $query->getMetaData('op')) {
  3024. $op = 'view';
  3025. }
  3026. // If $account can bypass node access, or there are no node access modules,
  3027. // or the operation is 'view' and the $account has a global view grant
  3028. // (such as a view grant for node ID 0), we don't need to alter the query.
  3029. if (user_access('bypass node access', $account)) {
  3030. return;
  3031. }
  3032. if (!count(module_implements('node_grants'))) {
  3033. return;
  3034. }
  3035. if ($op == 'view' && node_access_view_all_nodes($account)) {
  3036. return;
  3037. }
  3038. $tables = $query->getTables();
  3039. $base_table = $query->getMetaData('base_table');
  3040. // If no base table is specified explicitly, search for one.
  3041. if (!$base_table) {
  3042. $fallback = '';
  3043. foreach ($tables as $alias => $table_info) {
  3044. if (!($table_info instanceof SelectQueryInterface)) {
  3045. $table = $table_info['table'];
  3046. // If the node table is in the query, it wins immediately.
  3047. if ($table == 'node') {
  3048. $base_table = $table;
  3049. break;
  3050. }
  3051. // Check whether the table has a foreign key to node.nid. If it does,
  3052. // do not run this check again as we found a base table and only node
  3053. // can triumph that.
  3054. if (!$base_table) {
  3055. // The schema is cached.
  3056. $schema = drupal_get_schema($table);
  3057. if (isset($schema['fields']['nid'])) {
  3058. if (isset($schema['foreign keys'])) {
  3059. foreach ($schema['foreign keys'] as $relation) {
  3060. if ($relation['table'] === 'node' && $relation['columns'] === array('nid' => 'nid')) {
  3061. $base_table = $table;
  3062. }
  3063. }
  3064. }
  3065. else {
  3066. // At least it's a nid. A table with a field called nid is very
  3067. // very likely to be a node.nid in a node access query.
  3068. $fallback = $table;
  3069. }
  3070. }
  3071. }
  3072. }
  3073. }
  3074. // If there is nothing else, use the fallback.
  3075. if (!$base_table) {
  3076. if ($fallback) {
  3077. watchdog('security', 'Your node listing query is using @fallback as a base table in a query tagged for node access. This might not be secure and might not even work. Specify foreign keys in your schema to node.nid ', array('@fallback' => $fallback), WATCHDOG_WARNING);
  3078. $base_table = $fallback;
  3079. }
  3080. else {
  3081. throw new Exception(t('Query tagged for node access but there is no nid. Add foreign keys to node.nid in schema to fix.'));
  3082. }
  3083. }
  3084. }
  3085. // Find all instances of the base table being joined -- could appear
  3086. // more than once in the query, and could be aliased. Join each one to
  3087. // the node_access table.
  3088. $grants = node_access_grants($op, $account);
  3089. if ($type == 'entity') {
  3090. // The original query looked something like:
  3091. // @code
  3092. // SELECT nid FROM sometable s
  3093. // INNER JOIN node_access na ON na.nid = s.nid
  3094. // WHERE ($node_access_conditions)
  3095. // @endcode
  3096. //
  3097. // Our query will look like:
  3098. // @code
  3099. // SELECT entity_type, entity_id
  3100. // FROM field_data_something s
  3101. // LEFT JOIN node_access na ON s.entity_id = na.nid
  3102. // WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
  3103. // @endcode
  3104. //
  3105. // So instead of directly adding to the query object, we need to collect
  3106. // all of the node access conditions in a separate db_and() object and
  3107. // then add it to the query at the end.
  3108. $node_conditions = db_and();
  3109. }
  3110. foreach ($tables as $nalias => $tableinfo) {
  3111. $table = $tableinfo['table'];
  3112. if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
  3113. // Set the subquery.
  3114. $subquery = db_select('node_access', 'na')
  3115. ->fields('na', array('nid'));
  3116. $grant_conditions = db_or();
  3117. // If any grant exists for the specified user, then user has access
  3118. // to the node for the specified operation.
  3119. foreach ($grants as $realm => $gids) {
  3120. foreach ($gids as $gid) {
  3121. $grant_conditions->condition(db_and()
  3122. ->condition('na.gid', $gid)
  3123. ->condition('na.realm', $realm)
  3124. );
  3125. }
  3126. }
  3127. // Attach conditions to the subquery for nodes.
  3128. if (count($grant_conditions->conditions())) {
  3129. $subquery->condition($grant_conditions);
  3130. }
  3131. $subquery->condition('na.grant_' . $op, 1, '>=');
  3132. $field = 'nid';
  3133. // Now handle entities.
  3134. if ($type == 'entity') {
  3135. // Set a common alias for entities.
  3136. $base_alias = $nalias;
  3137. $field = 'entity_id';
  3138. }
  3139. $subquery->where("$nalias.$field = na.nid");
  3140. // For an entity query, attach the subquery to entity conditions.
  3141. if ($type == 'entity') {
  3142. $node_conditions->exists($subquery);
  3143. }
  3144. // Otherwise attach it to the node query itself.
  3145. else {
  3146. $query->exists($subquery);
  3147. }
  3148. }
  3149. }
  3150. if ($type == 'entity' && count($subquery->conditions())) {
  3151. // All the node access conditions are only for field values belonging to
  3152. // nodes.
  3153. $node_conditions->condition("$base_alias.entity_type", 'node');
  3154. $or = db_or();
  3155. $or->condition($node_conditions);
  3156. // If the field value belongs to a non-node entity type then this function
  3157. // does not do anything with it.
  3158. $or->condition("$base_alias.entity_type", 'node', '<>');
  3159. // Add the compiled set of rules to the query.
  3160. $query->condition($or);
  3161. }
  3162. }
  3163. /**
  3164. * Gets the list of node access grants and writes them to the database.
  3165. *
  3166. * This function is called when a node is saved, and can also be called by
  3167. * modules if something other than a node save causes node access permissions to
  3168. * change. It collects all node access grants for the node from
  3169. * hook_node_access_records() implementations, allows these grants to be altered
  3170. * via hook_node_access_records_alter() implementations, and saves the collected
  3171. * and altered grants to the database.
  3172. *
  3173. * @param $node
  3174. * The $node to acquire grants for.
  3175. *
  3176. * @param $delete
  3177. * Whether to delete existing node access records before inserting new ones.
  3178. * Defaults to TRUE.
  3179. */
  3180. function node_access_acquire_grants($node, $delete = TRUE) {
  3181. $grants = module_invoke_all('node_access_records', $node);
  3182. // Let modules alter the grants.
  3183. drupal_alter('node_access_records', $grants, $node);
  3184. // If no grants are set and the node is published, then use the default grant.
  3185. if (empty($grants) && !empty($node->status)) {
  3186. $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
  3187. }
  3188. else {
  3189. // Retain grants by highest priority.
  3190. $grant_by_priority = array();
  3191. foreach ($grants as $g) {
  3192. $grant_by_priority[intval($g['priority'])][] = $g;
  3193. }
  3194. krsort($grant_by_priority);
  3195. $grants = array_shift($grant_by_priority);
  3196. }
  3197. node_access_write_grants($node, $grants, NULL, $delete);
  3198. }
  3199. /**
  3200. * Writes a list of grants to the database, deleting any previously saved ones.
  3201. *
  3202. * If a realm is provided, it will only delete grants from that realm, but it
  3203. * will always delete a grant from the 'all' realm. Modules that utilize
  3204. * node_access() can use this function when doing mass updates due to widespread
  3205. * permission changes.
  3206. *
  3207. * Note: Don't call this function directly from a contributed module. Call
  3208. * node_access_acquire_grants() instead.
  3209. *
  3210. * @param $node
  3211. * The node whose grants are being written.
  3212. * @param $grants
  3213. * A list of grants to write. Each grant is an array that must contain the
  3214. * following keys: realm, gid, grant_view, grant_update, grant_delete.
  3215. * The realm is specified by a particular module; the gid is as well, and
  3216. * is a module-defined id to define grant privileges. each grant_* field
  3217. * is a boolean value.
  3218. * @param $realm
  3219. * (optional) If provided, read/write grants for that realm only. Defaults to
  3220. * NULL.
  3221. * @param $delete
  3222. * (optional) If false, does not delete records. This is only for optimization
  3223. * purposes, and assumes the caller has already performed a mass delete of
  3224. * some form. Defaults to TRUE.
  3225. *
  3226. * @see node_access_acquire_grants()
  3227. */
  3228. function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE) {
  3229. if ($delete) {
  3230. $query = db_delete('node_access')->condition('nid', $node->nid);
  3231. if ($realm) {
  3232. $query->condition('realm', array($realm, 'all'), 'IN');
  3233. }
  3234. $query->execute();
  3235. }
  3236. // Only perform work when node_access modules are active.
  3237. if (!empty($grants) && count(module_implements('node_grants'))) {
  3238. $query = db_insert('node_access')->fields(array('nid', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete'));
  3239. foreach ($grants as $grant) {
  3240. if ($realm && $realm != $grant['realm']) {
  3241. continue;
  3242. }
  3243. // Only write grants; denies are implicit.
  3244. if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
  3245. $grant['nid'] = $node->nid;
  3246. $query->values($grant);
  3247. }
  3248. }
  3249. $query->execute();
  3250. }
  3251. }
  3252. /**
  3253. * Flags or unflags the node access grants for rebuilding.
  3254. *
  3255. * If the argument isn't specified, the current value of the flag is returned.
  3256. * When the flag is set, a message is displayed to users with 'access
  3257. * administration pages' permission, pointing to the 'rebuild' confirm form.
  3258. * This can be used as an alternative to direct node_access_rebuild calls,
  3259. * allowing administrators to decide when they want to perform the actual
  3260. * (possibly time consuming) rebuild. When unsure if the current user is an
  3261. * administrator, node_access_rebuild() should be used instead.
  3262. *
  3263. * @param $rebuild
  3264. * (Optional) The boolean value to be written.
  3265. *
  3266. * @return
  3267. * The current value of the flag if no value was provided for $rebuild.
  3268. *
  3269. * @see node_access_rebuild()
  3270. */
  3271. function node_access_needs_rebuild($rebuild = NULL) {
  3272. if (!isset($rebuild)) {
  3273. return variable_get('node_access_needs_rebuild', FALSE);
  3274. }
  3275. elseif ($rebuild) {
  3276. variable_set('node_access_needs_rebuild', TRUE);
  3277. }
  3278. else {
  3279. variable_del('node_access_needs_rebuild');
  3280. }
  3281. }
  3282. /**
  3283. * Rebuilds the node access database.
  3284. *
  3285. * This is occasionally needed by modules that make system-wide changes to
  3286. * access levels. When the rebuild is required by an admin-triggered action (e.g
  3287. * module settings form), calling node_access_needs_rebuild(TRUE) instead of
  3288. * node_access_rebuild() lets the user perform his changes and actually
  3289. * rebuild only once he is done.
  3290. *
  3291. * Note: As of Drupal 6, node access modules are not required to (and actually
  3292. * should not) call node_access_rebuild() in hook_enable/disable anymore.
  3293. *
  3294. * @see node_access_needs_rebuild()
  3295. *
  3296. * @param $batch_mode
  3297. * Set to TRUE to process in 'batch' mode, spawning processing over several
  3298. * HTTP requests (thus avoiding the risk of PHP timeout if the site has a
  3299. * large number of nodes).
  3300. * hook_update_N and any form submit handler are safe contexts to use the
  3301. * 'batch mode'. Less decidable cases (such as calls from hook_user,
  3302. * hook_taxonomy, etc...) might consider using the non-batch mode.
  3303. */
  3304. function node_access_rebuild($batch_mode = FALSE) {
  3305. db_delete('node_access')->execute();
  3306. // Only recalculate if the site is using a node_access module.
  3307. if (count(module_implements('node_grants'))) {
  3308. if ($batch_mode) {
  3309. $batch = array(
  3310. 'title' => t('Rebuilding content access permissions'),
  3311. 'operations' => array(
  3312. array('_node_access_rebuild_batch_operation', array()),
  3313. ),
  3314. 'finished' => '_node_access_rebuild_batch_finished'
  3315. );
  3316. batch_set($batch);
  3317. }
  3318. else {
  3319. // Try to allocate enough time to rebuild node grants
  3320. drupal_set_time_limit(240);
  3321. $nids = db_query("SELECT nid FROM {node}")->fetchCol();
  3322. foreach ($nids as $nid) {
  3323. $node = node_load($nid, NULL, TRUE);
  3324. // To preserve database integrity, only acquire grants if the node
  3325. // loads successfully.
  3326. if (!empty($node)) {
  3327. node_access_acquire_grants($node);
  3328. }
  3329. }
  3330. }
  3331. }
  3332. else {
  3333. // Not using any node_access modules. Add the default grant.
  3334. db_insert('node_access')
  3335. ->fields(array(
  3336. 'nid' => 0,
  3337. 'realm' => 'all',
  3338. 'gid' => 0,
  3339. 'grant_view' => 1,
  3340. 'grant_update' => 0,
  3341. 'grant_delete' => 0,
  3342. ))
  3343. ->execute();
  3344. }
  3345. if (!isset($batch)) {
  3346. drupal_set_message(t('Content permissions have been rebuilt.'));
  3347. node_access_needs_rebuild(FALSE);
  3348. cache_clear_all();
  3349. }
  3350. }
  3351. /**
  3352. * Performs batch operation for node_access_rebuild().
  3353. *
  3354. * This is a multistep operation: we go through all nodes by packs of 20. The
  3355. * batch processing engine interrupts processing and sends progress feedback
  3356. * after 1 second execution time.
  3357. *
  3358. * @param array $context
  3359. * An array of contextual key/value information for rebuild batch process.
  3360. */
  3361. function _node_access_rebuild_batch_operation(&$context) {
  3362. if (empty($context['sandbox'])) {
  3363. // Initiate multistep processing.
  3364. $context['sandbox']['progress'] = 0;
  3365. $context['sandbox']['current_node'] = 0;
  3366. $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  3367. }
  3368. // Process the next 20 nodes.
  3369. $limit = 20;
  3370. $nids = db_query_range("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, array(':nid' => $context['sandbox']['current_node']))->fetchCol();
  3371. $nodes = node_load_multiple($nids, array(), TRUE);
  3372. foreach ($nodes as $nid => $node) {
  3373. // To preserve database integrity, only acquire grants if the node
  3374. // loads successfully.
  3375. if (!empty($node)) {
  3376. node_access_acquire_grants($node);
  3377. }
  3378. $context['sandbox']['progress']++;
  3379. $context['sandbox']['current_node'] = $nid;
  3380. }
  3381. // Multistep processing : report progress.
  3382. if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  3383. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  3384. }
  3385. }
  3386. /**
  3387. * Performs post-processing for node_access_rebuild().
  3388. *
  3389. * @param bool $success
  3390. * A boolean indicating whether the re-build process has completed.
  3391. * @param array $results
  3392. * An array of results information.
  3393. * @param array $operations
  3394. * An array of function calls (not used in this function).
  3395. */
  3396. function _node_access_rebuild_batch_finished($success, $results, $operations) {
  3397. if ($success) {
  3398. drupal_set_message(t('The content access permissions have been rebuilt.'));
  3399. node_access_needs_rebuild(FALSE);
  3400. }
  3401. else {
  3402. drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
  3403. }
  3404. cache_clear_all();
  3405. }
  3406. /**
  3407. * @} End of "defgroup node_access".
  3408. */
  3409. /**
  3410. * @defgroup node_content Hook implementations for user-created content types
  3411. * @{
  3412. * Functions that implement hooks for user-created content types.
  3413. */
  3414. /**
  3415. * Implements hook_form().
  3416. */
  3417. function node_content_form($node, $form_state) {
  3418. // It is impossible to define a content type without implementing hook_form()
  3419. // @todo: remove this requirement.
  3420. $form = array();
  3421. $type = node_type_get_type($node);
  3422. if ($type->has_title) {
  3423. $form['title'] = array(
  3424. '#type' => 'textfield',
  3425. '#title' => check_plain($type->title_label),
  3426. '#required' => TRUE,
  3427. '#default_value' => $node->title,
  3428. '#maxlength' => 255,
  3429. '#weight' => -5,
  3430. );
  3431. }
  3432. return $form;
  3433. }
  3434. /**
  3435. * @} End of "defgroup node_content".
  3436. */
  3437. /**
  3438. * Implements hook_forms().
  3439. *
  3440. * All node forms share the same form handler.
  3441. */
  3442. function node_forms() {
  3443. $forms = array();
  3444. if ($types = node_type_get_types()) {
  3445. foreach (array_keys($types) as $type) {
  3446. $forms[$type . '_node_form']['callback'] = 'node_form';
  3447. }
  3448. }
  3449. return $forms;
  3450. }
  3451. /**
  3452. * Implements hook_action_info().
  3453. */
  3454. function node_action_info() {
  3455. return array(
  3456. 'node_publish_action' => array(
  3457. 'type' => 'node',
  3458. 'label' => t('Publish content'),
  3459. 'configurable' => FALSE,
  3460. 'behavior' => array('changes_property'),
  3461. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3462. ),
  3463. 'node_unpublish_action' => array(
  3464. 'type' => 'node',
  3465. 'label' => t('Unpublish content'),
  3466. 'configurable' => FALSE,
  3467. 'behavior' => array('changes_property'),
  3468. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3469. ),
  3470. 'node_make_sticky_action' => array(
  3471. 'type' => 'node',
  3472. 'label' => t('Make content sticky'),
  3473. 'configurable' => FALSE,
  3474. 'behavior' => array('changes_property'),
  3475. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3476. ),
  3477. 'node_make_unsticky_action' => array(
  3478. 'type' => 'node',
  3479. 'label' => t('Make content unsticky'),
  3480. 'configurable' => FALSE,
  3481. 'behavior' => array('changes_property'),
  3482. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3483. ),
  3484. 'node_promote_action' => array(
  3485. 'type' => 'node',
  3486. 'label' => t('Promote content to front page'),
  3487. 'configurable' => FALSE,
  3488. 'behavior' => array('changes_property'),
  3489. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3490. ),
  3491. 'node_unpromote_action' => array(
  3492. 'type' => 'node',
  3493. 'label' => t('Remove content from front page'),
  3494. 'configurable' => FALSE,
  3495. 'behavior' => array('changes_property'),
  3496. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3497. ),
  3498. 'node_assign_owner_action' => array(
  3499. 'type' => 'node',
  3500. 'label' => t('Change the author of content'),
  3501. 'configurable' => TRUE,
  3502. 'behavior' => array('changes_property'),
  3503. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3504. ),
  3505. 'node_save_action' => array(
  3506. 'type' => 'node',
  3507. 'label' => t('Save content'),
  3508. 'configurable' => FALSE,
  3509. 'triggers' => array('comment_insert', 'comment_update', 'comment_delete'),
  3510. ),
  3511. 'node_unpublish_by_keyword_action' => array(
  3512. 'type' => 'node',
  3513. 'label' => t('Unpublish content containing keyword(s)'),
  3514. 'configurable' => TRUE,
  3515. 'triggers' => array('node_presave', 'node_insert', 'node_update'),
  3516. ),
  3517. );
  3518. }
  3519. /**
  3520. * Sets the status of a node to 1 (published).
  3521. *
  3522. * @param $node
  3523. * A node object.
  3524. * @param $context
  3525. * (optional) Array of additional information about what triggered the action.
  3526. * Not used for this action.
  3527. *
  3528. * @ingroup actions
  3529. */
  3530. function node_publish_action($node, $context = array()) {
  3531. $node->status = NODE_PUBLISHED;
  3532. watchdog('action', 'Set @type %title to published.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3533. }
  3534. /**
  3535. * Sets the status of a node to 0 (unpublished).
  3536. *
  3537. * @param $node
  3538. * A node object.
  3539. * @param $context
  3540. * (optional) Array of additional information about what triggered the action.
  3541. * Not used for this action.
  3542. *
  3543. * @ingroup actions
  3544. */
  3545. function node_unpublish_action($node, $context = array()) {
  3546. $node->status = NODE_NOT_PUBLISHED;
  3547. watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3548. }
  3549. /**
  3550. * Sets the sticky-at-top-of-list property of a node to 1.
  3551. *
  3552. * @param $node
  3553. * A node object.
  3554. * @param $context
  3555. * (optional) Array of additional information about what triggered the action.
  3556. * Not used for this action.
  3557. *
  3558. * @ingroup actions
  3559. */
  3560. function node_make_sticky_action($node, $context = array()) {
  3561. $node->sticky = NODE_STICKY;
  3562. watchdog('action', 'Set @type %title to sticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3563. }
  3564. /**
  3565. * Sets the sticky-at-top-of-list property of a node to 0.
  3566. *
  3567. * @param $node
  3568. * A node object.
  3569. * @param $context
  3570. * (optional) Array of additional information about what triggered the action.
  3571. * Not used for this action.
  3572. *
  3573. * @ingroup actions
  3574. */
  3575. function node_make_unsticky_action($node, $context = array()) {
  3576. $node->sticky = NODE_NOT_STICKY;
  3577. watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3578. }
  3579. /**
  3580. * Sets the promote property of a node to 1.
  3581. *
  3582. * @param $node
  3583. * A node object.
  3584. * @param $context
  3585. * (optional) Array of additional information about what triggered the action.
  3586. * Not used for this action.
  3587. *
  3588. * @ingroup actions
  3589. */
  3590. function node_promote_action($node, $context = array()) {
  3591. $node->promote = NODE_PROMOTED;
  3592. watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3593. }
  3594. /**
  3595. * Sets the promote property of a node to 0.
  3596. *
  3597. * @param $node
  3598. * A node object.
  3599. * @param $context
  3600. * (optional) Array of additional information about what triggered the action.
  3601. * Not used for this action.
  3602. *
  3603. * @ingroup actions
  3604. */
  3605. function node_unpromote_action($node, $context = array()) {
  3606. $node->promote = NODE_NOT_PROMOTED;
  3607. watchdog('action', 'Removed @type %title from front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3608. }
  3609. /**
  3610. * Saves a node.
  3611. *
  3612. * @param $node
  3613. * The node to be saved.
  3614. *
  3615. * @ingroup actions
  3616. */
  3617. function node_save_action($node) {
  3618. node_save($node);
  3619. watchdog('action', 'Saved @type %title', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3620. }
  3621. /**
  3622. * Assigns ownership of a node to a user.
  3623. *
  3624. * @param $node
  3625. * A node object to modify.
  3626. * @param $context
  3627. * Array with the following elements:
  3628. * - 'owner_uid': User ID to assign to the node.
  3629. *
  3630. * @see node_assign_owner_action_form()
  3631. * @see node_assign_owner_action_validate()
  3632. * @see node_assign_owner_action_submit()
  3633. * @ingroup actions
  3634. */
  3635. function node_assign_owner_action($node, $context) {
  3636. $node->uid = $context['owner_uid'];
  3637. $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
  3638. watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' => node_type_get_name($node), '%title' => $node->title, '%name' => $owner_name));
  3639. }
  3640. /**
  3641. * Generates the settings form for node_assign_owner_action().
  3642. *
  3643. * @param $context
  3644. * Array of additional information about what triggered the action. Includes
  3645. * the following elements:
  3646. * - 'owner_uid': User ID to assign to the node.
  3647. *
  3648. * @see node_assign_owner_action_submit()
  3649. * @see node_assign_owner_action_validate()
  3650. *
  3651. * @ingroup forms
  3652. */
  3653. function node_assign_owner_action_form($context) {
  3654. $description = t('The username of the user to which you would like to assign ownership.');
  3655. $count = db_query("SELECT COUNT(*) FROM {users}")->fetchField();
  3656. $owner_name = '';
  3657. if (isset($context['owner_uid'])) {
  3658. $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
  3659. }
  3660. // Use dropdown for fewer than 200 users; textbox for more than that.
  3661. if (intval($count) < 200) {
  3662. $options = array();
  3663. $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name");
  3664. foreach ($result as $data) {
  3665. $options[$data->name] = $data->name;
  3666. }
  3667. $form['owner_name'] = array(
  3668. '#type' => 'select',
  3669. '#title' => t('Username'),
  3670. '#default_value' => $owner_name,
  3671. '#options' => $options,
  3672. '#description' => $description,
  3673. );
  3674. }
  3675. else {
  3676. $form['owner_name'] = array(
  3677. '#type' => 'textfield',
  3678. '#title' => t('Username'),
  3679. '#default_value' => $owner_name,
  3680. '#autocomplete_path' => 'user/autocomplete',
  3681. '#size' => '6',
  3682. '#maxlength' => '60',
  3683. '#description' => $description,
  3684. );
  3685. }
  3686. return $form;
  3687. }
  3688. /**
  3689. * Validates settings form for node_assign_owner_action().
  3690. *
  3691. * @see node_assign_owner_action_submit()
  3692. */
  3693. function node_assign_owner_action_validate($form, $form_state) {
  3694. $exists = (bool) db_query_range('SELECT 1 FROM {users} WHERE name = :name', 0, 1, array(':name' => $form_state['values']['owner_name']))->fetchField();
  3695. if (!$exists) {
  3696. form_set_error('owner_name', t('Enter a valid username.'));
  3697. }
  3698. }
  3699. /**
  3700. * Saves settings form for node_assign_owner_action().
  3701. *
  3702. * @see node_assign_owner_action_validate()
  3703. */
  3704. function node_assign_owner_action_submit($form, $form_state) {
  3705. // Username can change, so we need to store the ID, not the username.
  3706. $uid = db_query('SELECT uid from {users} WHERE name = :name', array(':name' => $form_state['values']['owner_name']))->fetchField();
  3707. return array('owner_uid' => $uid);
  3708. }
  3709. /**
  3710. * Generates settings form for node_unpublish_by_keyword_action().
  3711. *
  3712. * @param array $context
  3713. * Array of additional information about what triggered this action.
  3714. *
  3715. * @return array
  3716. * A form array.
  3717. *
  3718. * @see node_unpublish_by_keyword_action_submit()
  3719. */
  3720. function node_unpublish_by_keyword_action_form($context) {
  3721. $form['keywords'] = array(
  3722. '#title' => t('Keywords'),
  3723. '#type' => 'textarea',
  3724. '#description' => t('The content 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."'),
  3725. '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  3726. );
  3727. return $form;
  3728. }
  3729. /**
  3730. * Saves settings form for node_unpublish_by_keyword_action().
  3731. */
  3732. function node_unpublish_by_keyword_action_submit($form, $form_state) {
  3733. return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
  3734. }
  3735. /**
  3736. * Unpublishes a node containing certain keywords.
  3737. *
  3738. * @param $node
  3739. * A node object to modify.
  3740. * @param $context
  3741. * Array with the following elements:
  3742. * - 'keywords': Array of keywords. If any keyword is present in the rendered
  3743. * node, the node's status flag is set to unpublished.
  3744. *
  3745. * @ingroup actions
  3746. */
  3747. function node_unpublish_by_keyword_action($node, $context) {
  3748. foreach ($context['keywords'] as $keyword) {
  3749. $elements = node_view(clone $node);
  3750. if (strpos(drupal_render($elements), $keyword) !== FALSE || strpos($node->title, $keyword) !== FALSE) {
  3751. $node->status = NODE_NOT_PUBLISHED;
  3752. watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3753. break;
  3754. }
  3755. }
  3756. }
  3757. /**
  3758. * Implements hook_requirements().
  3759. */
  3760. function node_requirements($phase) {
  3761. $requirements = array();
  3762. if ($phase === 'runtime') {
  3763. // Only show rebuild button if there are either 0, or 2 or more, rows
  3764. // in the {node_access} table, or if there are modules that
  3765. // implement hook_node_grants().
  3766. $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
  3767. if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
  3768. $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
  3769. }
  3770. else {
  3771. $value = t('Disabled');
  3772. }
  3773. $description = t('If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions.');
  3774. $requirements['node_access'] = array(
  3775. 'title' => t('Node Access Permissions'),
  3776. 'value' => $value,
  3777. 'description' => $description . ' ' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild'),
  3778. );
  3779. }
  3780. return $requirements;
  3781. }
  3782. /**
  3783. * Implements hook_modules_enabled().
  3784. */
  3785. function node_modules_enabled($modules) {
  3786. // Check if any of the newly enabled modules require the node_access table to
  3787. // be rebuilt.
  3788. if (!node_access_needs_rebuild() && array_intersect($modules, module_implements('node_grants'))) {
  3789. node_access_needs_rebuild(TRUE);
  3790. }
  3791. }
  3792. /**
  3793. * Controller class for nodes.
  3794. *
  3795. * This extends the DrupalDefaultEntityController class, adding required
  3796. * special handling for node objects.
  3797. */
  3798. class NodeController extends DrupalDefaultEntityController {
  3799. protected function attachLoad(&$nodes, $revision_id = FALSE) {
  3800. // Create an array of nodes for each content type and pass this to the
  3801. // object type specific callback.
  3802. $typed_nodes = array();
  3803. foreach ($nodes as $id => $entity) {
  3804. $typed_nodes[$entity->type][$id] = $entity;
  3805. }
  3806. // Call object type specific callbacks on each typed array of nodes.
  3807. foreach ($typed_nodes as $node_type => $nodes_of_type) {
  3808. if (node_hook($node_type, 'load')) {
  3809. $function = node_type_get_base($node_type) . '_load';
  3810. $function($nodes_of_type);
  3811. }
  3812. }
  3813. // Besides the list of nodes, pass one additional argument to
  3814. // hook_node_load(), containing a list of node types that were loaded.
  3815. $argument = array_keys($typed_nodes);
  3816. $this->hookLoadArguments = array($argument);
  3817. parent::attachLoad($nodes, $revision_id);
  3818. }
  3819. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  3820. // Ensure that uid is taken from the {node} table,
  3821. // alias timestamp to revision_timestamp and add revision_uid.
  3822. $query = parent::buildQuery($ids, $conditions, $revision_id);
  3823. $fields =& $query->getFields();
  3824. unset($fields['timestamp']);
  3825. $query->addField('revision', 'timestamp', 'revision_timestamp');
  3826. $fields['uid']['table'] = 'base';
  3827. $query->addField('revision', 'uid', 'revision_uid');
  3828. return $query;
  3829. }
  3830. }
  3831. /**
  3832. * Implements hook_file_download_access().
  3833. */
  3834. function node_file_download_access($field, $entity_type, $entity) {
  3835. if ($entity_type == 'node') {
  3836. return node_access('view', $entity);
  3837. }
  3838. }