12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193 |
- <?php
- /**
- * @file
- * The core that allows content to be submitted to the site. Modules and
- * scripts may programmatically submit nodes using the usual form API pattern.
- */
- /**
- * Node is not published.
- */
- define('NODE_NOT_PUBLISHED', 0);
- /**
- * Node is published.
- */
- define('NODE_PUBLISHED', 1);
- /**
- * Node is not promoted to front page.
- */
- define('NODE_NOT_PROMOTED', 0);
- /**
- * Node is promoted to front page.
- */
- define('NODE_PROMOTED', 1);
- /**
- * Node is not sticky at top of the page.
- */
- define('NODE_NOT_STICKY', 0);
- /**
- * Node is sticky at top of the page.
- */
- define('NODE_STICKY', 1);
- /**
- * Nodes changed before this time are always marked as read.
- *
- * Nodes changed after this time may be marked new, updated, or read, depending
- * on their state for the current user. Defaults to 30 days ago.
- */
- define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
- /**
- * Modules should return this value from hook_node_access() to allow access to a node.
- */
- define('NODE_ACCESS_ALLOW', 'allow');
- /**
- * Modules should return this value from hook_node_access() to deny access to a node.
- */
- define('NODE_ACCESS_DENY', 'deny');
- /**
- * Modules should return this value from hook_node_access() to not affect node access.
- */
- define('NODE_ACCESS_IGNORE', NULL);
- /**
- * Implements hook_help().
- */
- function node_help($path, $arg) {
- // Remind site administrators about the {node_access} table being flagged
- // for rebuild. We don't need to issue the message on the confirm form, or
- // while the rebuild is being processed.
- if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
- && user_access('access administration pages') && node_access_needs_rebuild()) {
- if ($path == 'admin/reports/status') {
- $message = t('The content access permissions need to be rebuilt.');
- }
- else {
- $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')));
- }
- drupal_set_message($message, 'error');
- }
- switch ($path) {
- case 'admin/help#node':
- $output = '';
- $output .= '<h3>' . t('About') . '</h3>';
- $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>';
- $output .= '<h3>' . t('Uses') . '</h3>';
- $output .= '<dl>';
- $output .= '<dt>' . t('Creating content') . '</dt>';
- $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>';
- $output .= '<dt>' . t('Creating custom content types') . '</dt>';
- $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>';
- $output .= '<dt>' . t('Administering content') . '</dt>';
- $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>';
- $output .= '<dt>' . t('Creating revisions') . '</dt>';
- $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>';
- $output .= '<dt>' . t('User permissions') . '</dt>';
- $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>';
- $output .= '</dl>';
- return $output;
- case 'admin/structure/types/add':
- return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
- case 'admin/structure/types/manage/%/display':
- 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>' .
- '<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>';
- case 'node/%/revisions':
- return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert back to older versions.') . '</p>';
- case 'node/%/edit':
- $node = node_load($arg[1]);
- $type = node_type_get_type($node);
- return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
- }
- if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
- $type = node_type_get_type(str_replace('-', '_', $arg[2]));
- return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
- }
- }
- /**
- * Implements hook_theme().
- */
- function node_theme() {
- return array(
- 'node' => array(
- 'render element' => 'elements',
- 'template' => 'node',
- ),
- 'node_search_admin' => array(
- 'render element' => 'form',
- ),
- 'node_add_list' => array(
- 'variables' => array('content' => NULL),
- 'file' => 'node.pages.inc',
- ),
- 'node_preview' => array(
- 'variables' => array('node' => NULL),
- 'file' => 'node.pages.inc',
- ),
- 'node_admin_overview' => array(
- 'variables' => array('name' => NULL, 'type' => NULL),
- 'file' => 'content_types.inc',
- ),
- 'node_recent_block' => array(
- 'variables' => array('nodes' => NULL),
- ),
- 'node_recent_content' => array(
- 'variables' => array('node' => NULL),
- ),
- );
- }
- /**
- * Implements hook_cron().
- */
- function node_cron() {
- db_delete('history')
- ->condition('timestamp', NODE_NEW_LIMIT, '<')
- ->execute();
- }
- /**
- * Implements hook_entity_info().
- */
- function node_entity_info() {
- $return = array(
- 'node' => array(
- 'label' => t('Node'),
- 'controller class' => 'NodeController',
- 'base table' => 'node',
- 'revision table' => 'node_revision',
- 'uri callback' => 'node_uri',
- 'fieldable' => TRUE,
- 'entity keys' => array(
- 'id' => 'nid',
- 'revision' => 'vid',
- 'bundle' => 'type',
- 'label' => 'title',
- 'language' => 'language',
- ),
- 'bundle keys' => array(
- 'bundle' => 'type',
- ),
- 'bundles' => array(),
- 'view modes' => array(
- 'full' => array(
- 'label' => t('Full content'),
- 'custom settings' => FALSE,
- ),
- 'teaser' => array(
- 'label' => t('Teaser'),
- 'custom settings' => TRUE,
- ),
- 'rss' => array(
- 'label' => t('RSS'),
- 'custom settings' => FALSE,
- ),
- ),
- ),
- );
- // Search integration is provided by node.module, so search-related view modes
- // for nodes are defined here and not in search.module.
- if (module_exists('search')) {
- $return['node']['view modes'] += array(
- 'search_index' => array(
- 'label' => t('Search index'),
- 'custom settings' => FALSE,
- ),
- 'search_result' => array(
- 'label' => t('Search result highlighting input'),
- 'custom settings' => FALSE,
- ),
- );
- }
- // Bundles must provide a human readable name so we can create help and error
- // messages, and the path to attach Field admin pages to.
- foreach (node_type_get_names() as $type => $name) {
- $return['node']['bundles'][$type] = array(
- 'label' => $name,
- 'admin' => array(
- 'path' => 'admin/structure/types/manage/%node_type',
- 'real path' => 'admin/structure/types/manage/' . str_replace('_', '-', $type),
- 'bundle argument' => 4,
- 'access arguments' => array('administer content types'),
- ),
- );
- }
- return $return;
- }
- /**
- * Implements hook_field_display_ENTITY_TYPE_alter().
- */
- function node_field_display_node_alter(&$display, $context) {
- // Hide field labels in search index.
- if ($context['view_mode'] == 'search_index') {
- $display['label'] = 'hidden';
- }
- }
- /**
- * Implements callback_entity_info_uri().
- */
- function node_uri($node) {
- return array(
- 'path' => 'node/' . $node->nid,
- );
- }
- /**
- * Implements hook_admin_paths().
- */
- function node_admin_paths() {
- if (variable_get('node_admin_theme')) {
- $paths = array(
- 'node/*/edit' => TRUE,
- 'node/*/delete' => TRUE,
- 'node/*/revisions' => TRUE,
- 'node/*/revisions/*/revert' => TRUE,
- 'node/*/revisions/*/delete' => TRUE,
- 'node/add' => TRUE,
- 'node/add/*' => TRUE,
- );
- return $paths;
- }
- }
- /**
- * Gathers a listing of links to nodes.
- *
- * @param $result
- * A database result object from a query to fetch node entities. If your
- * query joins the {node_comment_statistics} table so that the comment_count
- * field is available, a title attribute will be added to show the number of
- * comments.
- * @param $title
- * A heading for the resulting list.
- *
- * @return
- * A renderable array containing a list of linked node titles fetched from
- * $result, or FALSE if there are no rows in $result.
- */
- function node_title_list($result, $title = NULL) {
- $items = array();
- $num_rows = FALSE;
- foreach ($result as $node) {
- $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());
- $num_rows = TRUE;
- }
- return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
- }
- /**
- * Updates the 'last viewed' timestamp of the specified node for current user.
- *
- * @param $node
- * A node object.
- */
- function node_tag_new($node) {
- global $user;
- if ($user->uid) {
- db_merge('history')
- ->key(array(
- 'uid' => $user->uid,
- 'nid' => $node->nid,
- ))
- ->fields(array('timestamp' => REQUEST_TIME))
- ->execute();
- }
- }
- /**
- * Retrieves the timestamp for the current user's last view of a specified node.
- *
- * @param $nid
- * A node ID.
- *
- * @return
- * If a node has been previously viewed by the user, the timestamp in seconds
- * of when the last view occurred; otherwise, zero.
- */
- function node_last_viewed($nid) {
- global $user;
- $history = &drupal_static(__FUNCTION__, array());
- if (!isset($history[$nid])) {
- $history[$nid] = db_query("SELECT timestamp FROM {history} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $nid))->fetchObject();
- }
- return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
- }
- /**
- * Determines the type of marker to be displayed for a given node.
- *
- * @param $nid
- * Node ID whose history supplies the "last viewed" timestamp.
- * @param $timestamp
- * Time which is compared against node's "last viewed" timestamp.
- *
- * @return
- * One of the MARK constants.
- */
- function node_mark($nid, $timestamp) {
- global $user;
- $cache = &drupal_static(__FUNCTION__, array());
- if (!$user->uid) {
- return MARK_READ;
- }
- if (!isset($cache[$nid])) {
- $cache[$nid] = node_last_viewed($nid);
- }
- if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
- return MARK_NEW;
- }
- elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
- return MARK_UPDATED;
- }
- return MARK_READ;
- }
- /**
- * Extracts the type name.
- *
- * @param $node
- * Either a string or object, containing the node type information.
- *
- * @return
- * Node type of the passed-in data.
- */
- function _node_extract_type($node) {
- return is_object($node) ? $node->type : $node;
- }
- /**
- * Returns a list of all the available node types.
- *
- * This list can include types that are queued for addition or deletion.
- * See _node_types_build() for details.
- *
- * @return
- * An array of node types, as objects, keyed by the type.
- *
- * @see node_type_get_type()
- */
- function node_type_get_types() {
- return _node_types_build()->types;
- }
- /**
- * Returns the node type of the passed node or node type string.
- *
- * @param $node
- * A node object or string that indicates the node type to return.
- *
- * @return
- * A single node type, as an object, or FALSE if the node type is not found.
- * The node type is an object containing fields from hook_node_info() return
- * values, as well as the field 'type' (the machine-readable type) and other
- * fields used internally and defined in _node_types_build(),
- * hook_node_info(), and node_type_set_defaults().
- */
- function node_type_get_type($node) {
- $type = _node_extract_type($node);
- $types = _node_types_build()->types;
- return isset($types[$type]) ? $types[$type] : FALSE;
- }
- /**
- * Returns the node type base of the passed node or node type string.
- *
- * The base indicates which module implements this node type and is used to
- * execute node-type-specific hooks. For types defined in the user interface
- * and managed by node.module, the base is 'node_content'.
- *
- * @param $node
- * A node object or string that indicates the node type to return.
- *
- * @return
- * The node type base or FALSE if the node type is not found.
- *
- * @see node_invoke()
- */
- function node_type_get_base($node) {
- $type = _node_extract_type($node);
- $types = _node_types_build()->types;
- return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE;
- }
- /**
- * Returns a list of available node type names.
- *
- * This list can include types that are queued for addition or deletion.
- * See _node_types_build() for details.
- *
- * @return
- * An array of node type names, keyed by the type.
- */
- function node_type_get_names() {
- return _node_types_build()->names;
- }
- /**
- * Returns the node type name of the passed node or node type string.
- *
- * @param $node
- * A node object or string that indicates the node type to return.
- *
- * @return
- * The node type name or FALSE if the node type is not found.
- */
- function node_type_get_name($node) {
- $type = _node_extract_type($node);
- $types = _node_types_build()->names;
- return isset($types[$type]) ? $types[$type] : FALSE;
- }
- /**
- * Updates the database cache of node types.
- *
- * All new module-defined node types are saved to the database via a call to
- * node_type_save(), and obsolete ones are deleted via a call to
- * node_type_delete(). See _node_types_build() for an explanation of the new
- * and obsolete types.
- *
- * @see _node_types_build()
- */
- function node_types_rebuild() {
- _node_types_build(TRUE);
- }
- /**
- * Menu argument loader: loads a node type by string.
- *
- * @param $name
- * The machine-readable name of a node type to load, where '_' is replaced
- * with '-'.
- *
- * @return
- * A node type object or FALSE if $name does not exist.
- */
- function node_type_load($name) {
- return node_type_get_type(strtr($name, array('-' => '_')));
- }
- /**
- * Saves a node type to the database.
- *
- * @param object $info
- * The node type to save; an object with the following properties:
- * - type: A string giving the machine name of the node type.
- * - name: A string giving the human-readable name of the node type.
- * - base: A string that indicates the base string for hook functions. For
- * example, 'node_content' is the value used by the UI when creating a new
- * node type.
- * - description: A string that describes the node type.
- * - help: A string giving the help information shown to the user when
- * creating a node of this type.
- * - custom: TRUE or FALSE indicating whether this type is defined by a module
- * (FALSE) or by a user (TRUE) via Add Content Type.
- * - modified: TRUE or FALSE indicating whether this type has been modified by
- * an administrator. Currently not used in any way.
- * - locked: TRUE or FALSE indicating whether the administrator can change the
- * machine name of this type.
- * - disabled: TRUE or FALSE indicating whether this type has been disabled.
- * - has_title: TRUE or FALSE indicating whether this type uses the node title
- * field.
- * - title_label: A string containing the label for the title.
- * - module: A string giving the module defining this type of node.
- * - orig_type: A string giving the original machine-readable name of this
- * node type. This may be different from the current type name if the
- * 'locked' key is FALSE.
- *
- * @return int
- * A status flag indicating the outcome of the operation, either SAVED_NEW or
- * SAVED_UPDATED.
- */
- function node_type_save($info) {
- $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
- $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
- $type = node_type_set_defaults($info);
- $fields = array(
- 'type' => (string) $type->type,
- 'name' => (string) $type->name,
- 'base' => (string) $type->base,
- 'has_title' => (int) $type->has_title,
- 'title_label' => (string) $type->title_label,
- 'description' => (string) $type->description,
- 'help' => (string) $type->help,
- 'custom' => (int) $type->custom,
- 'modified' => (int) $type->modified,
- 'locked' => (int) $type->locked,
- 'disabled' => (int) $type->disabled,
- 'module' => $type->module,
- );
- if ($is_existing) {
- db_update('node_type')
- ->fields($fields)
- ->condition('type', $existing_type)
- ->execute();
- if (!empty($type->old_type) && $type->old_type != $type->type) {
- field_attach_rename_bundle('node', $type->old_type, $type->type);
- }
- module_invoke_all('node_type_update', $type);
- $status = SAVED_UPDATED;
- }
- else {
- $fields['orig_type'] = (string) $type->orig_type;
- db_insert('node_type')
- ->fields($fields)
- ->execute();
- field_attach_create_bundle('node', $type->type);
- module_invoke_all('node_type_insert', $type);
- $status = SAVED_NEW;
- }
- // Clear the node type cache.
- node_type_cache_reset();
- return $status;
- }
- /**
- * Adds default body field to a node type.
- *
- * @param $type
- * A node type object.
- * @param $label
- * The label for the body instance.
- *
- * @return
- * Body field instance.
- */
- function node_add_body_field($type, $label = 'Body') {
- // Add or remove the body field, as needed.
- $field = field_info_field('body');
- $instance = field_info_instance('node', 'body', $type->type);
- if (empty($field)) {
- $field = array(
- 'field_name' => 'body',
- 'type' => 'text_with_summary',
- 'entity_types' => array('node'),
- );
- $field = field_create_field($field);
- }
- if (empty($instance)) {
- $instance = array(
- 'field_name' => 'body',
- 'entity_type' => 'node',
- 'bundle' => $type->type,
- 'label' => $label,
- 'widget' => array('type' => 'text_textarea_with_summary'),
- 'settings' => array('display_summary' => TRUE),
- 'display' => array(
- 'default' => array(
- 'label' => 'hidden',
- 'type' => 'text_default',
- ),
- 'teaser' => array(
- 'label' => 'hidden',
- 'type' => 'text_summary_or_trimmed',
- ),
- ),
- );
- $instance = field_create_instance($instance);
- }
- return $instance;
- }
- /**
- * Implements hook_field_extra_fields().
- */
- function node_field_extra_fields() {
- $extra = array();
- foreach (node_type_get_types() as $type) {
- if ($type->has_title) {
- $extra['node'][$type->type] = array(
- 'form' => array(
- 'title' => array(
- 'label' => $type->title_label,
- 'description' => t('Node module element'),
- 'weight' => -5,
- ),
- ),
- );
- }
- }
- return $extra;
- }
- /**
- * Deletes a node type from the database.
- *
- * @param $type
- * The machine-readable name of the node type to be deleted.
- */
- function node_type_delete($type) {
- $info = node_type_get_type($type);
- db_delete('node_type')
- ->condition('type', $type)
- ->execute();
- field_attach_delete_bundle('node', $type);
- module_invoke_all('node_type_delete', $info);
- // Clear the node type cache.
- node_type_cache_reset();
- }
- /**
- * Updates all nodes of one type to be of another type.
- *
- * @param $old_type
- * The current node type of the nodes.
- * @param $type
- * The new node type of the nodes.
- *
- * @return
- * The number of nodes whose node type field was modified.
- */
- function node_type_update_nodes($old_type, $type) {
- return db_update('node')
- ->fields(array('type' => $type))
- ->condition('type', $old_type)
- ->execute();
- }
- /**
- * Builds and returns the list of available node types.
- *
- * The list of types is built by invoking hook_node_info() on all modules and
- * comparing this information with the node types in the {node_type} table.
- * These two information sources are not synchronized during module installation
- * until node_types_rebuild() is called.
- *
- * @param $rebuild
- * TRUE to rebuild node types. Equivalent to calling node_types_rebuild().
- *
- * @return
- * An object with two properties:
- * - names: Associative array of the names of node types, keyed by the type.
- * - types: Associative array of node type objects, keyed by the type.
- * Both of these arrays will include new types that have been defined by
- * hook_node_info() implementations but not yet saved in the {node_type}
- * table. These are indicated in the type object by $type->is_new being set
- * to the value 1. These arrays will also include obsolete types: types that
- * were previously defined by modules that have now been disabled, or for
- * whatever reason are no longer being defined in hook_node_info()
- * implementations, but are still in the database. These are indicated in the
- * type object by $type->disabled being set to TRUE.
- */
- function _node_types_build($rebuild = FALSE) {
- $cid = 'node_types:' . $GLOBALS['language']->language;
- if (!$rebuild) {
- $_node_types = &drupal_static(__FUNCTION__);
- if (isset($_node_types)) {
- return $_node_types;
- }
- if ($cache = cache_get($cid)) {
- $_node_types = $cache->data;
- return $_node_types;
- }
- }
- $_node_types = (object) array('types' => array(), 'names' => array());
- foreach (module_implements('node_info') as $module) {
- $info_array = module_invoke($module, 'node_info');
- foreach ($info_array as $type => $info) {
- $info['type'] = $type;
- $_node_types->types[$type] = node_type_set_defaults($info);
- $_node_types->types[$type]->module = $module;
- $_node_types->names[$type] = $info['name'];
- }
- }
- $query = db_select('node_type', 'nt')
- ->addTag('translatable')
- ->addTag('node_type_access')
- ->fields('nt')
- ->orderBy('nt.type', 'ASC');
- if (!$rebuild) {
- $query->condition('disabled', 0);
- }
- foreach ($query->execute() as $type_object) {
- $type_db = $type_object->type;
- // Original disabled value.
- $disabled = $type_object->disabled;
- // Check for node types from disabled modules and mark their types for removal.
- // Types defined by the node module in the database (rather than by a separate
- // module using hook_node_info) have a base value of 'node_content'. The isset()
- // check prevents errors on old (pre-Drupal 7) databases.
- if (isset($type_object->base) && $type_object->base != 'node_content' && empty($_node_types->types[$type_db])) {
- $type_object->disabled = TRUE;
- }
- if (isset($_node_types->types[$type_db])) {
- $type_object->disabled = FALSE;
- }
- if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
- $_node_types->types[$type_db] = $type_object;
- $_node_types->names[$type_db] = $type_object->name;
- if ($type_db != $type_object->orig_type) {
- unset($_node_types->types[$type_object->orig_type]);
- unset($_node_types->names[$type_object->orig_type]);
- }
- }
- $_node_types->types[$type_db]->disabled = $type_object->disabled;
- $_node_types->types[$type_db]->disabled_changed = $disabled != $type_object->disabled;
- }
- if ($rebuild) {
- foreach ($_node_types->types as $type => $type_object) {
- if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
- node_type_save($type_object);
- }
- }
- }
- asort($_node_types->names);
- cache_set($cid, $_node_types);
- return $_node_types;
- }
- /**
- * Clears the node type cache.
- */
- function node_type_cache_reset() {
- cache_clear_all('node_types:', 'cache', TRUE);
- drupal_static_reset('_node_types_build');
- }
- /**
- * Sets the default values for a node type.
- *
- * The defaults are appropriate for a type defined through hook_node_info(),
- * since 'custom' is TRUE for types defined in the user interface, and FALSE
- * for types defined by modules. (The 'custom' flag prevents types from being
- * deleted through the user interface.) Also, the default for 'locked' is TRUE,
- * which prevents users from changing the machine name of the type.
- *
- * @param $info
- * (optional) An object or array containing values to override the defaults.
- * See hook_node_info() for details on what the array elements mean. Defaults
- * to an empty array.
- *
- * @return
- * A node type object, with missing values in $info set to their defaults.
- */
- function node_type_set_defaults($info = array()) {
- $info = (array) $info;
- $new_type = $info + array(
- 'type' => '',
- 'name' => '',
- 'base' => '',
- 'description' => '',
- 'help' => '',
- 'custom' => 0,
- 'modified' => 0,
- 'locked' => 1,
- 'disabled' => 0,
- 'is_new' => 1,
- 'has_title' => 1,
- 'title_label' => 'Title',
- );
- $new_type = (object) $new_type;
- // If the type has no title, set an empty label.
- if (!$new_type->has_title) {
- $new_type->title_label = '';
- }
- if (empty($new_type->module)) {
- $new_type->module = $new_type->base == 'node_content' ? 'node' : '';
- }
- $new_type->orig_type = isset($info['type']) ? $info['type'] : '';
- return $new_type;
- }
- /**
- * Implements hook_rdf_mapping().
- */
- function node_rdf_mapping() {
- return array(
- array(
- 'type' => 'node',
- 'bundle' => RDF_DEFAULT_BUNDLE,
- 'mapping' => array(
- 'rdftype' => array('sioc:Item', 'foaf:Document'),
- 'title' => array(
- 'predicates' => array('dc:title'),
- ),
- 'created' => array(
- 'predicates' => array('dc:date', 'dc:created'),
- 'datatype' => 'xsd:dateTime',
- 'callback' => 'date_iso8601',
- ),
- 'changed' => array(
- 'predicates' => array('dc:modified'),
- 'datatype' => 'xsd:dateTime',
- 'callback' => 'date_iso8601',
- ),
- 'body' => array(
- 'predicates' => array('content:encoded'),
- ),
- 'uid' => array(
- 'predicates' => array('sioc:has_creator'),
- 'type' => 'rel',
- ),
- 'name' => array(
- 'predicates' => array('foaf:name'),
- ),
- 'comment_count' => array(
- 'predicates' => array('sioc:num_replies'),
- 'datatype' => 'xsd:integer',
- ),
- 'last_activity' => array(
- 'predicates' => array('sioc:last_activity_date'),
- 'datatype' => 'xsd:dateTime',
- 'callback' => 'date_iso8601',
- ),
- ),
- ),
- );
- }
- /**
- * Determines whether a node hook exists.
- *
- * @param $node
- * A node object or a string containing the node type.
- * @param $hook
- * A string containing the name of the hook.
- *
- * @return
- * TRUE if the $hook exists in the node type of $node.
- */
- function node_hook($node, $hook) {
- $base = node_type_get_base($node);
- return module_hook($base, $hook);
- }
- /**
- * Invokes a node hook.
- *
- * @param $node
- * A node object or a string containing the node type.
- * @param $hook
- * A string containing the name of the hook.
- * @param $a2, $a3, $a4
- * Arguments to pass on to the hook, after the $node argument.
- *
- * @return
- * The returned value of the invoked hook.
- */
- function node_invoke($node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
- if (node_hook($node, $hook)) {
- $base = node_type_get_base($node);
- $function = $base . '_' . $hook;
- return ($function($node, $a2, $a3, $a4));
- }
- }
- /**
- * Loads node entities from the database.
- *
- * This function should be used whenever you need to load more than one node
- * from the database. Nodes are loaded into memory and will not require database
- * access if loaded again during the same page request.
- *
- * @see entity_load()
- * @see EntityFieldQuery
- *
- * @param $nids
- * An array of node IDs.
- * @param $conditions
- * (deprecated) An associative array of conditions on the {node}
- * table, where the keys are the database fields and the values are the
- * values those fields must have. Instead, it is preferable to use
- * EntityFieldQuery to retrieve a list of entity IDs loadable by
- * this function.
- * @param $reset
- * Whether to reset the internal node_load cache.
- *
- * @return
- * An array of node objects indexed by nid.
- *
- * @todo Remove $conditions in Drupal 8.
- */
- function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) {
- return entity_load('node', $nids, $conditions, $reset);
- }
- /**
- * Loads a node object from the database.
- *
- * @param $nid
- * The node ID.
- * @param $vid
- * The revision ID.
- * @param $reset
- * Whether to reset the node_load_multiple cache.
- *
- * @return
- * A fully-populated node object, or FALSE if the node is not found.
- */
- function node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
- $nids = (isset($nid) ? array($nid) : array());
- $conditions = (isset($vid) ? array('vid' => $vid) : array());
- $node = node_load_multiple($nids, $conditions, $reset);
- return $node ? reset($node) : FALSE;
- }
- /**
- * Prepares a node object for editing.
- *
- * Fills in a few default values, and then invokes hook_prepare() on the node
- * type module, and hook_node_prepare() on all modules.
- *
- * @param $node
- * A node object.
- */
- function node_object_prepare($node) {
- // Set up default values, if required.
- $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
- // If this is a new node, fill in the default values.
- if (!isset($node->nid) || isset($node->is_new)) {
- foreach (array('status', 'promote', 'sticky') as $key) {
- // Multistep node forms might have filled in something already.
- if (!isset($node->$key)) {
- $node->$key = (int) in_array($key, $node_options);
- }
- }
- global $user;
- $node->uid = $user->uid;
- $node->created = REQUEST_TIME;
- }
- else {
- $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
- // Remove the log message from the original node object.
- $node->log = NULL;
- }
- // Always use the default revision setting.
- $node->revision = in_array('revision', $node_options);
- node_invoke($node, 'prepare');
- module_invoke_all('node_prepare', $node);
- }
- /**
- * Implements hook_validate().
- *
- * Performs validation checks on the given node.
- */
- function node_validate($node, $form, &$form_state) {
- if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
- 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.'));
- }
- // Validate the "authored by" field.
- if (!empty($node->name) && !($account = user_load_by_name($node->name))) {
- // The use of empty() is mandatory in the context of usernames
- // as the empty string denotes the anonymous user. In case we
- // are dealing with an anonymous user we set the user ID to 0.
- form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
- }
- // Validate the "authored on" field.
- if (!empty($node->date) && strtotime($node->date) === FALSE) {
- form_set_error('date', t('You have to specify a valid date.'));
- }
- // Invoke hook_validate() for node type specific validation and
- // hook_node_validate() for miscellaneous validation needed by modules. Can't
- // use node_invoke() or module_invoke_all(), because $form_state must be
- // receivable by reference.
- $function = node_type_get_base($node) . '_validate';
- if (function_exists($function)) {
- $function($node, $form, $form_state);
- }
- foreach (module_implements('node_validate') as $module) {
- $function = $module . '_node_validate';
- $function($node, $form, $form_state);
- }
- }
- /**
- * Prepares node for saving by populating author and creation date.
- *
- * @param $node
- * A node object.
- *
- * @return
- * An updated node object.
- */
- function node_submit($node) {
- // A user might assign the node author by entering a user name in the node
- // form, which we then need to translate to a user ID.
- if (isset($node->name)) {
- if ($account = user_load_by_name($node->name)) {
- $node->uid = $account->uid;
- }
- else {
- $node->uid = 0;
- }
- }
- $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
- $node->validated = TRUE;
- return $node;
- }
- /**
- * Saves changes to a node or adds a new node.
- *
- * @param $node
- * The $node object to be saved. If $node->nid is
- * omitted (or $node->is_new is TRUE), a new node will be added.
- */
- function node_save($node) {
- $transaction = db_transaction();
- try {
- // Load the stored entity, if any.
- if (!empty($node->nid) && !isset($node->original)) {
- $node->original = entity_load_unchanged('node', $node->nid);
- }
- field_attach_presave('node', $node);
- global $user;
- // Determine if we will be inserting a new node.
- if (!isset($node->is_new)) {
- $node->is_new = empty($node->nid);
- }
- // Set the timestamp fields.
- if (empty($node->created)) {
- $node->created = REQUEST_TIME;
- }
- // The changed timestamp is always updated for bookkeeping purposes,
- // for example: revisions, searching, etc.
- $node->changed = REQUEST_TIME;
- $node->timestamp = REQUEST_TIME;
- $update_node = TRUE;
- // Let modules modify the node before it is saved to the database.
- module_invoke_all('node_presave', $node);
- module_invoke_all('entity_presave', $node, 'node');
- if ($node->is_new || !empty($node->revision)) {
- // When inserting either a new node or a new node revision, $node->log
- // must be set because {node_revision}.log is a text column and therefore
- // cannot have a default value. However, it might not be set at this
- // point (for example, if the user submitting a node form does not have
- // permission to create revisions), so we ensure that it is at least an
- // empty string in that case.
- // @todo: Make the {node_revision}.log column nullable so that we can
- // remove this check.
- if (!isset($node->log)) {
- $node->log = '';
- }
- }
- elseif (!isset($node->log) || $node->log === '') {
- // If we are updating an existing node without adding a new revision, we
- // need to make sure $node->log is unset whenever it is empty. As long as
- // $node->log is unset, drupal_write_record() will not attempt to update
- // the existing database column when re-saving the revision; therefore,
- // this code allows us to avoid clobbering an existing log entry with an
- // empty one.
- unset($node->log);
- }
- // When saving a new node revision, unset any existing $node->vid so as to
- // ensure that a new revision will actually be created, then store the old
- // revision ID in a separate property for use by node hook implementations.
- if (!$node->is_new && !empty($node->revision) && $node->vid) {
- $node->old_vid = $node->vid;
- unset($node->vid);
- }
- // Save the node and node revision.
- if ($node->is_new) {
- // For new nodes, save new records for both the node itself and the node
- // revision.
- drupal_write_record('node', $node);
- _node_save_revision($node, $user->uid);
- $op = 'insert';
- }
- else {
- // For existing nodes, update the node record which matches the value of
- // $node->nid.
- drupal_write_record('node', $node, 'nid');
- // Then, if a new node revision was requested, save a new record for
- // that; otherwise, update the node revision record which matches the
- // value of $node->vid.
- if (!empty($node->revision)) {
- _node_save_revision($node, $user->uid);
- }
- else {
- _node_save_revision($node, $user->uid, 'vid');
- $update_node = FALSE;
- }
- $op = 'update';
- }
- if ($update_node) {
- db_update('node')
- ->fields(array('vid' => $node->vid))
- ->condition('nid', $node->nid)
- ->execute();
- }
- // Call the node specific callback (if any). This can be
- // node_invoke($node, 'insert') or
- // node_invoke($node, 'update').
- node_invoke($node, $op);
- // Save fields.
- $function = "field_attach_$op";
- $function('node', $node);
- module_invoke_all('node_' . $op, $node);
- module_invoke_all('entity_' . $op, $node, 'node');
- // Update the node access table for this node.
- node_access_acquire_grants($node);
- // Clear internal properties.
- unset($node->is_new);
- unset($node->original);
- // Clear the static loading cache.
- entity_get_controller('node')->resetCache(array($node->nid));
- // Ignore slave server temporarily to give time for the
- // saved node to be propagated to the slave.
- db_ignore_slave();
- }
- catch (Exception $e) {
- $transaction->rollback();
- watchdog_exception('node', $e);
- throw $e;
- }
- }
- /**
- * Helper function to save a revision with the uid of the current user.
- *
- * The resulting revision ID is available afterward in $node->vid.
- *
- * @param $node
- * A node object.
- * @param $uid
- * The current user's UID.
- * @param $update
- * (optional) An array of primary keys' field names to update.
- */
- function _node_save_revision($node, $uid, $update = NULL) {
- $temp_uid = $node->uid;
- $node->uid = $uid;
- if (isset($update)) {
- drupal_write_record('node_revision', $node, $update);
- }
- else {
- drupal_write_record('node_revision', $node);
- }
- // Have node object still show node owner's uid, not revision author's.
- $node->uid = $temp_uid;
- }
- /**
- * Deletes a node.
- *
- * @param $nid
- * A node ID.
- */
- function node_delete($nid) {
- node_delete_multiple(array($nid));
- }
- /**
- * Deletes multiple nodes.
- *
- * @param $nids
- * An array of node IDs.
- */
- function node_delete_multiple($nids) {
- $transaction = db_transaction();
- if (!empty($nids)) {
- $nodes = node_load_multiple($nids, array());
- try {
- foreach ($nodes as $nid => $node) {
- // Call the node-specific callback (if any):
- node_invoke($node, 'delete');
- module_invoke_all('node_delete', $node);
- module_invoke_all('entity_delete', $node, 'node');
- field_attach_delete('node', $node);
- // Remove this node from the search index if needed.
- // This code is implemented in node module rather than in search module,
- // because node module is implementing search module's API, not the other
- // way around.
- if (module_exists('search')) {
- search_reindex($nid, 'node');
- }
- }
- // Delete after calling hooks so that they can query node tables as needed.
- db_delete('node')
- ->condition('nid', $nids, 'IN')
- ->execute();
- db_delete('node_revision')
- ->condition('nid', $nids, 'IN')
- ->execute();
- db_delete('history')
- ->condition('nid', $nids, 'IN')
- ->execute();
- db_delete('node_access')
- ->condition('nid', $nids, 'IN')
- ->execute();
- }
- catch (Exception $e) {
- $transaction->rollback();
- watchdog_exception('node', $e);
- throw $e;
- }
- // Clear the page and block and node_load_multiple caches.
- entity_get_controller('node')->resetCache();
- }
- }
- /**
- * Deletes a node revision.
- *
- * @param $revision_id
- * The revision ID to delete.
- */
- function node_revision_delete($revision_id) {
- if ($revision = node_load(NULL, $revision_id)) {
- // Prevent deleting the current revision.
- $node = node_load($revision->nid);
- if ($revision_id == $node->vid) {
- return FALSE;
- }
- db_delete('node_revision')
- ->condition('nid', $revision->nid)
- ->condition('vid', $revision->vid)
- ->execute();
- module_invoke_all('node_revision_delete', $revision);
- field_attach_delete_revision('node', $revision);
- return TRUE;
- }
- return FALSE;
- }
- /**
- * Generates an array for rendering the given node.
- *
- * @param $node
- * A node object.
- * @param $view_mode
- * View mode, e.g. 'full', 'teaser'...
- * @param $langcode
- * (optional) A language code to use for rendering. Defaults to the global
- * content language of the current request.
- *
- * @return
- * An array as expected by drupal_render().
- */
- function node_view($node, $view_mode = 'full', $langcode = NULL) {
- if (!isset($langcode)) {
- $langcode = $GLOBALS['language_content']->language;
- }
- // Populate $node->content with a render() array.
- node_build_content($node, $view_mode, $langcode);
- $build = $node->content;
- // We don't need duplicate rendering info in node->content.
- unset($node->content);
- $build += array(
- '#theme' => 'node',
- '#node' => $node,
- '#view_mode' => $view_mode,
- '#language' => $langcode,
- );
- // Add contextual links for this node, except when the node is already being
- // displayed on its own page. Modules may alter this behavior (for example,
- // to restrict contextual links to certain view modes) by implementing
- // hook_node_view_alter().
- if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
- $build['#contextual_links']['node'] = array('node', array($node->nid));
- }
- // Allow modules to modify the structured node.
- $type = 'node';
- drupal_alter(array('node_view', 'entity_view'), $build, $type);
- return $build;
- }
- /**
- * Builds a structured array representing the node's content.
- *
- * The content built for the node (field values, comments, file attachments or
- * other node components) will vary depending on the $view_mode parameter.
- *
- * Drupal core defines the following view modes for nodes, with the following
- * default use cases:
- * - full (default): node is being displayed on its own page (node/123)
- * - teaser: node is being displayed on the default home page listing, on
- * taxonomy listing pages, or on blog listing pages.
- * - rss: node displayed in an RSS feed.
- * If search.module is enabled:
- * - search_index: node is being indexed for search.
- * - search_result: node is being displayed as a search result.
- * If book.module is enabled:
- * - print: node is being displayed in print-friendly mode.
- * Contributed modules might define additional view modes, or use existing
- * view modes in additional contexts.
- *
- * @param $node
- * A node object.
- * @param $view_mode
- * View mode, e.g. 'full', 'teaser'...
- * @param $langcode
- * (optional) A language code to use for rendering. Defaults to the global
- * content language of the current request.
- */
- function node_build_content($node, $view_mode = 'full', $langcode = NULL) {
- if (!isset($langcode)) {
- $langcode = $GLOBALS['language_content']->language;
- }
- // Remove previously built content, if exists.
- $node->content = array();
- // Allow modules to change the view mode.
- $view_mode = key(entity_view_mode_prepare('node', array($node->nid => $node), $view_mode, $langcode));
- // The 'view' hook can be implemented to overwrite the default function
- // to display nodes.
- if (node_hook($node, 'view')) {
- $node = node_invoke($node, 'view', $view_mode, $langcode);
- }
- // Build fields content.
- // In case of a multiple view, node_view_multiple() already ran the
- // 'prepare_view' step. An internal flag prevents the operation from running
- // twice.
- field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
- entity_prepare_view('node', array($node->nid => $node), $langcode);
- $node->content += field_attach_view('node', $node, $view_mode, $langcode);
- // Always display a read more link on teasers because we have no way to know
- // when a teaser view is different than a full view.
- $links = array();
- $node->content['links'] = array(
- '#theme' => 'links__node',
- '#pre_render' => array('drupal_pre_render_links'),
- '#attributes' => array('class' => array('links', 'inline')),
- );
- if ($view_mode == 'teaser') {
- $node_title_stripped = strip_tags($node->title);
- $links['node-readmore'] = array(
- 'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),
- 'href' => 'node/' . $node->nid,
- 'html' => TRUE,
- 'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped),
- );
- }
- $node->content['links']['node'] = array(
- '#theme' => 'links__node__node',
- '#links' => $links,
- '#attributes' => array('class' => array('links', 'inline')),
- );
- // Allow modules to make their own additions to the node.
- module_invoke_all('node_view', $node, $view_mode, $langcode);
- module_invoke_all('entity_view', $node, 'node', $view_mode, $langcode);
- // Make sure the current view mode is stored if no module has already
- // populated the related key.
- $node->content += array('#view_mode' => $view_mode);
- }
- /**
- * Generates an array which displays a node detail page.
- *
- * @param $node
- * A node object.
- * @param $message
- * A flag which sets a page title relevant to the revision being viewed.
- *
- * @return
- * A $page element suitable for use by drupal_render().
- */
- function node_show($node, $message = FALSE) {
- if ($message) {
- drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
- }
- // For markup consistency with other pages, use node_view_multiple() rather than node_view().
- $nodes = node_view_multiple(array($node->nid => $node), 'full');
- // Update the history table, stating that this user viewed this node.
- node_tag_new($node);
- return $nodes;
- }
- /**
- * Returns whether the current page is the full page view of the passed-in node.
- *
- * @param $node
- * A node object.
- *
- * @return
- * The ID of the node if this is a full page view, otherwise FALSE.
- */
- function node_is_page($node) {
- $page_node = menu_get_object();
- return (!empty($page_node) ? $page_node->nid == $node->nid : FALSE);
- }
- /**
- * Processes variables for node.tpl.php
- *
- * Most themes utilize their own copy of node.tpl.php. The default is located
- * inside "modules/node/node.tpl.php". Look in there for the full list of
- * variables.
- *
- * The $variables array contains the following arguments:
- * - $node
- * - $view_mode
- * - $page
- *
- * @see node.tpl.php
- */
- function template_preprocess_node(&$variables) {
- $variables['view_mode'] = $variables['elements']['#view_mode'];
- // Provide a distinct $teaser boolean.
- $variables['teaser'] = $variables['view_mode'] == 'teaser';
- $variables['node'] = $variables['elements']['#node'];
- $node = $variables['node'];
- $variables['date'] = format_date($node->created);
- $variables['name'] = theme('username', array('account' => $node));
- $uri = entity_uri('node', $node);
- $variables['node_url'] = url($uri['path'], $uri['options']);
- $variables['title'] = check_plain($node->title);
- $variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);
- // Flatten the node object's member fields.
- $variables = array_merge((array) $node, $variables);
- // Helpful $content variable for templates.
- $variables += array('content' => array());
- foreach (element_children($variables['elements']) as $key) {
- $variables['content'][$key] = $variables['elements'][$key];
- }
- // Make the field variables available with the appropriate language.
- field_attach_preprocess('node', $node, $variables['content'], $variables);
- // Display post information only on certain node types.
- if (variable_get('node_submitted_' . $node->type, TRUE)) {
- $variables['display_submitted'] = TRUE;
- $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
- $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
- }
- else {
- $variables['display_submitted'] = FALSE;
- $variables['submitted'] = '';
- $variables['user_picture'] = '';
- }
- // Gather node classes.
- $variables['classes_array'][] = drupal_html_class('node-' . $node->type);
- if ($variables['promote']) {
- $variables['classes_array'][] = 'node-promoted';
- }
- if ($variables['sticky']) {
- $variables['classes_array'][] = 'node-sticky';
- }
- if (!$variables['status']) {
- $variables['classes_array'][] = 'node-unpublished';
- }
- if ($variables['teaser']) {
- $variables['classes_array'][] = 'node-teaser';
- }
- if (isset($variables['preview'])) {
- $variables['classes_array'][] = 'node-preview';
- }
- // Clean up name so there are no underscores.
- $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
- $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
- }
- /**
- * Implements hook_permission().
- */
- function node_permission() {
- $perms = array(
- 'bypass node access' => array(
- 'title' => t('Bypass content access control'),
- 'description' => t('View, edit and delete all content regardless of permission restrictions.'),
- 'restrict access' => TRUE,
- ),
- 'administer content types' => array(
- 'title' => t('Administer content types'),
- 'restrict access' => TRUE,
- ),
- 'administer nodes' => array(
- 'title' => t('Administer content'),
- 'restrict access' => TRUE,
- ),
- 'access content overview' => array(
- 'title' => t('Access the content overview page'),
- 'description' => user_access('access content overview')
- ? t('Get an overview of <a href="@url">all content</a>.', array('@url' => url('admin/content')))
- : t('Get an overview of all content.'),
- ),
- 'access content' => array(
- 'title' => t('View published content'),
- ),
- 'view own unpublished content' => array(
- 'title' => t('View own unpublished content'),
- ),
- 'view revisions' => array(
- 'title' => t('View content revisions'),
- ),
- 'revert revisions' => array(
- 'title' => t('Revert content revisions'),
- ),
- 'delete revisions' => array(
- 'title' => t('Delete content revisions'),
- ),
- );
- // Generate standard node permissions for all applicable node types.
- foreach (node_permissions_get_configured_types() as $type) {
- $perms += node_list_permissions($type);
- }
- return $perms;
- }
- /**
- * Gathers the rankings from the the hook_ranking() implementations.
- *
- * @param $query
- * A query object that has been extended with the Search DB Extender.
- */
- function _node_rankings(SelectQueryExtender $query) {
- if ($ranking = module_invoke_all('ranking')) {
- $tables = &$query->getTables();
- foreach ($ranking as $rank => $values) {
- if ($node_rank = variable_get('node_rank_' . $rank, 0)) {
- // If the table defined in the ranking isn't already joined, then add it.
- if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
- $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
- }
- $arguments = isset($values['arguments']) ? $values['arguments'] : array();
- $query->addScore($values['score'], $arguments, $node_rank);
- }
- }
- }
- }
- /**
- * Implements hook_search_info().
- */
- function node_search_info() {
- return array(
- 'title' => 'Content',
- 'path' => 'node',
- );
- }
- /**
- * Implements hook_search_access().
- */
- function node_search_access() {
- return user_access('access content');
- }
- /**
- * Implements hook_search_reset().
- */
- function node_search_reset() {
- db_update('search_dataset')
- ->fields(array('reindex' => REQUEST_TIME))
- ->condition('type', 'node')
- ->execute();
- }
- /**
- * Implements hook_search_status().
- */
- function node_search_status() {
- $total = db_query('SELECT COUNT(*) FROM {node}')->fetchField();
- $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();
- return array('remaining' => $remaining, 'total' => $total);
- }
- /**
- * Implements hook_search_admin().
- */
- function node_search_admin() {
- // Output form for defining rank factor weights.
- $form['content_ranking'] = array(
- '#type' => 'fieldset',
- '#title' => t('Content ranking'),
- );
- $form['content_ranking']['#theme'] = 'node_search_admin';
- $form['content_ranking']['info'] = array(
- '#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>'
- );
- // Note: reversed to reflect that higher number = higher ranking.
- $options = drupal_map_assoc(range(0, 10));
- foreach (module_invoke_all('ranking') as $var => $values) {
- $form['content_ranking']['factors']['node_rank_' . $var] = array(
- '#title' => $values['title'],
- '#type' => 'select',
- '#options' => $options,
- '#default_value' => variable_get('node_rank_' . $var, 0),
- );
- }
- return $form;
- }
- /**
- * Implements hook_search_execute().
- */
- function node_search_execute($keys = NULL, $conditions = NULL) {
- // Build matching conditions
- $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
- $query->join('node', 'n', 'n.nid = i.sid');
- $query
- ->condition('n.status', 1)
- ->addTag('node_access')
- ->searchExpression($keys, 'node');
- // Insert special keywords.
- $query->setOption('type', 'n.type');
- $query->setOption('language', 'n.language');
- if ($query->setOption('term', 'ti.tid')) {
- $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
- }
- // Only continue if the first pass query matches.
- if (!$query->executeFirstPass()) {
- return array();
- }
- // Add the ranking expressions.
- _node_rankings($query);
- // Load results.
- $find = $query
- ->limit(10)
- ->execute();
- $results = array();
- foreach ($find as $item) {
- // Render the node.
- $node = node_load($item->sid);
- $build = node_view($node, 'search_result');
- unset($build['#theme']);
- $node->rendered = drupal_render($build);
- // Fetch comments for snippet.
- $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
- $extra = module_invoke_all('node_search_result', $node);
- $uri = entity_uri('node', $node);
- $results[] = array(
- 'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
- 'type' => check_plain(node_type_get_name($node)),
- 'title' => $node->title,
- 'user' => theme('username', array('account' => $node)),
- 'date' => $node->changed,
- 'node' => $node,
- 'extra' => $extra,
- 'score' => $item->calculated_score,
- 'snippet' => search_excerpt($keys, $node->rendered),
- 'language' => entity_language('node', $node),
- );
- }
- return $results;
- }
- /**
- * Implements hook_ranking().
- */
- function node_ranking() {
- // Create the ranking array and add the basic ranking options.
- $ranking = array(
- 'relevance' => array(
- 'title' => t('Keyword relevance'),
- // Average relevance values hover around 0.15
- 'score' => 'i.relevance',
- ),
- 'sticky' => array(
- 'title' => t('Content is sticky at top of lists'),
- // The sticky flag is either 0 or 1, which is automatically normalized.
- 'score' => 'n.sticky',
- ),
- 'promote' => array(
- 'title' => t('Content is promoted to the front page'),
- // The promote flag is either 0 or 1, which is automatically normalized.
- 'score' => 'n.promote',
- ),
- );
- // Add relevance based on creation or changed date.
- if ($node_cron_last = variable_get('node_cron_last', 0)) {
- $ranking['recent'] = array(
- 'title' => t('Recently posted'),
- // Exponential decay with half-life of 6 months, starting at last indexed node
- 'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - :node_cron_last) * 6.43e-8)',
- 'arguments' => array(':node_cron_last' => $node_cron_last),
- );
- }
- return $ranking;
- }
- /**
- * Implements hook_user_cancel().
- */
- function node_user_cancel($edit, $account, $method) {
- switch ($method) {
- case 'user_cancel_block_unpublish':
- // Unpublish nodes (current revisions).
- module_load_include('inc', 'node', 'node.admin');
- $nodes = db_select('node', 'n')
- ->fields('n', array('nid'))
- ->condition('uid', $account->uid)
- ->execute()
- ->fetchCol();
- node_mass_update($nodes, array('status' => 0));
- break;
- case 'user_cancel_reassign':
- // Anonymize nodes (current revisions).
- module_load_include('inc', 'node', 'node.admin');
- $nodes = db_select('node', 'n')
- ->fields('n', array('nid'))
- ->condition('uid', $account->uid)
- ->execute()
- ->fetchCol();
- node_mass_update($nodes, array('uid' => 0));
- // Anonymize old revisions.
- db_update('node_revision')
- ->fields(array('uid' => 0))
- ->condition('uid', $account->uid)
- ->execute();
- // Clean history.
- db_delete('history')
- ->condition('uid', $account->uid)
- ->execute();
- break;
- }
- }
- /**
- * Implements hook_user_delete().
- */
- function node_user_delete($account) {
- // Delete nodes (current revisions).
- // @todo Introduce node_mass_delete() or make node_mass_update() more flexible.
- $nodes = db_select('node', 'n')
- ->fields('n', array('nid'))
- ->condition('uid', $account->uid)
- ->execute()
- ->fetchCol();
- node_delete_multiple($nodes);
- // Delete old revisions.
- $revisions = db_query('SELECT vid FROM {node_revision} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
- foreach ($revisions as $revision) {
- node_revision_delete($revision);
- }
- // Clean history.
- db_delete('history')
- ->condition('uid', $account->uid)
- ->execute();
- }
- /**
- * Returns HTML for the content ranking part of the search settings admin page.
- *
- * @param $variables
- * An associative array containing:
- * - form: A render element representing the form.
- *
- * @see node_search_admin()
- * @ingroup themeable
- */
- function theme_node_search_admin($variables) {
- $form = $variables['form'];
- $output = drupal_render($form['info']);
- $header = array(t('Factor'), t('Influence'));
- foreach (element_children($form['factors']) as $key) {
- $row = array();
- $row[] = $form['factors'][$key]['#title'];
- $form['factors'][$key]['#title_display'] = 'invisible';
- $row[] = drupal_render($form['factors'][$key]);
- $rows[] = $row;
- }
- $output .= theme('table', array('header' => $header, 'rows' => $rows));
- $output .= drupal_render_children($form);
- return $output;
- }
- /**
- * Access callback: Checks node revision access.
- *
- * @param $node
- * The node to check.
- * @param $op
- * (optional) The specific operation being checked. Defaults to 'view.'
- * @param object $account
- * (optional) A user object representing the user for whom the operation is
- * to be performed. Determines access for a user other than the current user.
- *
- * @return
- * TRUE if the operation may be performed, FALSE otherwise.
- *
- * @see node_menu()
- */
- function _node_revision_access($node, $op = 'view', $account = NULL) {
- $access = &drupal_static(__FUNCTION__, array());
- $map = array(
- 'view' => 'view revisions',
- 'update' => 'revert revisions',
- 'delete' => 'delete revisions',
- );
- if (!$node || !isset($map[$op])) {
- // If there was no node to check against, or the $op was not one of the
- // supported ones, we return access denied.
- return FALSE;
- }
- if (!isset($account)) {
- $account = $GLOBALS['user'];
- }
- // Statically cache access by revision ID, user account ID, and operation.
- $cid = $node->vid . ':' . $account->uid . ':' . $op;
- if (!isset($access[$cid])) {
- // Perform basic permission checks first.
- if (!user_access($map[$op], $account) && !user_access('administer nodes', $account)) {
- return $access[$cid] = FALSE;
- }
- $node_current_revision = node_load($node->nid);
- $is_current_revision = $node_current_revision->vid == $node->vid;
- // There should be at least two revisions. If the vid of the given node and
- // the vid of the current revision differ, then we already have two
- // different revisions so there is no need for a separate database check.
- // Also, if you try to revert to or delete the current revision, that's not
- // good.
- 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')) {
- $access[$cid] = FALSE;
- }
- elseif (user_access('administer nodes', $account)) {
- $access[$cid] = TRUE;
- }
- else {
- // First check the access to the current revision and finally, if the node
- // passed in is not the current revision then access to that, too.
- $access[$cid] = node_access($op, $node_current_revision, $account) && ($is_current_revision || node_access($op, $node, $account));
- }
- }
- return $access[$cid];
- }
- /**
- * Access callback: Checks whether the user has permission to add a node.
- *
- * @return
- * TRUE if the user has add permission, otherwise FALSE.
- *
- * @see node_menu()
- */
- function _node_add_access() {
- $types = node_type_get_types();
- foreach ($types as $type) {
- if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
- return TRUE;
- }
- }
- if (user_access('administer content types')) {
- // There are no content types defined that the user has permission to create,
- // but the user does have the permission to administer the content types, so
- // grant them access to the page anyway.
- return TRUE;
- }
- return FALSE;
- }
- /**
- * Implements hook_menu().
- */
- function node_menu() {
- $items['admin/content'] = array(
- 'title' => 'Content',
- 'description' => 'Find and manage content.',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('node_admin_content'),
- 'access arguments' => array('access content overview'),
- 'weight' => -10,
- 'file' => 'node.admin.inc',
- );
- $items['admin/content/node'] = array(
- 'title' => 'Content',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => -10,
- );
- $items['admin/reports/status/rebuild'] = array(
- 'title' => 'Rebuild permissions',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('node_configure_rebuild_confirm'),
- // Any user than can potentially trigger a node_access_needs_rebuild(TRUE)
- // has to be allowed access to the 'node access rebuild' confirm form.
- 'access arguments' => array('access administration pages'),
- 'type' => MENU_CALLBACK,
- 'file' => 'node.admin.inc',
- );
- $items['admin/structure/types'] = array(
- 'title' => 'Content types',
- 'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
- 'page callback' => 'node_overview_types',
- 'access arguments' => array('administer content types'),
- 'file' => 'content_types.inc',
- );
- $items['admin/structure/types/list'] = array(
- 'title' => 'List',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => -10,
- );
- $items['admin/structure/types/add'] = array(
- 'title' => 'Add content type',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('node_type_form'),
- 'access arguments' => array('administer content types'),
- 'type' => MENU_LOCAL_ACTION,
- 'file' => 'content_types.inc',
- );
- $items['admin/structure/types/manage/%node_type'] = array(
- 'title' => 'Edit content type',
- 'title callback' => 'node_type_page_title',
- 'title arguments' => array(4),
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('node_type_form', 4),
- 'access arguments' => array('administer content types'),
- 'file' => 'content_types.inc',
- );
- $items['admin/structure/types/manage/%node_type/edit'] = array(
- 'title' => 'Edit',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- );
- $items['admin/structure/types/manage/%node_type/delete'] = array(
- 'title' => 'Delete',
- 'page arguments' => array('node_type_delete_confirm', 4),
- 'access arguments' => array('administer content types'),
- 'file' => 'content_types.inc',
- );
- $items['node'] = array(
- 'page callback' => 'node_page_default',
- 'access arguments' => array('access content'),
- 'menu_name' => 'navigation',
- 'type' => MENU_CALLBACK,
- );
- $items['node/add'] = array(
- 'title' => 'Add content',
- 'page callback' => 'node_add_page',
- 'access callback' => '_node_add_access',
- 'file' => 'node.pages.inc',
- );
- $items['rss.xml'] = array(
- 'title' => 'RSS feed',
- 'page callback' => 'node_feed',
- 'access arguments' => array('access content'),
- 'type' => MENU_CALLBACK,
- // Pass a FALSE and array argument to ensure that additional path components
- // are not passed to node_feed().
- 'page arguments' => array(FALSE, array()),
- );
- // @todo Remove this loop when we have a 'description callback' property.
- // Reset internal static cache of _node_types_build(), forces to rebuild the
- // node type information.
- node_type_cache_reset();
- foreach (node_type_get_types() as $type) {
- $type_url_str = str_replace('_', '-', $type->type);
- $items['node/add/' . $type_url_str] = array(
- 'title' => $type->name,
- 'title callback' => 'check_plain',
- 'page callback' => 'node_add',
- 'page arguments' => array($type->type),
- 'access callback' => 'node_access',
- 'access arguments' => array('create', $type->type),
- 'description' => $type->description,
- 'file' => 'node.pages.inc',
- );
- }
- $items['node/%node'] = array(
- 'title callback' => 'node_page_title',
- 'title arguments' => array(1),
- // The page callback also invokes drupal_set_title() in case
- // the menu router's title is overridden by a menu link.
- 'page callback' => 'node_page_view',
- 'page arguments' => array(1),
- 'access callback' => 'node_access',
- 'access arguments' => array('view', 1),
- );
- $items['node/%node/view'] = array(
- 'title' => 'View',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => -10,
- );
- $items['node/%node/edit'] = array(
- 'title' => 'Edit',
- 'page callback' => 'node_page_edit',
- 'page arguments' => array(1),
- 'access callback' => 'node_access',
- 'access arguments' => array('update', 1),
- 'weight' => 0,
- 'type' => MENU_LOCAL_TASK,
- 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
- 'file' => 'node.pages.inc',
- );
- $items['node/%node/delete'] = array(
- 'title' => 'Delete',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('node_delete_confirm', 1),
- 'access callback' => 'node_access',
- 'access arguments' => array('delete', 1),
- 'weight' => 1,
- 'type' => MENU_LOCAL_TASK,
- 'context' => MENU_CONTEXT_INLINE,
- 'file' => 'node.pages.inc',
- );
- $items['node/%node/revisions'] = array(
- 'title' => 'Revisions',
- 'page callback' => 'node_revision_overview',
- 'page arguments' => array(1),
- 'access callback' => '_node_revision_access',
- 'access arguments' => array(1),
- 'weight' => 2,
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'node.pages.inc',
- );
- $items['node/%node/revisions/%/view'] = array(
- 'title' => 'Revisions',
- 'load arguments' => array(3),
- 'page callback' => 'node_show',
- 'page arguments' => array(1, TRUE),
- 'access callback' => '_node_revision_access',
- 'access arguments' => array(1),
- );
- $items['node/%node/revisions/%/revert'] = array(
- 'title' => 'Revert to earlier revision',
- 'load arguments' => array(3),
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('node_revision_revert_confirm', 1),
- 'access callback' => '_node_revision_access',
- 'access arguments' => array(1, 'update'),
- 'file' => 'node.pages.inc',
- );
- $items['node/%node/revisions/%/delete'] = array(
- 'title' => 'Delete earlier revision',
- 'load arguments' => array(3),
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('node_revision_delete_confirm', 1),
- 'access callback' => '_node_revision_access',
- 'access arguments' => array(1, 'delete'),
- 'file' => 'node.pages.inc',
- );
- return $items;
- }
- /**
- * Implements hook_menu_local_tasks_alter().
- */
- function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
- // Add action link to 'node/add' on 'admin/content' page.
- if ($root_path == 'admin/content') {
- $item = menu_get_item('node/add');
- if ($item['access']) {
- $data['actions']['output'][] = array(
- '#theme' => 'menu_local_action',
- '#link' => $item,
- );
- }
- }
- }
- /**
- * Title callback: Returns the unsanitized title of the node type edit form.
- *
- * @param $type
- * The node type object.
- *
- * @return string
- * An unsanitized string that is the title of the node type edit form.
- *
- * @see node_menu()
- */
- function node_type_page_title($type) {
- return $type->name;
- }
- /**
- * Title callback: Returns the title of the node.
- *
- * @param $node
- * The node object.
- *
- * @return
- * An unsanitized string that is the title of the node.
- *
- * @see node_menu()
- */
- function node_page_title($node) {
- return $node->title;
- }
- /**
- * Finds the last time a node was changed.
- *
- * @param $nid
- * The ID of a node.
- *
- * @return
- * A unix timestamp indicating the last time the node was changed.
- */
- function node_last_changed($nid) {
- return db_query('SELECT changed FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetch()->changed;
- }
- /**
- * Returns a list of all the existing revision numbers.
- *
- * @param $node
- * The node object.
- *
- * @return
- * An associative array keyed by node revision number.
- */
- function node_revision_list($node) {
- $revisions = array();
- $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));
- foreach ($result as $revision) {
- $revisions[$revision->vid] = $revision;
- }
- return $revisions;
- }
- /**
- * Implements hook_block_info().
- */
- function node_block_info() {
- $blocks['syndicate']['info'] = t('Syndicate');
- // Not worth caching.
- $blocks['syndicate']['cache'] = DRUPAL_NO_CACHE;
- $blocks['recent']['info'] = t('Recent content');
- $blocks['recent']['properties']['administrative'] = TRUE;
- return $blocks;
- }
- /**
- * Implements hook_block_view().
- */
- function node_block_view($delta = '') {
- $block = array();
- switch ($delta) {
- case 'syndicate':
- $block['subject'] = t('Syndicate');
- $block['content'] = theme('feed_icon', array('url' => 'rss.xml', 'title' => t('Syndicate')));
- break;
- case 'recent':
- if (user_access('access content')) {
- $block['subject'] = t('Recent content');
- if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
- $block['content'] = theme('node_recent_block', array(
- 'nodes' => $nodes,
- ));
- } else {
- $block['content'] = t('No content available.');
- }
- }
- break;
- }
- return $block;
- }
- /**
- * Implements hook_block_configure().
- */
- function node_block_configure($delta = '') {
- $form = array();
- if ($delta == 'recent') {
- $form['node_recent_block_count'] = array(
- '#type' => 'select',
- '#title' => t('Number of recent content items to display'),
- '#default_value' => variable_get('node_recent_block_count', 10),
- '#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)),
- );
- }
- return $form;
- }
- /**
- * Implements hook_block_save().
- */
- function node_block_save($delta = '', $edit = array()) {
- if ($delta == 'recent') {
- variable_set('node_recent_block_count', $edit['node_recent_block_count']);
- }
- }
- /**
- * Finds the most recently changed nodes that are available to the current user.
- *
- * @param $number
- * (optional) The maximum number of nodes to find. Defaults to 10.
- *
- * @return
- * An array of node entities or an empty array if there are no recent nodes
- * visible to the current user.
- */
- function node_get_recent($number = 10) {
- $query = db_select('node', 'n');
- if (!user_access('bypass node access')) {
- // If the user is able to view their own unpublished nodes, allow them to
- // see these in addition to published nodes. Check that they actually have
- // some unpublished nodes to view before adding the condition.
- 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()) {
- $query->condition(db_or()
- ->condition('n.status', NODE_PUBLISHED)
- ->condition('n.nid', $own_unpublished, 'IN')
- );
- }
- else {
- // If not, restrict the query to published nodes.
- $query->condition('n.status', NODE_PUBLISHED);
- }
- }
- $nids = $query
- ->fields('n', array('nid'))
- ->orderBy('n.changed', 'DESC')
- ->range(0, $number)
- ->addTag('node_access')
- ->execute()
- ->fetchCol();
- $nodes = node_load_multiple($nids);
- return $nodes ? $nodes : array();
- }
- /**
- * Returns HTML for a list of recent content.
- *
- * @param $variables
- * An associative array containing:
- * - nodes: An array of recent node objects.
- *
- * @ingroup themeable
- */
- function theme_node_recent_block($variables) {
- $rows = array();
- $output = '';
- $l_options = array('query' => drupal_get_destination());
- foreach ($variables['nodes'] as $node) {
- $row = array();
- $row[] = array(
- 'data' => theme('node_recent_content', array('node' => $node)),
- 'class' => 'title-author',
- );
- $row[] = array(
- 'data' => node_access('update', $node) ? l(t('edit'), 'node/' . $node->nid . '/edit', $l_options) : '',
- 'class' => 'edit',
- );
- $row[] = array(
- 'data' => node_access('delete', $node) ? l(t('delete'), 'node/' . $node->nid . '/delete', $l_options) : '',
- 'class' => 'delete',
- );
- $rows[] = $row;
- }
- if ($rows) {
- $output = theme('table', array('rows' => $rows));
- if (user_access('access content overview')) {
- $output .= theme('more_link', array('url' => 'admin/content', 'title' => t('Show more content')));
- }
- }
- return $output;
- }
- /**
- * Returns HTML for a recent node to be displayed in the recent content block.
- *
- * @param $variables
- * An associative array containing:
- * - node: A node object.
- *
- * @ingroup themeable
- */
- function theme_node_recent_content($variables) {
- $node = $variables['node'];
- $output = '<div class="node-title">';
- $output .= l($node->title, 'node/' . $node->nid);
- $output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
- $output .= '</div><div class="node-author">';
- $output .= theme('username', array('account' => user_load($node->uid)));
- $output .= '</div>';
- return $output;
- }
- /**
- * Implements hook_form_FORMID_alter().
- *
- * Adds node-type specific visibility options to add block form.
- *
- * @see block_add_block_form()
- */
- function node_form_block_add_block_form_alter(&$form, &$form_state) {
- node_form_block_admin_configure_alter($form, $form_state);
- }
- /**
- * Implements hook_form_FORMID_alter().
- *
- * Adds node-type specific visibility options to block configuration form.
- *
- * @see block_admin_configure()
- */
- function node_form_block_admin_configure_alter(&$form, &$form_state) {
- $default_type_options = db_query("SELECT type FROM {block_node_type} WHERE module = :module AND delta = :delta", array(
- ':module' => $form['module']['#value'],
- ':delta' => $form['delta']['#value'],
- ))->fetchCol();
- $form['visibility']['node_type'] = array(
- '#type' => 'fieldset',
- '#title' => t('Content types'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- '#group' => 'visibility',
- '#weight' => 5,
- );
- $form['visibility']['node_type']['types'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Show block for specific content types'),
- '#default_value' => $default_type_options,
- '#options' => node_type_get_names(),
- '#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.'),
- );
- $form['#submit'][] = 'node_form_block_admin_configure_submit';
- }
- /**
- * Form submission handler for node_form_block_admin_configure_alter().
- *
- * @see node_form_block_admin_configure_alter()
- */
- function node_form_block_admin_configure_submit($form, &$form_state) {
- db_delete('block_node_type')
- ->condition('module', $form_state['values']['module'])
- ->condition('delta', $form_state['values']['delta'])
- ->execute();
- $query = db_insert('block_node_type')->fields(array('type', 'module', 'delta'));
- foreach (array_filter($form_state['values']['types']) as $type) {
- $query->values(array(
- 'type' => $type,
- 'module' => $form_state['values']['module'],
- 'delta' => $form_state['values']['delta'],
- ));
- }
- $query->execute();
- }
- /**
- * Implements hook_form_FORMID_alter().
- *
- * Adds node specific submit handler to delete custom block form.
- *
- * @see block_custom_block_delete()
- */
- function node_form_block_custom_block_delete_alter(&$form, &$form_state) {
- $form['#submit'][] = 'node_form_block_custom_block_delete_submit';
- }
- /**
- * Form submission handler for node_form_block_custom_block_delete_alter().
- *
- * @see node_form_block_custom_block_delete_alter()
- */
- function node_form_block_custom_block_delete_submit($form, &$form_state) {
- db_delete('block_node_type')
- ->condition('module', 'block')
- ->condition('delta', $form_state['values']['bid'])
- ->execute();
- }
- /**
- * Implements hook_modules_uninstalled().
- *
- * Cleanup {block_node_type} table from modules' blocks.
- */
- function node_modules_uninstalled($modules) {
- db_delete('block_node_type')
- ->condition('module', $modules, 'IN')
- ->execute();
- }
- /**
- * Implements hook_block_list_alter().
- *
- * Check the content type specific visibilty settings. Remove the block if the
- * visibility conditions are not met.
- */
- function node_block_list_alter(&$blocks) {
- global $theme_key;
- // Build an array of node types for each block.
- $block_node_types = array();
- $result = db_query('SELECT module, delta, type FROM {block_node_type}');
- foreach ($result as $record) {
- $block_node_types[$record->module][$record->delta][$record->type] = TRUE;
- }
- $node = menu_get_object();
- $node_types = node_type_get_types();
- if (arg(0) == 'node' && arg(1) == 'add' && arg(2)) {
- $node_add_arg = strtr(arg(2), '-', '_');
- }
- foreach ($blocks as $key => $block) {
- if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
- // This block was added by a contrib module, leave it in the list.
- continue;
- }
- // If a block has no node types associated, it is displayed for every type.
- // For blocks with node types associated, if the node type does not match
- // the settings from this block, remove it from the block list.
- if (isset($block_node_types[$block->module][$block->delta])) {
- if (!empty($node)) {
- // This is a node or node edit page.
- if (!isset($block_node_types[$block->module][$block->delta][$node->type])) {
- // This block should not be displayed for this node type.
- unset($blocks[$key]);
- continue;
- }
- }
- elseif (isset($node_add_arg) && isset($node_types[$node_add_arg])) {
- // This is a node creation page
- if (!isset($block_node_types[$block->module][$block->delta][$node_add_arg])) {
- // This block should not be displayed for this node type.
- unset($blocks[$key]);
- continue;
- }
- }
- else {
- // This is not a node page, remove the block.
- unset($blocks[$key]);
- continue;
- }
- }
- }
- }
- /**
- * Generates and prints an RSS feed.
- *
- * Generates an RSS feed from an array of node IDs, and prints it with an HTTP
- * header, with Content Type set to RSS/XML.
- *
- * @param $nids
- * An array of node IDs (nid). Defaults to FALSE so empty feeds can be
- * generated with passing an empty array, if no items are to be added
- * to the feed.
- * @param $channel
- * An associative array containing title, link, description and other keys,
- * to be parsed by format_rss_channel() and format_xml_elements().
- * A list of channel elements can be found at the
- * @link http://cyber.law.harvard.edu/rss/rss.html RSS 2.0 Specification. @endlink
- * The link should be an absolute URL.
- */
- function node_feed($nids = FALSE, $channel = array()) {
- global $base_url, $language_content;
- if ($nids === FALSE) {
- $nids = db_select('node', 'n')
- ->fields('n', array('nid', 'created'))
- ->condition('n.promote', 1)
- ->condition('n.status', 1)
- ->orderBy('n.created', 'DESC')
- ->range(0, variable_get('feed_default_items', 10))
- ->addTag('node_access')
- ->execute()
- ->fetchCol();
- }
- $item_length = variable_get('feed_item_length', 'fulltext');
- $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');
- // Load all nodes to be rendered.
- $nodes = node_load_multiple($nids);
- $items = '';
- foreach ($nodes as $node) {
- $item_text = '';
- $node->link = url("node/$node->nid", array('absolute' => TRUE));
- $node->rss_namespaces = array();
- $account = user_load($node->uid);
- $node->rss_elements = array(
- array('key' => 'pubDate', 'value' => gmdate('r', $node->created)),
- array('key' => 'dc:creator', 'value' => format_username($account)),
- array('key' => 'guid', 'value' => $node->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))
- );
- // The node gets built and modules add to or modify $node->rss_elements
- // and $node->rss_namespaces.
- $build = node_view($node, 'rss');
- unset($build['#theme']);
- if (!empty($node->rss_namespaces)) {
- $namespaces = array_merge($namespaces, $node->rss_namespaces);
- }
- if ($item_length != 'title') {
- // We render node contents and force links to be last.
- $build['links']['#weight'] = 1000;
- $item_text .= drupal_render($build);
- }
- $items .= format_rss_item($node->title, $node->link, $item_text, $node->rss_elements);
- }
- $channel_defaults = array(
- 'version' => '2.0',
- 'title' => variable_get('site_name', 'Drupal'),
- 'link' => $base_url,
- 'description' => variable_get('feed_description', ''),
- 'language' => $language_content->language
- );
- $channel_extras = array_diff_key($channel, $channel_defaults);
- $channel = array_merge($channel_defaults, $channel);
- $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
- $output .= "<rss version=\"" . $channel["version"] . "\" xml:base=\"" . $base_url . "\" " . drupal_attributes($namespaces) . ">\n";
- $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language'], $channel_extras);
- $output .= "</rss>\n";
- drupal_add_http_header('Content-Type', 'application/rss+xml; charset=utf-8');
- print $output;
- }
- /**
- * Constructs a drupal_render() style array from an array of loaded nodes.
- *
- * @param $nodes
- * An array of nodes as returned by node_load_multiple().
- * @param $view_mode
- * View mode, e.g. 'full', 'teaser'...
- * @param $weight
- * An integer representing the weight of the first node in the list.
- * @param $langcode
- * (optional) A language code to use for rendering. Defaults to NULL which is
- * the global content language of the current request.
- *
- * @return
- * An array in the format expected by drupal_render().
- */
- function node_view_multiple($nodes, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
- $build = array();
- $entities_by_view_mode = entity_view_mode_prepare('node', $nodes, $view_mode, $langcode);
- foreach ($entities_by_view_mode as $entity_view_mode => $entities) {
- field_attach_prepare_view('node', $entities, $entity_view_mode, $langcode);
- entity_prepare_view('node', $entities, $langcode);
- foreach ($entities as $entity) {
- $build['nodes'][$entity->nid] = node_view($entity, $entity_view_mode, $langcode);
- }
- }
- foreach ($nodes as $node) {
- $build['nodes'][$node->nid]['#weight'] = $weight;
- $weight++;
- }
- // Sort here, to preserve the input order of the entities that were passed to
- // this function.
- uasort($build['nodes'], 'element_sort');
- $build['nodes']['#sorted'] = TRUE;
- return $build;
- }
- /**
- * Menu callback: Generates a listing of promoted nodes.
- *
- * @return array
- * An array in the format expected by drupal_render().
- *
- * @see node_menu()
- */
- function node_page_default() {
- $select = db_select('node', 'n')
- ->fields('n', array('nid', 'sticky', 'created'))
- ->condition('n.promote', 1)
- ->condition('n.status', 1)
- ->orderBy('n.sticky', 'DESC')
- ->orderBy('n.created', 'DESC')
- ->extend('PagerDefault')
- ->limit(variable_get('default_nodes_main', 10))
- ->addTag('node_access');
- $nids = $select->execute()->fetchCol();
- if (!empty($nids)) {
- $nodes = node_load_multiple($nids);
- $build = node_view_multiple($nodes);
- // 'rss.xml' is a path, not a file, registered in node_menu().
- drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
- $build['pager'] = array(
- '#theme' => 'pager',
- '#weight' => 5,
- );
- drupal_set_title('');
- }
- else {
- drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);
- $default_message = '<p>' . t('No front page content has been created yet.') . '</p>';
- $default_links = array();
- if (_node_add_access()) {
- $default_links[] = l(t('Add new content'), 'node/add');
- }
- if (!empty($default_links)) {
- $default_message .= theme('item_list', array('items' => $default_links));
- }
- $build['default_message'] = array(
- '#markup' => $default_message,
- '#prefix' => '<div id="first-time">',
- '#suffix' => '</div>',
- );
- }
- return $build;
- }
- /**
- * Menu callback: Displays a single node.
- *
- * @param $node
- * The node object.
- *
- * @return
- * A page array suitable for use by drupal_render().
- *
- * @see node_menu()
- */
- function node_page_view($node) {
- // If there is a menu link to this node, the link becomes the last part
- // of the active trail, and the link name becomes the page title.
- // Thus, we must explicitly set the page title to be the node title.
- drupal_set_title($node->title);
- $uri = entity_uri('node', $node);
- // Set the node path as the canonical URL to prevent duplicate content.
- drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
- // Set the non-aliased path as a default shortlink.
- drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
- return node_show($node);
- }
- /**
- * Implements hook_update_index().
- */
- function node_update_index() {
- $limit = (int)variable_get('search_cron_limit', 100);
- $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'));
- foreach ($result as $node) {
- _node_index_node($node);
- }
- }
- /**
- * Indexes a single node.
- *
- * @param $node
- * The node to index.
- */
- function _node_index_node($node) {
- $node = node_load($node->nid);
- // Save the changed time of the most recent indexed node, for the search
- // results half-life calculation.
- variable_set('node_cron_last', $node->changed);
- // Render the node.
- $build = node_view($node, 'search_index');
- unset($build['#theme']);
- $node->rendered = drupal_render($build);
- $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;
- // Fetch extra data normally not visible
- $extra = module_invoke_all('node_update_index', $node);
- foreach ($extra as $t) {
- $text .= $t;
- }
- // Update index
- search_index($node->nid, 'node', $text);
- }
- /**
- * Implements hook_form_FORM_ID_alter().
- */
- function node_form_search_form_alter(&$form, $form_state) {
- if (isset($form['module']) && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
- // Keyword boxes:
- $form['advanced'] = array(
- '#type' => 'fieldset',
- '#title' => t('Advanced search'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- '#attributes' => array('class' => array('search-advanced')),
- );
- $form['advanced']['keywords'] = array(
- '#prefix' => '<div class="criterion">',
- '#suffix' => '</div>',
- );
- $form['advanced']['keywords']['or'] = array(
- '#type' => 'textfield',
- '#title' => t('Containing any of the words'),
- '#size' => 30,
- '#maxlength' => 255,
- );
- $form['advanced']['keywords']['phrase'] = array(
- '#type' => 'textfield',
- '#title' => t('Containing the phrase'),
- '#size' => 30,
- '#maxlength' => 255,
- );
- $form['advanced']['keywords']['negative'] = array(
- '#type' => 'textfield',
- '#title' => t('Containing none of the words'),
- '#size' => 30,
- '#maxlength' => 255,
- );
- // Node types:
- $types = array_map('check_plain', node_type_get_names());
- $form['advanced']['type'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Only of the type(s)'),
- '#prefix' => '<div class="criterion">',
- '#suffix' => '</div>',
- '#options' => $types,
- );
- $form['advanced']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Advanced search'),
- '#prefix' => '<div class="action">',
- '#suffix' => '</div>',
- '#weight' => 100,
- );
- // Languages:
- $language_options = array();
- foreach (language_list('language') as $key => $entity) {
- if ($entity->enabled) {
- $language_options[$key] = $entity->name;
- }
- }
- if (count($language_options) > 1) {
- $form['advanced']['language'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Languages'),
- '#prefix' => '<div class="criterion">',
- '#suffix' => '</div>',
- '#options' => $language_options,
- );
- }
- $form['#validate'][] = 'node_search_validate';
- }
- }
- /**
- * Form validation handler for node_form_alter().
- */
- function node_search_validate($form, &$form_state) {
- // Initialize using any existing basic search keywords.
- $keys = $form_state['values']['processed_keys'];
- // Insert extra restrictions into the search keywords string.
- if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
- // Retrieve selected types - Form API sets the value of unselected
- // checkboxes to 0.
- $form_state['values']['type'] = array_filter($form_state['values']['type']);
- if (count($form_state['values']['type'])) {
- $keys = search_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
- }
- }
- if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
- $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
- }
- if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
- $languages = array_filter($form_state['values']['language']);
- if (count($languages)) {
- $keys = search_expression_insert($keys, 'language', implode(',', $languages));
- }
- }
- if ($form_state['values']['or'] != '') {
- if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
- $keys .= ' ' . implode(' OR ', $matches[1]);
- }
- }
- if ($form_state['values']['negative'] != '') {
- if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
- $keys .= ' -' . implode(' -', $matches[1]);
- }
- }
- if ($form_state['values']['phrase'] != '') {
- $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
- }
- if (!empty($keys)) {
- form_set_value($form['basic']['processed_keys'], trim($keys), $form_state);
- }
- }
- /**
- * @defgroup node_access Node access rights
- * @{
- * The node access system determines who can do what to which nodes.
- *
- * In determining access rights for a node, node_access() first checks whether
- * the user has the "bypass node access" permission. Such users have
- * unrestricted access to all nodes. user 1 will always pass this check.
- *
- * Next, all implementations of hook_node_access() will be called. Each
- * implementation may explicitly allow, explicitly deny, or ignore the access
- * request. If at least one module says to deny the request, it will be rejected.
- * If no modules deny the request and at least one says to allow it, the request
- * will be permitted.
- *
- * If all modules ignore the access request, then the node_access table is used
- * to determine access. All node access modules are queried using
- * hook_node_grants() to assemble a list of "grant IDs" for the user. This list
- * is compared against the table. If any row contains the node ID in question
- * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a
- * value of TRUE for the operation in question, then access is granted. Note
- * that this table is a list of grants; any matching row is sufficient to
- * grant access to the node.
- *
- * In node listings (lists of nodes generated from a select query, such as the
- * default home page at path 'node', an RSS feed, a recent content block, etc.),
- * the process above is followed except that hook_node_access() is not called on
- * each node for performance reasons and for proper functioning of the pager
- * system. When adding a node listing to your module, be sure to use a dynamic
- * query created by db_select() and add a tag of "node_access". This will allow
- * modules dealing with node access to ensure only nodes to which the user has
- * access are retrieved, through the use of hook_query_TAG_alter().
- *
- * Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access()
- * will block access to the node. Therefore, implementers should take care to
- * not deny access unless they really intend to. Unless a module wishes to
- * actively deny access it should return NODE_ACCESS_IGNORE (or simply return
- * nothing) to allow other modules or the node_access table to control access.
- *
- * To see how to write a node access module of your own, see
- * node_access_example.module.
- */
- /**
- * Determines whether the current user may perform the operation on the node.
- *
- * @param $op
- * The operation to be performed on the node. Possible values are:
- * - "view"
- * - "update"
- * - "delete"
- * - "create"
- * @param $node
- * The node object on which the operation is to be performed, or node type
- * (e.g. 'forum') for "create" operation.
- * @param $account
- * Optional, a user object representing the user for whom the operation is to
- * be performed. Determines access for a user other than the current user.
- *
- * @return
- * TRUE if the operation may be performed, FALSE otherwise.
- */
- function node_access($op, $node, $account = NULL) {
- $rights = &drupal_static(__FUNCTION__, array());
- if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
- // If there was no node to check against, or the $op was not one of the
- // supported ones, we return access denied.
- return FALSE;
- }
- // If no user object is supplied, the access check is for the current user.
- if (empty($account)) {
- $account = $GLOBALS['user'];
- }
- // $node may be either an object or a node type. Since node types cannot be
- // an integer, use either nid or type as the static cache id.
- $cid = is_object($node) ? $node->nid : $node;
- // If we've already checked access for this node, user and op, return from
- // cache.
- if (isset($rights[$account->uid][$cid][$op])) {
- return $rights[$account->uid][$cid][$op];
- }
- if (user_access('bypass node access', $account)) {
- $rights[$account->uid][$cid][$op] = TRUE;
- return TRUE;
- }
- if (!user_access('access content', $account)) {
- $rights[$account->uid][$cid][$op] = FALSE;
- return FALSE;
- }
- // We grant access to the node if both of the following conditions are met:
- // - No modules say to deny access.
- // - At least one module says to grant access.
- // If no module specified either allow or deny, we fall back to the
- // node_access table.
- $access = module_invoke_all('node_access', $node, $op, $account);
- if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
- $rights[$account->uid][$cid][$op] = FALSE;
- return FALSE;
- }
- elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
- $rights[$account->uid][$cid][$op] = TRUE;
- return TRUE;
- }
- // Check if authors can view their own unpublished nodes.
- if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
- $rights[$account->uid][$cid][$op] = TRUE;
- return TRUE;
- }
- // If the module did not override the access rights, use those set in the
- // node_access table.
- if ($op != 'create' && $node->nid) {
- if (module_implements('node_grants')) {
- $query = db_select('node_access');
- $query->addExpression('1');
- $query->condition('grant_' . $op, 1, '>=');
- $nids = db_or()->condition('nid', $node->nid);
- if ($node->status) {
- $nids->condition('nid', 0);
- }
- $query->condition($nids);
- $query->range(0, 1);
- $grants = db_or();
- foreach (node_access_grants($op, $account) as $realm => $gids) {
- foreach ($gids as $gid) {
- $grants->condition(db_and()
- ->condition('gid', $gid)
- ->condition('realm', $realm)
- );
- }
- }
- if (count($grants) > 0) {
- $query->condition($grants);
- }
- $result = (bool) $query
- ->execute()
- ->fetchField();
- $rights[$account->uid][$cid][$op] = $result;
- return $result;
- }
- elseif (is_object($node) && $op == 'view' && $node->status) {
- // If no modules implement hook_node_grants(), the default behavior is to
- // allow all users to view published nodes, so reflect that here.
- $rights[$account->uid][$cid][$op] = TRUE;
- return TRUE;
- }
- }
- return FALSE;
- }
- /**
- * Implements hook_node_access().
- */
- function node_node_access($node, $op, $account) {
- $type = is_string($node) ? $node : $node->type;
- if (in_array($type, node_permissions_get_configured_types())) {
- if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
- return NODE_ACCESS_ALLOW;
- }
- if ($op == 'update') {
- if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
- return NODE_ACCESS_ALLOW;
- }
- }
- if ($op == 'delete') {
- if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
- return NODE_ACCESS_ALLOW;
- }
- }
- }
- return NODE_ACCESS_IGNORE;
- }
- /**
- * Helper function to generate standard node permission list for a given type.
- *
- * @param $type
- * The machine-readable name of the node type.
- *
- * @return array
- * An array of permission names and descriptions.
- */
- function node_list_permissions($type) {
- $info = node_type_get_type($type);
- // Build standard list of node permissions for this type.
- $perms = array(
- "create $type content" => array(
- 'title' => t('%type_name: Create new content', array('%type_name' => $info->name)),
- ),
- "edit own $type content" => array(
- 'title' => t('%type_name: Edit own content', array('%type_name' => $info->name)),
- ),
- "edit any $type content" => array(
- 'title' => t('%type_name: Edit any content', array('%type_name' => $info->name)),
- ),
- "delete own $type content" => array(
- 'title' => t('%type_name: Delete own content', array('%type_name' => $info->name)),
- ),
- "delete any $type content" => array(
- 'title' => t('%type_name: Delete any content', array('%type_name' => $info->name)),
- ),
- );
- return $perms;
- }
- /**
- * Returns an array of node types that should be managed by permissions.
- *
- * By default, this will include all node types in the system. To exclude a
- * specific node from getting permissions defined for it, set the
- * node_permissions_$type variable to 0. Core does not provide an interface for
- * doing so. However, contrib modules may exclude their own nodes in
- * hook_install(). Alternatively, contrib modules may configure all node types
- * at once, or decide to apply some other hook_node_access() implementation to
- * some or all node types.
- *
- * @return
- * An array of node types managed by this module.
- */
- function node_permissions_get_configured_types() {
- $configured_types = array();
- foreach (node_type_get_types() as $type => $info) {
- if (variable_get('node_permissions_' . $type, 1)) {
- $configured_types[] = $type;
- }
- }
- return $configured_types;
- }
- /**
- * Fetches an array of permission IDs granted to the given user ID.
- *
- * The implementation here provides only the universal "all" grant. A node
- * access module should implement hook_node_grants() to provide a grant list for
- * the user.
- *
- * After the default grants have been loaded, we allow modules to alter the
- * grants array by reference. This hook allows for complex business logic to be
- * applied when integrating multiple node access modules.
- *
- * @param $op
- * The operation that the user is trying to perform.
- * @param $account
- * The user object for the user performing the operation. If omitted, the
- * current user is used.
- *
- * @return
- * An associative array in which the keys are realms, and the values are
- * arrays of grants for those realms.
- */
- function node_access_grants($op, $account = NULL) {
- if (!isset($account)) {
- $account = $GLOBALS['user'];
- }
- // Fetch node access grants from other modules.
- $grants = module_invoke_all('node_grants', $account, $op);
- // Allow modules to alter the assigned grants.
- drupal_alter('node_grants', $grants, $account, $op);
- return array_merge(array('all' => array(0)), $grants);
- }
- /**
- * Determines whether the user has a global viewing grant for all nodes.
- *
- * Checks to see whether any module grants global 'view' access to a user
- * account; global 'view' access is encoded in the {node_access} table as a
- * grant with nid=0. If no node access modules are enabled, node.module defines
- * such a global 'view' access grant.
- *
- * This function is called when a node listing query is tagged with
- * 'node_access'; when this function returns TRUE, no node access joins are
- * added to the query.
- *
- * @param $account
- * The user object for the user whose access is being checked. If omitted,
- * the current user is used.
- *
- * @return
- * TRUE if 'view' access to all nodes is granted, FALSE otherwise.
- *
- * @see hook_node_grants()
- * @see _node_query_node_access_alter()
- */
- function node_access_view_all_nodes($account = NULL) {
- global $user;
- if (!$account) {
- $account = $user;
- }
- // Statically cache results in an array keyed by $account->uid.
- $access = &drupal_static(__FUNCTION__);
- if (isset($access[$account->uid])) {
- return $access[$account->uid];
- }
- // If no modules implement the node access system, access is always TRUE.
- if (!module_implements('node_grants')) {
- $access[$account->uid] = TRUE;
- }
- else {
- $query = db_select('node_access');
- $query->addExpression('COUNT(*)');
- $query
- ->condition('nid', 0)
- ->condition('grant_view', 1, '>=');
- $grants = db_or();
- foreach (node_access_grants('view', $account) as $realm => $gids) {
- foreach ($gids as $gid) {
- $grants->condition(db_and()
- ->condition('gid', $gid)
- ->condition('realm', $realm)
- );
- }
- }
- if (count($grants) > 0 ) {
- $query->condition($grants);
- }
- $access[$account->uid] = $query
- ->execute()
- ->fetchField();
- }
- return $access[$account->uid];
- }
- /**
- * Implements hook_query_TAG_alter().
- *
- * This is the hook_query_alter() for queries tagged with 'node_access'. It adds
- * node access checks for the user account given by the 'account' meta-data (or
- * global $user if not provided), for an operation given by the 'op' meta-data
- * (or 'view' if not provided; other possible values are 'update' and 'delete').
- */
- function node_query_node_access_alter(QueryAlterableInterface $query) {
- _node_query_node_access_alter($query, 'node');
- }
- /**
- * Implements hook_query_TAG_alter().
- *
- * This function implements the same functionality as
- * node_query_node_access_alter() for the SQL field storage engine. Node access
- * conditions are added for field values belonging to nodes only.
- */
- function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
- _node_query_node_access_alter($query, 'entity');
- }
- /**
- * Helper for node access functions.
- *
- * Queries tagged with 'node_access' that are not against the {node} table
- * should add the base table as metadata. For example:
- * @code
- * $query
- * ->addTag('node_access')
- * ->addMetaData('base_table', 'taxonomy_index');
- * @endcode
- * If the query is not against the {node} table, an attempt is made to guess
- * the table, but is not recommended to rely on this as it is deprecated and not
- * allowed in Drupal 8. It is always safer to provide the table.
- *
- * @param $query
- * The query to add conditions to.
- * @param $type
- * Either 'node' or 'entity' depending on what sort of query it is. See
- * node_query_node_access_alter() and node_query_entity_field_access_alter()
- * for more.
- */
- function _node_query_node_access_alter($query, $type) {
- global $user;
- // Read meta-data from query, if provided.
- if (!$account = $query->getMetaData('account')) {
- $account = $user;
- }
- if (!$op = $query->getMetaData('op')) {
- $op = 'view';
- }
- // If $account can bypass node access, or there are no node access modules,
- // or the operation is 'view' and the $account has a global view grant
- // (such as a view grant for node ID 0), we don't need to alter the query.
- if (user_access('bypass node access', $account)) {
- return;
- }
- if (!count(module_implements('node_grants'))) {
- return;
- }
- if ($op == 'view' && node_access_view_all_nodes($account)) {
- return;
- }
- $tables = $query->getTables();
- $base_table = $query->getMetaData('base_table');
- // If no base table is specified explicitly, search for one.
- if (!$base_table) {
- $fallback = '';
- foreach ($tables as $alias => $table_info) {
- if (!($table_info instanceof SelectQueryInterface)) {
- $table = $table_info['table'];
- // If the node table is in the query, it wins immediately.
- if ($table == 'node') {
- $base_table = $table;
- break;
- }
- // Check whether the table has a foreign key to node.nid. If it does,
- // do not run this check again as we found a base table and only node
- // can triumph that.
- if (!$base_table) {
- // The schema is cached.
- $schema = drupal_get_schema($table);
- if (isset($schema['fields']['nid'])) {
- if (isset($schema['foreign keys'])) {
- foreach ($schema['foreign keys'] as $relation) {
- if ($relation['table'] === 'node' && $relation['columns'] === array('nid' => 'nid')) {
- $base_table = $table;
- }
- }
- }
- else {
- // At least it's a nid. A table with a field called nid is very
- // very likely to be a node.nid in a node access query.
- $fallback = $table;
- }
- }
- }
- }
- }
- // If there is nothing else, use the fallback.
- if (!$base_table) {
- if ($fallback) {
- 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);
- $base_table = $fallback;
- }
- else {
- throw new Exception(t('Query tagged for node access but there is no nid. Add foreign keys to node.nid in schema to fix.'));
- }
- }
- }
- // Find all instances of the base table being joined -- could appear
- // more than once in the query, and could be aliased. Join each one to
- // the node_access table.
- $grants = node_access_grants($op, $account);
- if ($type == 'entity') {
- // The original query looked something like:
- // @code
- // SELECT nid FROM sometable s
- // INNER JOIN node_access na ON na.nid = s.nid
- // WHERE ($node_access_conditions)
- // @endcode
- //
- // Our query will look like:
- // @code
- // SELECT entity_type, entity_id
- // FROM field_data_something s
- // LEFT JOIN node_access na ON s.entity_id = na.nid
- // WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
- // @endcode
- //
- // So instead of directly adding to the query object, we need to collect
- // all of the node access conditions in a separate db_and() object and
- // then add it to the query at the end.
- $node_conditions = db_and();
- }
- foreach ($tables as $nalias => $tableinfo) {
- $table = $tableinfo['table'];
- if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
- // Set the subquery.
- $subquery = db_select('node_access', 'na')
- ->fields('na', array('nid'));
- $grant_conditions = db_or();
- // If any grant exists for the specified user, then user has access
- // to the node for the specified operation.
- foreach ($grants as $realm => $gids) {
- foreach ($gids as $gid) {
- $grant_conditions->condition(db_and()
- ->condition('na.gid', $gid)
- ->condition('na.realm', $realm)
- );
- }
- }
- // Attach conditions to the subquery for nodes.
- if (count($grant_conditions->conditions())) {
- $subquery->condition($grant_conditions);
- }
- $subquery->condition('na.grant_' . $op, 1, '>=');
- $field = 'nid';
- // Now handle entities.
- if ($type == 'entity') {
- // Set a common alias for entities.
- $base_alias = $nalias;
- $field = 'entity_id';
- }
- $subquery->where("$nalias.$field = na.nid");
- // For an entity query, attach the subquery to entity conditions.
- if ($type == 'entity') {
- $node_conditions->exists($subquery);
- }
- // Otherwise attach it to the node query itself.
- else {
- $query->exists($subquery);
- }
- }
- }
- if ($type == 'entity' && count($subquery->conditions())) {
- // All the node access conditions are only for field values belonging to
- // nodes.
- $node_conditions->condition("$base_alias.entity_type", 'node');
- $or = db_or();
- $or->condition($node_conditions);
- // If the field value belongs to a non-node entity type then this function
- // does not do anything with it.
- $or->condition("$base_alias.entity_type", 'node', '<>');
- // Add the compiled set of rules to the query.
- $query->condition($or);
- }
- }
- /**
- * Gets the list of node access grants and writes them to the database.
- *
- * This function is called when a node is saved, and can also be called by
- * modules if something other than a node save causes node access permissions to
- * change. It collects all node access grants for the node from
- * hook_node_access_records() implementations, allows these grants to be altered
- * via hook_node_access_records_alter() implementations, and saves the collected
- * and altered grants to the database.
- *
- * @param $node
- * The $node to acquire grants for.
- *
- * @param $delete
- * Whether to delete existing node access records before inserting new ones.
- * Defaults to TRUE.
- */
- function node_access_acquire_grants($node, $delete = TRUE) {
- $grants = module_invoke_all('node_access_records', $node);
- // Let modules alter the grants.
- drupal_alter('node_access_records', $grants, $node);
- // If no grants are set and the node is published, then use the default grant.
- if (empty($grants) && !empty($node->status)) {
- $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
- }
- else {
- // Retain grants by highest priority.
- $grant_by_priority = array();
- foreach ($grants as $g) {
- $grant_by_priority[intval($g['priority'])][] = $g;
- }
- krsort($grant_by_priority);
- $grants = array_shift($grant_by_priority);
- }
- node_access_write_grants($node, $grants, NULL, $delete);
- }
- /**
- * Writes a list of grants to the database, deleting any previously saved ones.
- *
- * If a realm is provided, it will only delete grants from that realm, but it
- * will always delete a grant from the 'all' realm. Modules that utilize
- * node_access() can use this function when doing mass updates due to widespread
- * permission changes.
- *
- * Note: Don't call this function directly from a contributed module. Call
- * node_access_acquire_grants() instead.
- *
- * @param $node
- * The node whose grants are being written.
- * @param $grants
- * A list of grants to write. Each grant is an array that must contain the
- * following keys: realm, gid, grant_view, grant_update, grant_delete.
- * The realm is specified by a particular module; the gid is as well, and
- * is a module-defined id to define grant privileges. each grant_* field
- * is a boolean value.
- * @param $realm
- * (optional) If provided, read/write grants for that realm only. Defaults to
- * NULL.
- * @param $delete
- * (optional) If false, does not delete records. This is only for optimization
- * purposes, and assumes the caller has already performed a mass delete of
- * some form. Defaults to TRUE.
- *
- * @see node_access_acquire_grants()
- */
- function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE) {
- if ($delete) {
- $query = db_delete('node_access')->condition('nid', $node->nid);
- if ($realm) {
- $query->condition('realm', array($realm, 'all'), 'IN');
- }
- $query->execute();
- }
- // Only perform work when node_access modules are active.
- if (!empty($grants) && count(module_implements('node_grants'))) {
- $query = db_insert('node_access')->fields(array('nid', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete'));
- foreach ($grants as $grant) {
- if ($realm && $realm != $grant['realm']) {
- continue;
- }
- // Only write grants; denies are implicit.
- if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
- $grant['nid'] = $node->nid;
- $query->values($grant);
- }
- }
- $query->execute();
- }
- }
- /**
- * Flags or unflags the node access grants for rebuilding.
- *
- * If the argument isn't specified, the current value of the flag is returned.
- * When the flag is set, a message is displayed to users with 'access
- * administration pages' permission, pointing to the 'rebuild' confirm form.
- * This can be used as an alternative to direct node_access_rebuild calls,
- * allowing administrators to decide when they want to perform the actual
- * (possibly time consuming) rebuild. When unsure if the current user is an
- * administrator, node_access_rebuild() should be used instead.
- *
- * @param $rebuild
- * (Optional) The boolean value to be written.
- *
- * @return
- * The current value of the flag if no value was provided for $rebuild.
- *
- * @see node_access_rebuild()
- */
- function node_access_needs_rebuild($rebuild = NULL) {
- if (!isset($rebuild)) {
- return variable_get('node_access_needs_rebuild', FALSE);
- }
- elseif ($rebuild) {
- variable_set('node_access_needs_rebuild', TRUE);
- }
- else {
- variable_del('node_access_needs_rebuild');
- }
- }
- /**
- * Rebuilds the node access database.
- *
- * This is occasionally needed by modules that make system-wide changes to
- * access levels. When the rebuild is required by an admin-triggered action (e.g
- * module settings form), calling node_access_needs_rebuild(TRUE) instead of
- * node_access_rebuild() lets the user perform his changes and actually
- * rebuild only once he is done.
- *
- * Note: As of Drupal 6, node access modules are not required to (and actually
- * should not) call node_access_rebuild() in hook_enable/disable anymore.
- *
- * @see node_access_needs_rebuild()
- *
- * @param $batch_mode
- * Set to TRUE to process in 'batch' mode, spawning processing over several
- * HTTP requests (thus avoiding the risk of PHP timeout if the site has a
- * large number of nodes).
- * hook_update_N and any form submit handler are safe contexts to use the
- * 'batch mode'. Less decidable cases (such as calls from hook_user,
- * hook_taxonomy, etc...) might consider using the non-batch mode.
- */
- function node_access_rebuild($batch_mode = FALSE) {
- db_delete('node_access')->execute();
- // Only recalculate if the site is using a node_access module.
- if (count(module_implements('node_grants'))) {
- if ($batch_mode) {
- $batch = array(
- 'title' => t('Rebuilding content access permissions'),
- 'operations' => array(
- array('_node_access_rebuild_batch_operation', array()),
- ),
- 'finished' => '_node_access_rebuild_batch_finished'
- );
- batch_set($batch);
- }
- else {
- // Try to allocate enough time to rebuild node grants
- drupal_set_time_limit(240);
- // Rebuild newest nodes first so that recent content becomes available quickly.
- $nids = db_query("SELECT nid FROM {node} ORDER BY nid DESC")->fetchCol();
- foreach ($nids as $nid) {
- $node = node_load($nid, NULL, TRUE);
- // To preserve database integrity, only acquire grants if the node
- // loads successfully.
- if (!empty($node)) {
- node_access_acquire_grants($node);
- }
- }
- }
- }
- else {
- // Not using any node_access modules. Add the default grant.
- db_insert('node_access')
- ->fields(array(
- 'nid' => 0,
- 'realm' => 'all',
- 'gid' => 0,
- 'grant_view' => 1,
- 'grant_update' => 0,
- 'grant_delete' => 0,
- ))
- ->execute();
- }
- if (!isset($batch)) {
- drupal_set_message(t('Content permissions have been rebuilt.'));
- node_access_needs_rebuild(FALSE);
- cache_clear_all();
- }
- }
- /**
- * Performs batch operation for node_access_rebuild().
- *
- * This is a multistep operation: we go through all nodes by packs of 20. The
- * batch processing engine interrupts processing and sends progress feedback
- * after 1 second execution time.
- *
- * @param array $context
- * An array of contextual key/value information for rebuild batch process.
- */
- function _node_access_rebuild_batch_operation(&$context) {
- if (empty($context['sandbox'])) {
- // Initiate multistep processing.
- $context['sandbox']['progress'] = 0;
- $context['sandbox']['current_node'] = 0;
- $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
- }
- // Process the next 20 nodes.
- $limit = 20;
- $nids = db_query_range("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, array(':nid' => $context['sandbox']['current_node']))->fetchCol();
- $nodes = node_load_multiple($nids, array(), TRUE);
- foreach ($nodes as $nid => $node) {
- // To preserve database integrity, only acquire grants if the node
- // loads successfully.
- if (!empty($node)) {
- node_access_acquire_grants($node);
- }
- $context['sandbox']['progress']++;
- $context['sandbox']['current_node'] = $nid;
- }
- // Multistep processing : report progress.
- if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
- $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
- }
- }
- /**
- * Performs post-processing for node_access_rebuild().
- *
- * @param bool $success
- * A boolean indicating whether the re-build process has completed.
- * @param array $results
- * An array of results information.
- * @param array $operations
- * An array of function calls (not used in this function).
- */
- function _node_access_rebuild_batch_finished($success, $results, $operations) {
- if ($success) {
- drupal_set_message(t('The content access permissions have been rebuilt.'));
- node_access_needs_rebuild(FALSE);
- }
- else {
- drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
- }
- cache_clear_all();
- }
- /**
- * @} End of "defgroup node_access".
- */
- /**
- * @defgroup node_content Hook implementations for user-created content types
- * @{
- * Functions that implement hooks for user-created content types.
- */
- /**
- * Implements hook_form().
- */
- function node_content_form($node, $form_state) {
- // It is impossible to define a content type without implementing hook_form()
- // @todo: remove this requirement.
- $form = array();
- $type = node_type_get_type($node);
- if ($type->has_title) {
- $form['title'] = array(
- '#type' => 'textfield',
- '#title' => check_plain($type->title_label),
- '#required' => TRUE,
- '#default_value' => $node->title,
- '#maxlength' => 255,
- '#weight' => -5,
- );
- }
- return $form;
- }
- /**
- * @} End of "defgroup node_content".
- */
- /**
- * Implements hook_forms().
- *
- * All node forms share the same form handler.
- */
- function node_forms() {
- $forms = array();
- if ($types = node_type_get_types()) {
- foreach (array_keys($types) as $type) {
- $forms[$type . '_node_form']['callback'] = 'node_form';
- }
- }
- return $forms;
- }
- /**
- * Implements hook_action_info().
- */
- function node_action_info() {
- return array(
- 'node_publish_action' => array(
- 'type' => 'node',
- 'label' => t('Publish content'),
- 'configurable' => FALSE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_unpublish_action' => array(
- 'type' => 'node',
- 'label' => t('Unpublish content'),
- 'configurable' => FALSE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_make_sticky_action' => array(
- 'type' => 'node',
- 'label' => t('Make content sticky'),
- 'configurable' => FALSE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_make_unsticky_action' => array(
- 'type' => 'node',
- 'label' => t('Make content unsticky'),
- 'configurable' => FALSE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_promote_action' => array(
- 'type' => 'node',
- 'label' => t('Promote content to front page'),
- 'configurable' => FALSE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_unpromote_action' => array(
- 'type' => 'node',
- 'label' => t('Remove content from front page'),
- 'configurable' => FALSE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_assign_owner_action' => array(
- 'type' => 'node',
- 'label' => t('Change the author of content'),
- 'configurable' => TRUE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_save_action' => array(
- 'type' => 'node',
- 'label' => t('Save content'),
- 'configurable' => FALSE,
- 'triggers' => array('comment_insert', 'comment_update', 'comment_delete'),
- ),
- 'node_unpublish_by_keyword_action' => array(
- 'type' => 'node',
- 'label' => t('Unpublish content containing keyword(s)'),
- 'configurable' => TRUE,
- 'triggers' => array('node_presave', 'node_insert', 'node_update'),
- ),
- );
- }
- /**
- * Sets the status of a node to 1 (published).
- *
- * @param $node
- * A node object.
- * @param $context
- * (optional) Array of additional information about what triggered the action.
- * Not used for this action.
- *
- * @ingroup actions
- */
- function node_publish_action($node, $context = array()) {
- $node->status = NODE_PUBLISHED;
- watchdog('action', 'Set @type %title to published.', array('@type' => node_type_get_name($node), '%title' => $node->title));
- }
- /**
- * Sets the status of a node to 0 (unpublished).
- *
- * @param $node
- * A node object.
- * @param $context
- * (optional) Array of additional information about what triggered the action.
- * Not used for this action.
- *
- * @ingroup actions
- */
- function node_unpublish_action($node, $context = array()) {
- $node->status = NODE_NOT_PUBLISHED;
- watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
- }
- /**
- * Sets the sticky-at-top-of-list property of a node to 1.
- *
- * @param $node
- * A node object.
- * @param $context
- * (optional) Array of additional information about what triggered the action.
- * Not used for this action.
- *
- * @ingroup actions
- */
- function node_make_sticky_action($node, $context = array()) {
- $node->sticky = NODE_STICKY;
- watchdog('action', 'Set @type %title to sticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
- }
- /**
- * Sets the sticky-at-top-of-list property of a node to 0.
- *
- * @param $node
- * A node object.
- * @param $context
- * (optional) Array of additional information about what triggered the action.
- * Not used for this action.
- *
- * @ingroup actions
- */
- function node_make_unsticky_action($node, $context = array()) {
- $node->sticky = NODE_NOT_STICKY;
- watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
- }
- /**
- * Sets the promote property of a node to 1.
- *
- * @param $node
- * A node object.
- * @param $context
- * (optional) Array of additional information about what triggered the action.
- * Not used for this action.
- *
- * @ingroup actions
- */
- function node_promote_action($node, $context = array()) {
- $node->promote = NODE_PROMOTED;
- watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
- }
- /**
- * Sets the promote property of a node to 0.
- *
- * @param $node
- * A node object.
- * @param $context
- * (optional) Array of additional information about what triggered the action.
- * Not used for this action.
- *
- * @ingroup actions
- */
- function node_unpromote_action($node, $context = array()) {
- $node->promote = NODE_NOT_PROMOTED;
- watchdog('action', 'Removed @type %title from front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
- }
- /**
- * Saves a node.
- *
- * @param $node
- * The node to be saved.
- *
- * @ingroup actions
- */
- function node_save_action($node) {
- node_save($node);
- watchdog('action', 'Saved @type %title', array('@type' => node_type_get_name($node), '%title' => $node->title));
- }
- /**
- * Assigns ownership of a node to a user.
- *
- * @param $node
- * A node object to modify.
- * @param $context
- * Array with the following elements:
- * - 'owner_uid': User ID to assign to the node.
- *
- * @see node_assign_owner_action_form()
- * @see node_assign_owner_action_validate()
- * @see node_assign_owner_action_submit()
- * @ingroup actions
- */
- function node_assign_owner_action($node, $context) {
- $node->uid = $context['owner_uid'];
- $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
- watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' => node_type_get_name($node), '%title' => $node->title, '%name' => $owner_name));
- }
- /**
- * Generates the settings form for node_assign_owner_action().
- *
- * @param $context
- * Array of additional information about what triggered the action. Includes
- * the following elements:
- * - 'owner_uid': User ID to assign to the node.
- *
- * @see node_assign_owner_action_submit()
- * @see node_assign_owner_action_validate()
- *
- * @ingroup forms
- */
- function node_assign_owner_action_form($context) {
- $description = t('The username of the user to which you would like to assign ownership.');
- $count = db_query("SELECT COUNT(*) FROM {users}")->fetchField();
- $owner_name = '';
- if (isset($context['owner_uid'])) {
- $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
- }
- // Use dropdown for fewer than 200 users; textbox for more than that.
- if (intval($count) < 200) {
- $options = array();
- $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name");
- foreach ($result as $data) {
- $options[$data->name] = $data->name;
- }
- $form['owner_name'] = array(
- '#type' => 'select',
- '#title' => t('Username'),
- '#default_value' => $owner_name,
- '#options' => $options,
- '#description' => $description,
- );
- }
- else {
- $form['owner_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Username'),
- '#default_value' => $owner_name,
- '#autocomplete_path' => 'user/autocomplete',
- '#size' => '6',
- '#maxlength' => '60',
- '#description' => $description,
- );
- }
- return $form;
- }
- /**
- * Validates settings form for node_assign_owner_action().
- *
- * @see node_assign_owner_action_submit()
- */
- function node_assign_owner_action_validate($form, $form_state) {
- $exists = (bool) db_query_range('SELECT 1 FROM {users} WHERE name = :name', 0, 1, array(':name' => $form_state['values']['owner_name']))->fetchField();
- if (!$exists) {
- form_set_error('owner_name', t('Enter a valid username.'));
- }
- }
- /**
- * Saves settings form for node_assign_owner_action().
- *
- * @see node_assign_owner_action_validate()
- */
- function node_assign_owner_action_submit($form, $form_state) {
- // Username can change, so we need to store the ID, not the username.
- $uid = db_query('SELECT uid from {users} WHERE name = :name', array(':name' => $form_state['values']['owner_name']))->fetchField();
- return array('owner_uid' => $uid);
- }
- /**
- * Generates settings form for node_unpublish_by_keyword_action().
- *
- * @param array $context
- * Array of additional information about what triggered this action.
- *
- * @return array
- * A form array.
- *
- * @see node_unpublish_by_keyword_action_submit()
- */
- function node_unpublish_by_keyword_action_form($context) {
- $form['keywords'] = array(
- '#title' => t('Keywords'),
- '#type' => 'textarea',
- '#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."'),
- '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
- );
- return $form;
- }
- /**
- * Saves settings form for node_unpublish_by_keyword_action().
- */
- function node_unpublish_by_keyword_action_submit($form, $form_state) {
- return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
- }
- /**
- * Unpublishes a node containing certain keywords.
- *
- * @param $node
- * A node object to modify.
- * @param $context
- * Array with the following elements:
- * - 'keywords': Array of keywords. If any keyword is present in the rendered
- * node, the node's status flag is set to unpublished.
- *
- * @ingroup actions
- */
- function node_unpublish_by_keyword_action($node, $context) {
- foreach ($context['keywords'] as $keyword) {
- $elements = node_view(clone $node);
- if (strpos(drupal_render($elements), $keyword) !== FALSE || strpos($node->title, $keyword) !== FALSE) {
- $node->status = NODE_NOT_PUBLISHED;
- watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
- break;
- }
- }
- }
- /**
- * Implements hook_requirements().
- */
- function node_requirements($phase) {
- $requirements = array();
- if ($phase === 'runtime') {
- // Only show rebuild button if there are either 0, or 2 or more, rows
- // in the {node_access} table, or if there are modules that
- // implement hook_node_grants().
- $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
- if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
- $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
- }
- else {
- $value = t('Disabled');
- }
- $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.');
- $requirements['node_access'] = array(
- 'title' => t('Node Access Permissions'),
- 'value' => $value,
- 'description' => $description . ' ' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild'),
- );
- }
- return $requirements;
- }
- /**
- * Implements hook_modules_enabled().
- */
- function node_modules_enabled($modules) {
- // Check if any of the newly enabled modules require the node_access table to
- // be rebuilt.
- if (!node_access_needs_rebuild() && array_intersect($modules, module_implements('node_grants'))) {
- node_access_needs_rebuild(TRUE);
- }
- }
- /**
- * Controller class for nodes.
- *
- * This extends the DrupalDefaultEntityController class, adding required
- * special handling for node objects.
- */
- class NodeController extends DrupalDefaultEntityController {
- protected function attachLoad(&$nodes, $revision_id = FALSE) {
- // Create an array of nodes for each content type and pass this to the
- // object type specific callback.
- $typed_nodes = array();
- foreach ($nodes as $id => $entity) {
- $typed_nodes[$entity->type][$id] = $entity;
- }
- // Call object type specific callbacks on each typed array of nodes.
- foreach ($typed_nodes as $node_type => $nodes_of_type) {
- if (node_hook($node_type, 'load')) {
- $function = node_type_get_base($node_type) . '_load';
- $function($nodes_of_type);
- }
- }
- // Besides the list of nodes, pass one additional argument to
- // hook_node_load(), containing a list of node types that were loaded.
- $argument = array_keys($typed_nodes);
- $this->hookLoadArguments = array($argument);
- parent::attachLoad($nodes, $revision_id);
- }
- protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
- // Ensure that uid is taken from the {node} table,
- // alias timestamp to revision_timestamp and add revision_uid.
- $query = parent::buildQuery($ids, $conditions, $revision_id);
- $fields =& $query->getFields();
- unset($fields['timestamp']);
- $query->addField('revision', 'timestamp', 'revision_timestamp');
- $fields['uid']['table'] = 'base';
- $query->addField('revision', 'uid', 'revision_uid');
- return $query;
- }
- }
- /**
- * Implements hook_file_download_access().
- */
- function node_file_download_access($field, $entity_type, $entity) {
- if ($entity_type == 'node') {
- return node_access('view', $entity);
- }
- }
|