node.module 136 KB

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