node.module 136 KB

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