menu.inc 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923
  1. <?php
  2. /**
  3. * @file
  4. * API for the Drupal menu system.
  5. */
  6. /**
  7. * @defgroup menu Menu system
  8. * @{
  9. * Define the navigation menus, and route page requests to code based on URLs.
  10. *
  11. * The Drupal menu system drives both the navigation system from a user
  12. * perspective and the callback system that Drupal uses to respond to URLs
  13. * passed from the browser. For this reason, a good understanding of the
  14. * menu system is fundamental to the creation of complex modules. As a note,
  15. * this is related to, but separate from menu.module, which allows menus
  16. * (which in this context are hierarchical lists of links) to be customized from
  17. * the Drupal administrative interface.
  18. *
  19. * Drupal's menu system follows a simple hierarchy defined by paths.
  20. * Implementations of hook_menu() define menu items and assign them to
  21. * paths (which should be unique). The menu system aggregates these items
  22. * and determines the menu hierarchy from the paths. For example, if the
  23. * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
  24. * would form the structure:
  25. * - a
  26. * - a/b
  27. * - a/b/c/d
  28. * - a/b/h
  29. * - e
  30. * - f/g
  31. * Note that the number of elements in the path does not necessarily
  32. * determine the depth of the menu item in the tree.
  33. *
  34. * When responding to a page request, the menu system looks to see if the
  35. * path requested by the browser is registered as a menu item with a
  36. * callback. If not, the system searches up the menu tree for the most
  37. * complete match with a callback it can find. If the path a/b/i is
  38. * requested in the tree above, the callback for a/b would be used.
  39. *
  40. * The found callback function is called with any arguments specified
  41. * in the "page arguments" attribute of its menu item. The
  42. * attribute must be an array. After these arguments, any remaining
  43. * components of the path are appended as further arguments. In this
  44. * way, the callback for a/b above could respond to a request for
  45. * a/b/i differently than a request for a/b/j.
  46. *
  47. * For an illustration of this process, see page_example.module.
  48. *
  49. * Access to the callback functions is also protected by the menu system.
  50. * The "access callback" with an optional "access arguments" of each menu
  51. * item is called before the page callback proceeds. If this returns TRUE,
  52. * then access is granted; if FALSE, then access is denied. Default local task
  53. * menu items (see next paragraph) may omit this attribute to use the value
  54. * provided by the parent item.
  55. *
  56. * In the default Drupal interface, you will notice many links rendered as
  57. * tabs. These are known in the menu system as "local tasks", and they are
  58. * rendered as tabs by default, though other presentations are possible.
  59. * Local tasks function just as other menu items in most respects. It is
  60. * convention that the names of these tasks should be short verbs if
  61. * possible. In addition, a "default" local task should be provided for
  62. * each set. When visiting a local task's parent menu item, the default
  63. * local task will be rendered as if it is selected; this provides for a
  64. * normal tab user experience. This default task is special in that it
  65. * links not to its provided path, but to its parent item's path instead.
  66. * The default task's path is only used to place it appropriately in the
  67. * menu hierarchy.
  68. *
  69. * Everything described so far is stored in the menu_router table. The
  70. * menu_links table holds the visible menu links. By default these are
  71. * derived from the same hook_menu definitions, however you are free to
  72. * add more with menu_link_save().
  73. */
  74. /**
  75. * @defgroup menu_flags Menu flags
  76. * @{
  77. * Flags for use in the "type" attribute of menu items.
  78. */
  79. /**
  80. * Internal menu flag -- menu item is the root of the menu tree.
  81. */
  82. define('MENU_IS_ROOT', 0x0001);
  83. /**
  84. * Internal menu flag -- menu item is visible in the menu tree.
  85. */
  86. define('MENU_VISIBLE_IN_TREE', 0x0002);
  87. /**
  88. * Internal menu flag -- menu item is visible in the breadcrumb.
  89. */
  90. define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
  91. /**
  92. * Internal menu flag -- menu item links back to its parent.
  93. */
  94. define('MENU_LINKS_TO_PARENT', 0x0008);
  95. /**
  96. * Internal menu flag -- menu item can be modified by administrator.
  97. */
  98. define('MENU_MODIFIED_BY_ADMIN', 0x0020);
  99. /**
  100. * Internal menu flag -- menu item was created by administrator.
  101. */
  102. define('MENU_CREATED_BY_ADMIN', 0x0040);
  103. /**
  104. * Internal menu flag -- menu item is a local task.
  105. */
  106. define('MENU_IS_LOCAL_TASK', 0x0080);
  107. /**
  108. * Internal menu flag -- menu item is a local action.
  109. */
  110. define('MENU_IS_LOCAL_ACTION', 0x0100);
  111. /**
  112. * @} End of "Menu flags".
  113. */
  114. /**
  115. * @defgroup menu_item_types Menu item types
  116. * @{
  117. * Definitions for various menu item types.
  118. *
  119. * Menu item definitions provide one of these constants, which are shortcuts for
  120. * combinations of @link menu_flags Menu flags @endlink.
  121. */
  122. /**
  123. * Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.
  124. *
  125. * Normal menu items show up in the menu tree and can be moved/hidden by
  126. * the administrator. Use this for most menu items. It is the default value if
  127. * no menu item type is specified.
  128. */
  129. define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB);
  130. /**
  131. * Menu type -- A hidden, internal callback, typically used for API calls.
  132. *
  133. * Callbacks simply register a path so that the correct function is fired
  134. * when the URL is accessed. They do not appear in menus or breadcrumbs.
  135. */
  136. define('MENU_CALLBACK', 0x0000);
  137. /**
  138. * Menu type -- A normal menu item, hidden until enabled by an administrator.
  139. *
  140. * Modules may "suggest" menu items that the administrator may enable. They act
  141. * just as callbacks do until enabled, at which time they act like normal items.
  142. * Note for the value: 0x0010 was a flag which is no longer used, but this way
  143. * the values of MENU_CALLBACK and MENU_SUGGESTED_ITEM are separate.
  144. */
  145. define('MENU_SUGGESTED_ITEM', MENU_VISIBLE_IN_BREADCRUMB | 0x0010);
  146. /**
  147. * Menu type -- A task specific to the parent item, usually rendered as a tab.
  148. *
  149. * Local tasks are menu items that describe actions to be performed on their
  150. * parent item. An example is the path "node/52/edit", which performs the
  151. * "edit" task on "node/52".
  152. */
  153. define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_VISIBLE_IN_BREADCRUMB);
  154. /**
  155. * Menu type -- The "default" local task, which is initially active.
  156. *
  157. * Every set of local tasks should provide one "default" task, that links to the
  158. * same path as its parent when clicked.
  159. */
  160. define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT | MENU_VISIBLE_IN_BREADCRUMB);
  161. /**
  162. * Menu type -- An action specific to the parent, usually rendered as a link.
  163. *
  164. * Local actions are menu items that describe actions on the parent item such
  165. * as adding a new user, taxonomy term, etc.
  166. */
  167. define('MENU_LOCAL_ACTION', MENU_IS_LOCAL_TASK | MENU_IS_LOCAL_ACTION | MENU_VISIBLE_IN_BREADCRUMB);
  168. /**
  169. * @} End of "Menu item types".
  170. */
  171. /**
  172. * @defgroup menu_context_types Menu context types
  173. * @{
  174. * Flags for use in the "context" attribute of menu router items.
  175. */
  176. /**
  177. * Internal menu flag: Invisible local task.
  178. *
  179. * This flag may be used for local tasks like "Delete", so custom modules and
  180. * themes can alter the default context and expose the task by altering menu.
  181. */
  182. define('MENU_CONTEXT_NONE', 0x0000);
  183. /**
  184. * Internal menu flag: Local task should be displayed in page context.
  185. */
  186. define('MENU_CONTEXT_PAGE', 0x0001);
  187. /**
  188. * Internal menu flag: Local task should be displayed inline.
  189. */
  190. define('MENU_CONTEXT_INLINE', 0x0002);
  191. /**
  192. * @} End of "Menu context types".
  193. */
  194. /**
  195. * @defgroup menu_status_codes Menu status codes
  196. * @{
  197. * Status codes for menu callbacks.
  198. */
  199. /**
  200. * Internal menu status code -- Menu item was found.
  201. */
  202. define('MENU_FOUND', 1);
  203. /**
  204. * Internal menu status code -- Menu item was not found.
  205. */
  206. define('MENU_NOT_FOUND', 2);
  207. /**
  208. * Internal menu status code -- Menu item access is denied.
  209. */
  210. define('MENU_ACCESS_DENIED', 3);
  211. /**
  212. * Internal menu status code -- Menu item inaccessible because site is offline.
  213. */
  214. define('MENU_SITE_OFFLINE', 4);
  215. /**
  216. * Internal menu status code -- Everything is working fine.
  217. */
  218. define('MENU_SITE_ONLINE', 5);
  219. /**
  220. * @} End of "Menu status codes".
  221. */
  222. /**
  223. * @defgroup menu_tree_parameters Menu tree parameters
  224. * @{
  225. * Parameters for a menu tree.
  226. */
  227. /**
  228. * The maximum number of path elements for a menu callback
  229. */
  230. define('MENU_MAX_PARTS', 9);
  231. /**
  232. * The maximum depth of a menu links tree - matches the number of p columns.
  233. */
  234. define('MENU_MAX_DEPTH', 9);
  235. /**
  236. * @} End of "Menu tree parameters".
  237. */
  238. /**
  239. * Reserved key to identify the most specific menu link for a given path.
  240. *
  241. * The value of this constant is a hash of the constant name. We use the hash
  242. * so that the reserved key is over 32 characters in length and will not
  243. * collide with allowed menu names:
  244. * @code
  245. * sha1('MENU_PREFERRED_LINK') = 1cf698d64d1aa4b83907cf6ed55db3a7f8e92c91
  246. * @endcode
  247. *
  248. * @see menu_link_get_preferred()
  249. */
  250. define('MENU_PREFERRED_LINK', '1cf698d64d1aa4b83907cf6ed55db3a7f8e92c91');
  251. /**
  252. * Returns the ancestors (and relevant placeholders) for any given path.
  253. *
  254. * For example, the ancestors of node/12345/edit are:
  255. * - node/12345/edit
  256. * - node/12345/%
  257. * - node/%/edit
  258. * - node/%/%
  259. * - node/12345
  260. * - node/%
  261. * - node
  262. *
  263. * To generate these, we will use binary numbers. Each bit represents a
  264. * part of the path. If the bit is 1, then it represents the original
  265. * value while 0 means wildcard. If the path is node/12/edit/foo
  266. * then the 1011 bitstring represents node/%/edit/foo where % means that
  267. * any argument matches that part. We limit ourselves to using binary
  268. * numbers that correspond the patterns of wildcards of router items that
  269. * actually exists. This list of 'masks' is built in menu_rebuild().
  270. *
  271. * @param $parts
  272. * An array of path parts; for the above example,
  273. * array('node', '12345', 'edit').
  274. *
  275. * @return
  276. * An array which contains the ancestors and placeholders. Placeholders
  277. * simply contain as many '%s' as the ancestors.
  278. */
  279. function menu_get_ancestors($parts) {
  280. $number_parts = count($parts);
  281. $ancestors = array();
  282. $length = $number_parts - 1;
  283. $end = (1 << $number_parts) - 1;
  284. $masks = variable_get('menu_masks');
  285. // If the optimized menu_masks array is not available use brute force to get
  286. // the correct $ancestors and $placeholders returned. Do not use this as the
  287. // default value of the menu_masks variable to avoid building such a big
  288. // array.
  289. if (!$masks) {
  290. $masks = range(511, 1);
  291. }
  292. // Only examine patterns that actually exist as router items (the masks).
  293. foreach ($masks as $i) {
  294. if ($i > $end) {
  295. // Only look at masks that are not longer than the path of interest.
  296. continue;
  297. }
  298. elseif ($i < (1 << $length)) {
  299. // We have exhausted the masks of a given length, so decrease the length.
  300. --$length;
  301. }
  302. $current = '';
  303. for ($j = $length; $j >= 0; $j--) {
  304. // Check the bit on the $j offset.
  305. if ($i & (1 << $j)) {
  306. // Bit one means the original value.
  307. $current .= $parts[$length - $j];
  308. }
  309. else {
  310. // Bit zero means means wildcard.
  311. $current .= '%';
  312. }
  313. // Unless we are at offset 0, add a slash.
  314. if ($j) {
  315. $current .= '/';
  316. }
  317. }
  318. $ancestors[] = $current;
  319. }
  320. return $ancestors;
  321. }
  322. /**
  323. * Unserializes menu data, using a map to replace path elements.
  324. *
  325. * The menu system stores various path-related information (such as the 'page
  326. * arguments' and 'access arguments' components of a menu item) in the database
  327. * using serialized arrays, where integer values in the arrays represent
  328. * arguments to be replaced by values from the path. This function first
  329. * unserializes such menu information arrays, and then does the path
  330. * replacement.
  331. *
  332. * The path replacement acts on each integer-valued element of the unserialized
  333. * menu data array ($data) using a map array ($map, which is typically an array
  334. * of path arguments) as a list of replacements. For instance, if there is an
  335. * element of $data whose value is the number 2, then it is replaced in $data
  336. * with $map[2]; non-integer values in $data are left alone.
  337. *
  338. * As an example, an unserialized $data array with elements ('node_load', 1)
  339. * represents instructions for calling the node_load() function. Specifically,
  340. * this instruction says to use the path component at index 1 as the input
  341. * parameter to node_load(). If the path is 'node/123', then $map will be the
  342. * array ('node', 123), and the returned array from this function will have
  343. * elements ('node_load', 123), since $map[1] is 123. This return value will
  344. * indicate specifically that node_load(123) is to be called to load the node
  345. * whose ID is 123 for this menu item.
  346. *
  347. * @param $data
  348. * A serialized array of menu data, as read from the database.
  349. * @param $map
  350. * A path argument array, used to replace integer values in $data; an integer
  351. * value N in $data will be replaced by value $map[N]. Typically, the $map
  352. * array is generated from a call to the arg() function.
  353. *
  354. * @return
  355. * The unserialized $data array, with path arguments replaced.
  356. */
  357. function menu_unserialize($data, $map) {
  358. if ($data = unserialize($data)) {
  359. foreach ($data as $k => $v) {
  360. if (is_int($v)) {
  361. $data[$k] = isset($map[$v]) ? $map[$v] : '';
  362. }
  363. }
  364. return $data;
  365. }
  366. else {
  367. return array();
  368. }
  369. }
  370. /**
  371. * Replaces the statically cached item for a given path.
  372. *
  373. * @param $path
  374. * The path.
  375. * @param $router_item
  376. * The router item. Usually a router entry from menu_get_item() is either
  377. * modified or set to a different path. This allows the navigation block,
  378. * the page title, the breadcrumb, and the page help to be modified in one
  379. * call.
  380. */
  381. function menu_set_item($path, $router_item) {
  382. menu_get_item($path, $router_item);
  383. }
  384. /**
  385. * Gets a router item.
  386. *
  387. * @param $path
  388. * The path; for example, 'node/5'. The function will find the corresponding
  389. * node/% item and return that.
  390. * @param $router_item
  391. * Internal use only.
  392. *
  393. * @return
  394. * The router item or, if an error occurs in _menu_translate(), FALSE. A
  395. * router item is an associative array corresponding to one row in the
  396. * menu_router table. The value corresponding to the key 'map' holds the
  397. * loaded objects. The value corresponding to the key 'access' is TRUE if the
  398. * current user can access this page. The values corresponding to the keys
  399. * 'title', 'page_arguments', 'access_arguments', and 'theme_arguments' will
  400. * be filled in based on the database values and the objects loaded.
  401. */
  402. function menu_get_item($path = NULL, $router_item = NULL) {
  403. $router_items = &drupal_static(__FUNCTION__);
  404. if (!isset($path)) {
  405. $path = $_GET['q'];
  406. }
  407. if (isset($router_item)) {
  408. $router_items[$path] = $router_item;
  409. }
  410. if (!isset($router_items[$path])) {
  411. // Rebuild if we know it's needed, or if the menu masks are missing which
  412. // occurs rarely, likely due to a race condition of multiple rebuilds.
  413. if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
  414. if (_menu_check_rebuild()) {
  415. menu_rebuild();
  416. }
  417. }
  418. $original_map = arg(NULL, $path);
  419. $parts = array_slice($original_map, 0, MENU_MAX_PARTS);
  420. $ancestors = menu_get_ancestors($parts);
  421. $router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();
  422. if ($router_item) {
  423. // Allow modules to alter the router item before it is translated and
  424. // checked for access.
  425. drupal_alter('menu_get_item', $router_item, $path, $original_map);
  426. $map = _menu_translate($router_item, $original_map);
  427. $router_item['original_map'] = $original_map;
  428. if ($map === FALSE) {
  429. $router_items[$path] = FALSE;
  430. return FALSE;
  431. }
  432. if ($router_item['access']) {
  433. $router_item['map'] = $map;
  434. $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
  435. $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
  436. }
  437. }
  438. $router_items[$path] = $router_item;
  439. }
  440. return $router_items[$path];
  441. }
  442. /**
  443. * Execute the page callback associated with the current path.
  444. *
  445. * @param $path
  446. * The drupal path whose handler is to be be executed. If set to NULL, then
  447. * the current path is used.
  448. * @param $deliver
  449. * (optional) A boolean to indicate whether the content should be sent to the
  450. * browser using the appropriate delivery callback (TRUE) or whether to return
  451. * the result to the caller (FALSE).
  452. */
  453. function menu_execute_active_handler($path = NULL, $deliver = TRUE) {
  454. // Check if site is offline.
  455. $page_callback_result = _menu_site_is_offline() ? MENU_SITE_OFFLINE : MENU_SITE_ONLINE;
  456. // Allow other modules to change the site status but not the path because that
  457. // would not change the global variable. hook_url_inbound_alter() can be used
  458. // to change the path. Code later will not use the $read_only_path variable.
  459. $read_only_path = !empty($path) ? $path : $_GET['q'];
  460. drupal_alter('menu_site_status', $page_callback_result, $read_only_path);
  461. // Only continue if the site status is not set.
  462. if ($page_callback_result == MENU_SITE_ONLINE) {
  463. if ($router_item = menu_get_item($path)) {
  464. if ($router_item['access']) {
  465. if ($router_item['include_file']) {
  466. require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
  467. }
  468. $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
  469. }
  470. else {
  471. $page_callback_result = MENU_ACCESS_DENIED;
  472. }
  473. }
  474. else {
  475. $page_callback_result = MENU_NOT_FOUND;
  476. }
  477. }
  478. // Deliver the result of the page callback to the browser, or if requested,
  479. // return it raw, so calling code can do more processing.
  480. if ($deliver) {
  481. $default_delivery_callback = (isset($router_item) && $router_item) ? $router_item['delivery_callback'] : NULL;
  482. drupal_deliver_page($page_callback_result, $default_delivery_callback);
  483. }
  484. else {
  485. return $page_callback_result;
  486. }
  487. }
  488. /**
  489. * Loads objects into the map as defined in the $item['load_functions'].
  490. *
  491. * @param $item
  492. * A menu router or menu link item
  493. * @param $map
  494. * An array of path arguments; for example, array('node', '5').
  495. *
  496. * @return
  497. * Returns TRUE for success, FALSE if an object cannot be loaded.
  498. * Names of object loading functions are placed in $item['load_functions'].
  499. * Loaded objects are placed in $map[]; keys are the same as keys in the
  500. * $item['load_functions'] array.
  501. * $item['access'] is set to FALSE if an object cannot be loaded.
  502. */
  503. function _menu_load_objects(&$item, &$map) {
  504. if ($load_functions = $item['load_functions']) {
  505. // If someone calls this function twice, then unserialize will fail.
  506. if (!is_array($load_functions)) {
  507. $load_functions = unserialize($load_functions);
  508. }
  509. $path_map = $map;
  510. foreach ($load_functions as $index => $function) {
  511. if ($function) {
  512. $value = isset($path_map[$index]) ? $path_map[$index] : '';
  513. if (is_array($function)) {
  514. // Set up arguments for the load function. These were pulled from
  515. // 'load arguments' in the hook_menu() entry, but they need
  516. // some processing. In this case the $function is the key to the
  517. // load_function array, and the value is the list of arguments.
  518. list($function, $args) = each($function);
  519. $load_functions[$index] = $function;
  520. // Some arguments are placeholders for dynamic items to process.
  521. foreach ($args as $i => $arg) {
  522. if ($arg === '%index') {
  523. // Pass on argument index to the load function, so multiple
  524. // occurrences of the same placeholder can be identified.
  525. $args[$i] = $index;
  526. }
  527. if ($arg === '%map') {
  528. // Pass on menu map by reference. The accepting function must
  529. // also declare this as a reference if it wants to modify
  530. // the map.
  531. $args[$i] = &$map;
  532. }
  533. if (is_int($arg)) {
  534. $args[$i] = isset($path_map[$arg]) ? $path_map[$arg] : '';
  535. }
  536. }
  537. array_unshift($args, $value);
  538. $return = call_user_func_array($function, $args);
  539. }
  540. else {
  541. $return = $function($value);
  542. }
  543. // If callback returned an error or there is no callback, trigger 404.
  544. if ($return === FALSE) {
  545. $item['access'] = FALSE;
  546. $map = FALSE;
  547. return FALSE;
  548. }
  549. $map[$index] = $return;
  550. }
  551. }
  552. $item['load_functions'] = $load_functions;
  553. }
  554. return TRUE;
  555. }
  556. /**
  557. * Checks access to a menu item using the access callback.
  558. *
  559. * @param $item
  560. * A menu router or menu link item
  561. * @param $map
  562. * An array of path arguments; for example, array('node', '5').
  563. *
  564. * @return
  565. * $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
  566. */
  567. function _menu_check_access(&$item, $map) {
  568. $item['access'] = FALSE;
  569. // Determine access callback, which will decide whether or not the current
  570. // user has access to this path.
  571. $callback = empty($item['access_callback']) ? 0 : trim($item['access_callback']);
  572. // Check for a TRUE or FALSE value.
  573. if (is_numeric($callback)) {
  574. $item['access'] = (bool) $callback;
  575. }
  576. else {
  577. $arguments = menu_unserialize($item['access_arguments'], $map);
  578. // As call_user_func_array is quite slow and user_access is a very common
  579. // callback, it is worth making a special case for it.
  580. if ($callback == 'user_access') {
  581. $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
  582. }
  583. elseif (function_exists($callback)) {
  584. $item['access'] = call_user_func_array($callback, $arguments);
  585. }
  586. }
  587. }
  588. /**
  589. * Localizes the router item title using t() or another callback.
  590. *
  591. * Translate the title and description to allow storage of English title
  592. * strings in the database, yet display of them in the language required
  593. * by the current user.
  594. *
  595. * @param $item
  596. * A menu router item or a menu link item.
  597. * @param $map
  598. * The path as an array with objects already replaced. E.g., for path
  599. * node/123 $map would be array('node', $node) where $node is the node
  600. * object for node 123.
  601. * @param $link_translate
  602. * TRUE if we are translating a menu link item; FALSE if we are
  603. * translating a menu router item.
  604. *
  605. * @return
  606. * No return value.
  607. * $item['title'] is localized according to $item['title_callback'].
  608. * If an item's callback is check_plain(), $item['options']['html'] becomes
  609. * TRUE.
  610. * $item['description'] is translated using t().
  611. * When doing link translation and the $item['options']['attributes']['title']
  612. * (link title attribute) matches the description, it is translated as well.
  613. */
  614. function _menu_item_localize(&$item, $map, $link_translate = FALSE) {
  615. $callback = $item['title_callback'];
  616. $item['localized_options'] = $item['options'];
  617. // All 'class' attributes are assumed to be an array during rendering, but
  618. // links stored in the database may use an old string value.
  619. // @todo In order to remove this code we need to implement a database update
  620. // including unserializing all existing link options and running this code
  621. // on them, as well as adding validation to menu_link_save().
  622. if (isset($item['options']['attributes']['class']) && is_string($item['options']['attributes']['class'])) {
  623. $item['localized_options']['attributes']['class'] = explode(' ', $item['options']['attributes']['class']);
  624. }
  625. // If we are translating the title of a menu link, and its title is the same
  626. // as the corresponding router item, then we can use the title information
  627. // from the router. If it's customized, then we need to use the link title
  628. // itself; can't localize.
  629. // If we are translating a router item (tabs, page, breadcrumb), then we
  630. // can always use the information from the router item.
  631. if (!$link_translate || ($item['title'] == $item['link_title'])) {
  632. // t() is a special case. Since it is used very close to all the time,
  633. // we handle it directly instead of using indirect, slower methods.
  634. if ($callback == 't') {
  635. if (empty($item['title_arguments'])) {
  636. $item['title'] = t($item['title']);
  637. }
  638. else {
  639. $item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));
  640. }
  641. }
  642. elseif ($callback && function_exists($callback)) {
  643. if (empty($item['title_arguments'])) {
  644. $item['title'] = $callback($item['title']);
  645. }
  646. else {
  647. $item['title'] = call_user_func_array($callback, menu_unserialize($item['title_arguments'], $map));
  648. }
  649. // Avoid calling check_plain again on l() function.
  650. if ($callback == 'check_plain') {
  651. $item['localized_options']['html'] = TRUE;
  652. }
  653. }
  654. }
  655. elseif ($link_translate) {
  656. $item['title'] = $item['link_title'];
  657. }
  658. // Translate description, see the motivation above.
  659. if (!empty($item['description'])) {
  660. $original_description = $item['description'];
  661. $item['description'] = t($item['description']);
  662. if ($link_translate && isset($item['options']['attributes']['title']) && $item['options']['attributes']['title'] == $original_description) {
  663. $item['localized_options']['attributes']['title'] = $item['description'];
  664. }
  665. }
  666. }
  667. /**
  668. * Handles dynamic path translation and menu access control.
  669. *
  670. * When a user arrives on a page such as node/5, this function determines
  671. * what "5" corresponds to, by inspecting the page's menu path definition,
  672. * node/%node. This will call node_load(5) to load the corresponding node
  673. * object.
  674. *
  675. * It also works in reverse, to allow the display of tabs and menu items which
  676. * contain these dynamic arguments, translating node/%node to node/5.
  677. *
  678. * Translation of menu item titles and descriptions are done here to
  679. * allow for storage of English strings in the database, and translation
  680. * to the language required to generate the current page.
  681. *
  682. * @param $router_item
  683. * A menu router item
  684. * @param $map
  685. * An array of path arguments; for example, array('node', '5').
  686. * @param $to_arg
  687. * Execute $item['to_arg_functions'] or not. Use only if you want to render a
  688. * path from the menu table, for example tabs.
  689. *
  690. * @return
  691. * Returns the map with objects loaded as defined in the
  692. * $item['load_functions']. $item['access'] becomes TRUE if the item is
  693. * accessible, FALSE otherwise. $item['href'] is set according to the map.
  694. * If an error occurs during calling the load_functions (like trying to load
  695. * a non-existent node) then this function returns FALSE.
  696. */
  697. function _menu_translate(&$router_item, $map, $to_arg = FALSE) {
  698. if ($to_arg && !empty($router_item['to_arg_functions'])) {
  699. // Fill in missing path elements, such as the current uid.
  700. _menu_link_map_translate($map, $router_item['to_arg_functions']);
  701. }
  702. // The $path_map saves the pieces of the path as strings, while elements in
  703. // $map may be replaced with loaded objects.
  704. $path_map = $map;
  705. if (!empty($router_item['load_functions']) && !_menu_load_objects($router_item, $map)) {
  706. // An error occurred loading an object.
  707. $router_item['access'] = FALSE;
  708. return FALSE;
  709. }
  710. // Generate the link path for the page request or local tasks.
  711. $link_map = explode('/', $router_item['path']);
  712. if (isset($router_item['tab_root'])) {
  713. $tab_root_map = explode('/', $router_item['tab_root']);
  714. }
  715. if (isset($router_item['tab_parent'])) {
  716. $tab_parent_map = explode('/', $router_item['tab_parent']);
  717. }
  718. for ($i = 0; $i < $router_item['number_parts']; $i++) {
  719. if ($link_map[$i] == '%') {
  720. $link_map[$i] = $path_map[$i];
  721. }
  722. if (isset($tab_root_map[$i]) && $tab_root_map[$i] == '%') {
  723. $tab_root_map[$i] = $path_map[$i];
  724. }
  725. if (isset($tab_parent_map[$i]) && $tab_parent_map[$i] == '%') {
  726. $tab_parent_map[$i] = $path_map[$i];
  727. }
  728. }
  729. $router_item['href'] = implode('/', $link_map);
  730. $router_item['tab_root_href'] = implode('/', $tab_root_map);
  731. $router_item['tab_parent_href'] = implode('/', $tab_parent_map);
  732. $router_item['options'] = array();
  733. _menu_check_access($router_item, $map);
  734. // For performance, don't localize an item the user can't access.
  735. if ($router_item['access']) {
  736. _menu_item_localize($router_item, $map);
  737. }
  738. return $map;
  739. }
  740. /**
  741. * Translates the path elements in the map using any to_arg helper function.
  742. *
  743. * @param $map
  744. * An array of path arguments; for example, array('node', '5').
  745. * @param $to_arg_functions
  746. * An array of helper functions; for example, array(2 => 'menu_tail_to_arg').
  747. *
  748. * @see hook_menu()
  749. */
  750. function _menu_link_map_translate(&$map, $to_arg_functions) {
  751. $to_arg_functions = unserialize($to_arg_functions);
  752. foreach ($to_arg_functions as $index => $function) {
  753. // Translate place-holders into real values.
  754. $arg = $function(!empty($map[$index]) ? $map[$index] : '', $map, $index);
  755. if (!empty($map[$index]) || isset($arg)) {
  756. $map[$index] = $arg;
  757. }
  758. else {
  759. unset($map[$index]);
  760. }
  761. }
  762. }
  763. /**
  764. * Returns a string containing the path relative to the current index.
  765. */
  766. function menu_tail_to_arg($arg, $map, $index) {
  767. return implode('/', array_slice($map, $index));
  768. }
  769. /**
  770. * Loads the path as one string relative to the current index.
  771. *
  772. * To use this load function, you must specify the load arguments
  773. * in the router item as:
  774. * @code
  775. * $item['load arguments'] = array('%map', '%index');
  776. * @endcode
  777. *
  778. * @see search_menu().
  779. */
  780. function menu_tail_load($arg, &$map, $index) {
  781. $arg = implode('/', array_slice($map, $index));
  782. $map = array_slice($map, 0, $index);
  783. return $arg;
  784. }
  785. /**
  786. * Provides menu link access control, translation, and argument handling.
  787. *
  788. * This function is similar to _menu_translate(), but it also does
  789. * link-specific preparation (such as always calling to_arg() functions).
  790. *
  791. * @param $item
  792. * A menu link.
  793. * @param $translate
  794. * (optional) Whether to try to translate a link containing dynamic path
  795. * argument placeholders (%) based on the menu router item of the current
  796. * path. Defaults to FALSE. Internally used for breadcrumbs.
  797. *
  798. * @return
  799. * Returns the map of path arguments with objects loaded as defined in the
  800. * $item['load_functions'].
  801. * $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
  802. * $item['href'] is generated from link_path, possibly by to_arg functions.
  803. * $item['title'] is generated from link_title, and may be localized.
  804. * $item['options'] is unserialized; it is also changed within the call here
  805. * to $item['localized_options'] by _menu_item_localize().
  806. */
  807. function _menu_link_translate(&$item, $translate = FALSE) {
  808. if (!is_array($item['options'])) {
  809. $item['options'] = unserialize($item['options']);
  810. }
  811. if ($item['external']) {
  812. $item['access'] = 1;
  813. $map = array();
  814. $item['href'] = $item['link_path'];
  815. $item['title'] = $item['link_title'];
  816. $item['localized_options'] = $item['options'];
  817. }
  818. else {
  819. // Complete the path of the menu link with elements from the current path,
  820. // if it contains dynamic placeholders (%).
  821. $map = explode('/', $item['link_path']);
  822. if (strpos($item['link_path'], '%') !== FALSE) {
  823. // Invoke registered to_arg callbacks.
  824. if (!empty($item['to_arg_functions'])) {
  825. _menu_link_map_translate($map, $item['to_arg_functions']);
  826. }
  827. // Or try to derive the path argument map from the current router item,
  828. // if this $item's path is within the router item's path. This means
  829. // that if we are on the current path 'foo/%/bar/%/baz', then
  830. // menu_get_item() will have translated the menu router item for the
  831. // current path, and we can take over the argument map for a link like
  832. // 'foo/%/bar'. This inheritance is only valid for breadcrumb links.
  833. // @see _menu_tree_check_access()
  834. // @see menu_get_active_breadcrumb()
  835. elseif ($translate && ($current_router_item = menu_get_item())) {
  836. // If $translate is TRUE, then this link is in the active trail.
  837. // Only translate paths within the current path.
  838. if (strpos($current_router_item['path'], $item['link_path']) === 0) {
  839. $count = count($map);
  840. $map = array_slice($current_router_item['original_map'], 0, $count);
  841. $item['original_map'] = $map;
  842. if (isset($current_router_item['map'])) {
  843. $item['map'] = array_slice($current_router_item['map'], 0, $count);
  844. }
  845. // Reset access to check it (for the first time).
  846. unset($item['access']);
  847. }
  848. }
  849. }
  850. $item['href'] = implode('/', $map);
  851. // Skip links containing untranslated arguments.
  852. if (strpos($item['href'], '%') !== FALSE) {
  853. $item['access'] = FALSE;
  854. return FALSE;
  855. }
  856. // menu_tree_check_access() may set this ahead of time for links to nodes.
  857. if (!isset($item['access'])) {
  858. if (!empty($item['load_functions']) && !_menu_load_objects($item, $map)) {
  859. // An error occurred loading an object.
  860. $item['access'] = FALSE;
  861. return FALSE;
  862. }
  863. _menu_check_access($item, $map);
  864. }
  865. // For performance, don't localize a link the user can't access.
  866. if ($item['access']) {
  867. _menu_item_localize($item, $map, TRUE);
  868. }
  869. }
  870. // Allow other customizations - e.g. adding a page-specific query string to the
  871. // options array. For performance reasons we only invoke this hook if the link
  872. // has the 'alter' flag set in the options array.
  873. if (!empty($item['options']['alter'])) {
  874. drupal_alter('translated_menu_link', $item, $map);
  875. }
  876. return $map;
  877. }
  878. /**
  879. * Gets a loaded object from a router item.
  880. *
  881. * menu_get_object() provides access to objects loaded by the current router
  882. * item. For example, on the page node/%node, the router loads the %node object,
  883. * and calling menu_get_object() will return that. Normally, it is necessary to
  884. * specify the type of object referenced, however node is the default.
  885. * The following example tests to see whether the node being displayed is of the
  886. * "story" content type:
  887. * @code
  888. * $node = menu_get_object();
  889. * $story = $node->type == 'story';
  890. * @endcode
  891. *
  892. * @param $type
  893. * Type of the object. These appear in hook_menu definitions as %type. Core
  894. * provides aggregator_feed, aggregator_category, contact, filter_format,
  895. * forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the
  896. * relevant {$type}_load function for more on each. Defaults to node.
  897. * @param $position
  898. * The position of the object in the path, where the first path segment is 0.
  899. * For node/%node, the position of %node is 1, but for comment/reply/%node,
  900. * it's 2. Defaults to 1.
  901. * @param $path
  902. * See menu_get_item() for more on this. Defaults to the current path.
  903. */
  904. function menu_get_object($type = 'node', $position = 1, $path = NULL) {
  905. $router_item = menu_get_item($path);
  906. if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
  907. return $router_item['map'][$position];
  908. }
  909. }
  910. /**
  911. * Renders a menu tree based on the current path.
  912. *
  913. * The tree is expanded based on the current path and dynamic paths are also
  914. * changed according to the defined to_arg functions (for example the 'My
  915. * account' link is changed from user/% to a link with the current user's uid).
  916. *
  917. * @param $menu_name
  918. * The name of the menu.
  919. *
  920. * @return
  921. * A structured array representing the specified menu on the current page, to
  922. * be rendered by drupal_render().
  923. */
  924. function menu_tree($menu_name) {
  925. $menu_output = &drupal_static(__FUNCTION__, array());
  926. if (!isset($menu_output[$menu_name])) {
  927. $tree = menu_tree_page_data($menu_name);
  928. $menu_output[$menu_name] = menu_tree_output($tree);
  929. }
  930. return $menu_output[$menu_name];
  931. }
  932. /**
  933. * Returns an output structure for rendering a menu tree.
  934. *
  935. * The menu item's LI element is given one of the following classes:
  936. * - expanded: The menu item is showing its submenu.
  937. * - collapsed: The menu item has a submenu which is not shown.
  938. * - leaf: The menu item has no submenu.
  939. *
  940. * @param $tree
  941. * A data structure representing the tree as returned from menu_tree_data.
  942. *
  943. * @return
  944. * A structured array to be rendered by drupal_render().
  945. */
  946. function menu_tree_output($tree) {
  947. $build = array();
  948. $items = array();
  949. // Pull out just the menu links we are going to render so that we
  950. // get an accurate count for the first/last classes.
  951. foreach ($tree as $data) {
  952. if ($data['link']['access'] && !$data['link']['hidden']) {
  953. $items[] = $data;
  954. }
  955. }
  956. $router_item = menu_get_item();
  957. $num_items = count($items);
  958. foreach ($items as $i => $data) {
  959. $class = array();
  960. if ($i == 0) {
  961. $class[] = 'first';
  962. }
  963. if ($i == $num_items - 1) {
  964. $class[] = 'last';
  965. }
  966. // Set a class for the <li>-tag. Since $data['below'] may contain local
  967. // tasks, only set 'expanded' class if the link also has children within
  968. // the current menu.
  969. if ($data['link']['has_children'] && $data['below']) {
  970. $class[] = 'expanded';
  971. }
  972. elseif ($data['link']['has_children']) {
  973. $class[] = 'collapsed';
  974. }
  975. else {
  976. $class[] = 'leaf';
  977. }
  978. // Set a class if the link is in the active trail.
  979. if ($data['link']['in_active_trail']) {
  980. $class[] = 'active-trail';
  981. $data['link']['localized_options']['attributes']['class'][] = 'active-trail';
  982. }
  983. // Normally, l() compares the href of every link with $_GET['q'] and sets
  984. // the active class accordingly. But local tasks do not appear in menu
  985. // trees, so if the current path is a local task, and this link is its
  986. // tab root, then we have to set the class manually.
  987. if ($data['link']['href'] == $router_item['tab_root_href'] && $data['link']['href'] != $_GET['q']) {
  988. $data['link']['localized_options']['attributes']['class'][] = 'active';
  989. }
  990. // Allow menu-specific theme overrides.
  991. $element['#theme'] = 'menu_link__' . strtr($data['link']['menu_name'], '-', '_');
  992. $element['#attributes']['class'] = $class;
  993. $element['#title'] = $data['link']['title'];
  994. $element['#href'] = $data['link']['href'];
  995. $element['#localized_options'] = !empty($data['link']['localized_options']) ? $data['link']['localized_options'] : array();
  996. $element['#below'] = $data['below'] ? menu_tree_output($data['below']) : $data['below'];
  997. $element['#original_link'] = $data['link'];
  998. // Index using the link's unique mlid.
  999. $build[$data['link']['mlid']] = $element;
  1000. }
  1001. if ($build) {
  1002. // Make sure drupal_render() does not re-order the links.
  1003. $build['#sorted'] = TRUE;
  1004. // Add the theme wrapper for outer markup.
  1005. // Allow menu-specific theme overrides.
  1006. $build['#theme_wrappers'][] = 'menu_tree__' . strtr($data['link']['menu_name'], '-', '_');
  1007. }
  1008. return $build;
  1009. }
  1010. /**
  1011. * Gets the data structure representing a named menu tree.
  1012. *
  1013. * Since this can be the full tree including hidden items, the data returned
  1014. * may be used for generating an an admin interface or a select.
  1015. *
  1016. * @param $menu_name
  1017. * The named menu links to return
  1018. * @param $link
  1019. * A fully loaded menu link, or NULL. If a link is supplied, only the
  1020. * path to root will be included in the returned tree - as if this link
  1021. * represented the current page in a visible menu.
  1022. * @param $max_depth
  1023. * Optional maximum depth of links to retrieve. Typically useful if only one
  1024. * or two levels of a sub tree are needed in conjunction with a non-NULL
  1025. * $link, in which case $max_depth should be greater than $link['depth'].
  1026. *
  1027. * @return
  1028. * An tree of menu links in an array, in the order they should be rendered.
  1029. */
  1030. function menu_tree_all_data($menu_name, $link = NULL, $max_depth = NULL) {
  1031. $tree = &drupal_static(__FUNCTION__, array());
  1032. // Use $mlid as a flag for whether the data being loaded is for the whole tree.
  1033. $mlid = isset($link['mlid']) ? $link['mlid'] : 0;
  1034. // Generate a cache ID (cid) specific for this $menu_name, $link, $language, and depth.
  1035. $cid = 'links:' . $menu_name . ':all:' . $mlid . ':' . $GLOBALS['language']->language . ':' . (int) $max_depth;
  1036. if (!isset($tree[$cid])) {
  1037. // If the static variable doesn't have the data, check {cache_menu}.
  1038. $cache = cache_get($cid, 'cache_menu');
  1039. if ($cache && isset($cache->data)) {
  1040. // If the cache entry exists, it contains the parameters for
  1041. // menu_build_tree().
  1042. $tree_parameters = $cache->data;
  1043. }
  1044. // If the tree data was not in the cache, build $tree_parameters.
  1045. if (!isset($tree_parameters)) {
  1046. $tree_parameters = array(
  1047. 'min_depth' => 1,
  1048. 'max_depth' => $max_depth,
  1049. );
  1050. if ($mlid) {
  1051. // The tree is for a single item, so we need to match the values in its
  1052. // p columns and 0 (the top level) with the plid values of other links.
  1053. $parents = array(0);
  1054. for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
  1055. if (!empty($link["p$i"])) {
  1056. $parents[] = $link["p$i"];
  1057. }
  1058. }
  1059. $tree_parameters['expanded'] = $parents;
  1060. $tree_parameters['active_trail'] = $parents;
  1061. $tree_parameters['active_trail'][] = $mlid;
  1062. }
  1063. // Cache the tree building parameters using the page-specific cid.
  1064. cache_set($cid, $tree_parameters, 'cache_menu');
  1065. }
  1066. // Build the tree using the parameters; the resulting tree will be cached
  1067. // by _menu_build_tree()).
  1068. $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
  1069. }
  1070. return $tree[$cid];
  1071. }
  1072. /**
  1073. * Sets the path for determining the active trail of the specified menu tree.
  1074. *
  1075. * This path will also affect the breadcrumbs under some circumstances.
  1076. * Breadcrumbs are built using the preferred link returned by
  1077. * menu_link_get_preferred(). If the preferred link is inside one of the menus
  1078. * specified in calls to menu_tree_set_path(), the preferred link will be
  1079. * overridden by the corresponding path returned by menu_tree_get_path().
  1080. *
  1081. * Setting this path does not affect the main content; for that use
  1082. * menu_set_active_item() instead.
  1083. *
  1084. * @param $menu_name
  1085. * The name of the affected menu tree.
  1086. * @param $path
  1087. * The path to use when finding the active trail.
  1088. */
  1089. function menu_tree_set_path($menu_name, $path = NULL) {
  1090. $paths = &drupal_static(__FUNCTION__);
  1091. if (isset($path)) {
  1092. $paths[$menu_name] = $path;
  1093. }
  1094. return isset($paths[$menu_name]) ? $paths[$menu_name] : NULL;
  1095. }
  1096. /**
  1097. * Gets the path for determining the active trail of the specified menu tree.
  1098. *
  1099. * @param $menu_name
  1100. * The menu name of the requested tree.
  1101. *
  1102. * @return
  1103. * A string containing the path. If no path has been specified with
  1104. * menu_tree_set_path(), NULL is returned.
  1105. */
  1106. function menu_tree_get_path($menu_name) {
  1107. return menu_tree_set_path($menu_name);
  1108. }
  1109. /**
  1110. * Gets the data structure for a named menu tree, based on the current page.
  1111. *
  1112. * The tree order is maintained by storing each parent in an individual
  1113. * field, see http://drupal.org/node/141866 for more.
  1114. *
  1115. * @param $menu_name
  1116. * The named menu links to return.
  1117. * @param $max_depth
  1118. * (optional) The maximum depth of links to retrieve.
  1119. * @param $only_active_trail
  1120. * (optional) Whether to only return the links in the active trail (TRUE)
  1121. * instead of all links on every level of the menu link tree (FALSE). Defaults
  1122. * to FALSE. Internally used for breadcrumbs only.
  1123. *
  1124. * @return
  1125. * An array of menu links, in the order they should be rendered. The array
  1126. * is a list of associative arrays -- these have two keys, link and below.
  1127. * link is a menu item, ready for theming as a link. Below represents the
  1128. * submenu below the link if there is one, and it is a subtree that has the
  1129. * same structure described for the top-level array.
  1130. */
  1131. function menu_tree_page_data($menu_name, $max_depth = NULL, $only_active_trail = FALSE) {
  1132. $tree = &drupal_static(__FUNCTION__, array());
  1133. // Check if the active trail has been overridden for this menu tree.
  1134. $active_path = menu_tree_get_path($menu_name);
  1135. // Load the menu item corresponding to the current page.
  1136. if ($item = menu_get_item($active_path)) {
  1137. if (isset($max_depth)) {
  1138. $max_depth = min($max_depth, MENU_MAX_DEPTH);
  1139. }
  1140. // Generate a cache ID (cid) specific for this page.
  1141. $cid = 'links:' . $menu_name . ':page:' . $item['href'] . ':' . $GLOBALS['language']->language . ':' . (int) $item['access'] . ':' . (int) $max_depth;
  1142. // If we are asked for the active trail only, and $menu_name has not been
  1143. // built and cached for this page yet, then this likely means that it
  1144. // won't be built anymore, as this function is invoked from
  1145. // template_process_page(). So in order to not build a giant menu tree
  1146. // that needs to be checked for access on all levels, we simply check
  1147. // whether we have the menu already in cache, or otherwise, build a minimum
  1148. // tree containing the breadcrumb/active trail only.
  1149. // @see menu_set_active_trail()
  1150. if (!isset($tree[$cid]) && $only_active_trail) {
  1151. $cid .= ':trail';
  1152. }
  1153. if (!isset($tree[$cid])) {
  1154. // If the static variable doesn't have the data, check {cache_menu}.
  1155. $cache = cache_get($cid, 'cache_menu');
  1156. if ($cache && isset($cache->data)) {
  1157. // If the cache entry exists, it contains the parameters for
  1158. // menu_build_tree().
  1159. $tree_parameters = $cache->data;
  1160. }
  1161. // If the tree data was not in the cache, build $tree_parameters.
  1162. if (!isset($tree_parameters)) {
  1163. $tree_parameters = array(
  1164. 'min_depth' => 1,
  1165. 'max_depth' => $max_depth,
  1166. );
  1167. // Parent mlids; used both as key and value to ensure uniqueness.
  1168. // We always want all the top-level links with plid == 0.
  1169. $active_trail = array(0 => 0);
  1170. // If the item for the current page is accessible, build the tree
  1171. // parameters accordingly.
  1172. if ($item['access']) {
  1173. // Find a menu link corresponding to the current path. If $active_path
  1174. // is NULL, let menu_link_get_preferred() determine the path.
  1175. if ($active_link = menu_link_get_preferred($active_path, $menu_name)) {
  1176. // The active link may only be taken into account to build the
  1177. // active trail, if it resides in the requested menu. Otherwise,
  1178. // we'd needlessly re-run _menu_build_tree() queries for every menu
  1179. // on every page.
  1180. if ($active_link['menu_name'] == $menu_name) {
  1181. // Use all the coordinates, except the last one because there
  1182. // can be no child beyond the last column.
  1183. for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
  1184. if ($active_link['p' . $i]) {
  1185. $active_trail[$active_link['p' . $i]] = $active_link['p' . $i];
  1186. }
  1187. }
  1188. // If we are asked to build links for the active trail only, skip
  1189. // the entire 'expanded' handling.
  1190. if ($only_active_trail) {
  1191. $tree_parameters['only_active_trail'] = TRUE;
  1192. }
  1193. }
  1194. }
  1195. $parents = $active_trail;
  1196. $expanded = variable_get('menu_expanded', array());
  1197. // Check whether the current menu has any links set to be expanded.
  1198. if (!$only_active_trail && in_array($menu_name, $expanded)) {
  1199. // Collect all the links set to be expanded, and then add all of
  1200. // their children to the list as well.
  1201. do {
  1202. $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
  1203. ->fields('menu_links', array('mlid'))
  1204. ->condition('menu_name', $menu_name)
  1205. ->condition('expanded', 1)
  1206. ->condition('has_children', 1)
  1207. ->condition('plid', $parents, 'IN')
  1208. ->condition('mlid', $parents, 'NOT IN')
  1209. ->execute();
  1210. $num_rows = FALSE;
  1211. foreach ($result as $item) {
  1212. $parents[$item['mlid']] = $item['mlid'];
  1213. $num_rows = TRUE;
  1214. }
  1215. } while ($num_rows);
  1216. }
  1217. $tree_parameters['expanded'] = $parents;
  1218. $tree_parameters['active_trail'] = $active_trail;
  1219. }
  1220. // If access is denied, we only show top-level links in menus.
  1221. else {
  1222. $tree_parameters['expanded'] = $active_trail;
  1223. $tree_parameters['active_trail'] = $active_trail;
  1224. }
  1225. // Cache the tree building parameters using the page-specific cid.
  1226. cache_set($cid, $tree_parameters, 'cache_menu');
  1227. }
  1228. // Build the tree using the parameters; the resulting tree will be cached
  1229. // by _menu_build_tree().
  1230. $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
  1231. }
  1232. return $tree[$cid];
  1233. }
  1234. return array();
  1235. }
  1236. /**
  1237. * Builds a menu tree, translates links, and checks access.
  1238. *
  1239. * @param $menu_name
  1240. * The name of the menu.
  1241. * @param $parameters
  1242. * (optional) An associative array of build parameters. Possible keys:
  1243. * - expanded: An array of parent link ids to return only menu links that are
  1244. * children of one of the plids in this list. If empty, the whole menu tree
  1245. * is built, unless 'only_active_trail' is TRUE.
  1246. * - active_trail: An array of mlids, representing the coordinates of the
  1247. * currently active menu link.
  1248. * - only_active_trail: Whether to only return links that are in the active
  1249. * trail. This option is ignored, if 'expanded' is non-empty. Internally
  1250. * used for breadcrumbs.
  1251. * - min_depth: The minimum depth of menu links in the resulting tree.
  1252. * Defaults to 1, which is the default to build a whole tree for a menu
  1253. * (excluding menu container itself).
  1254. * - max_depth: The maximum depth of menu links in the resulting tree.
  1255. * - conditions: An associative array of custom database select query
  1256. * condition key/value pairs; see _menu_build_tree() for the actual query.
  1257. *
  1258. * @return
  1259. * A fully built menu tree.
  1260. */
  1261. function menu_build_tree($menu_name, array $parameters = array()) {
  1262. // Build the menu tree.
  1263. $data = _menu_build_tree($menu_name, $parameters);
  1264. // Check access for the current user to each item in the tree.
  1265. menu_tree_check_access($data['tree'], $data['node_links']);
  1266. return $data['tree'];
  1267. }
  1268. /**
  1269. * Builds a menu tree.
  1270. *
  1271. * This function may be used build the data for a menu tree only, for example
  1272. * to further massage the data manually before further processing happens.
  1273. * menu_tree_check_access() needs to be invoked afterwards.
  1274. *
  1275. * @see menu_build_tree()
  1276. */
  1277. function _menu_build_tree($menu_name, array $parameters = array()) {
  1278. // Static cache of already built menu trees.
  1279. $trees = &drupal_static(__FUNCTION__, array());
  1280. // Build the cache id; sort parents to prevent duplicate storage and remove
  1281. // default parameter values.
  1282. if (isset($parameters['expanded'])) {
  1283. sort($parameters['expanded']);
  1284. }
  1285. $tree_cid = 'links:' . $menu_name . ':tree-data:' . $GLOBALS['language']->language . ':' . hash('sha256', serialize($parameters));
  1286. // If we do not have this tree in the static cache, check {cache_menu}.
  1287. if (!isset($trees[$tree_cid])) {
  1288. $cache = cache_get($tree_cid, 'cache_menu');
  1289. if ($cache && isset($cache->data)) {
  1290. $trees[$tree_cid] = $cache->data;
  1291. }
  1292. }
  1293. if (!isset($trees[$tree_cid])) {
  1294. // Select the links from the table, and recursively build the tree. We
  1295. // LEFT JOIN since there is no match in {menu_router} for an external
  1296. // link.
  1297. $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
  1298. $query->addTag('translatable');
  1299. $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
  1300. $query->fields('ml');
  1301. $query->fields('m', array(
  1302. 'load_functions',
  1303. 'to_arg_functions',
  1304. 'access_callback',
  1305. 'access_arguments',
  1306. 'page_callback',
  1307. 'page_arguments',
  1308. 'delivery_callback',
  1309. 'tab_parent',
  1310. 'tab_root',
  1311. 'title',
  1312. 'title_callback',
  1313. 'title_arguments',
  1314. 'theme_callback',
  1315. 'theme_arguments',
  1316. 'type',
  1317. 'description',
  1318. ));
  1319. for ($i = 1; $i <= MENU_MAX_DEPTH; $i++) {
  1320. $query->orderBy('p' . $i, 'ASC');
  1321. }
  1322. $query->condition('ml.menu_name', $menu_name);
  1323. if (!empty($parameters['expanded'])) {
  1324. $query->condition('ml.plid', $parameters['expanded'], 'IN');
  1325. }
  1326. elseif (!empty($parameters['only_active_trail'])) {
  1327. $query->condition('ml.mlid', $parameters['active_trail'], 'IN');
  1328. }
  1329. $min_depth = (isset($parameters['min_depth']) ? $parameters['min_depth'] : 1);
  1330. if ($min_depth != 1) {
  1331. $query->condition('ml.depth', $min_depth, '>=');
  1332. }
  1333. if (isset($parameters['max_depth'])) {
  1334. $query->condition('ml.depth', $parameters['max_depth'], '<=');
  1335. }
  1336. // Add custom query conditions, if any were passed.
  1337. if (isset($parameters['conditions'])) {
  1338. foreach ($parameters['conditions'] as $column => $value) {
  1339. $query->condition($column, $value);
  1340. }
  1341. }
  1342. // Build an ordered array of links using the query result object.
  1343. $links = array();
  1344. foreach ($query->execute() as $item) {
  1345. $links[] = $item;
  1346. }
  1347. $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : array());
  1348. $data['tree'] = menu_tree_data($links, $active_trail, $min_depth);
  1349. $data['node_links'] = array();
  1350. menu_tree_collect_node_links($data['tree'], $data['node_links']);
  1351. // Cache the data, if it is not already in the cache.
  1352. cache_set($tree_cid, $data, 'cache_menu');
  1353. $trees[$tree_cid] = $data;
  1354. }
  1355. return $trees[$tree_cid];
  1356. }
  1357. /**
  1358. * Collects node links from a given menu tree recursively.
  1359. *
  1360. * @param $tree
  1361. * The menu tree you wish to collect node links from.
  1362. * @param $node_links
  1363. * An array in which to store the collected node links.
  1364. */
  1365. function menu_tree_collect_node_links(&$tree, &$node_links) {
  1366. foreach ($tree as $key => $v) {
  1367. if ($tree[$key]['link']['router_path'] == 'node/%') {
  1368. $nid = substr($tree[$key]['link']['link_path'], 5);
  1369. if (is_numeric($nid)) {
  1370. $node_links[$nid][$tree[$key]['link']['mlid']] = &$tree[$key]['link'];
  1371. $tree[$key]['link']['access'] = FALSE;
  1372. }
  1373. }
  1374. if ($tree[$key]['below']) {
  1375. menu_tree_collect_node_links($tree[$key]['below'], $node_links);
  1376. }
  1377. }
  1378. }
  1379. /**
  1380. * Checks access and performs dynamic operations for each link in the tree.
  1381. *
  1382. * @param $tree
  1383. * The menu tree you wish to operate on.
  1384. * @param $node_links
  1385. * A collection of node link references generated from $tree by
  1386. * menu_tree_collect_node_links().
  1387. */
  1388. function menu_tree_check_access(&$tree, $node_links = array()) {
  1389. if ($node_links) {
  1390. $nids = array_keys($node_links);
  1391. $select = db_select('node', 'n');
  1392. $select->addField('n', 'nid');
  1393. $select->condition('n.status', 1);
  1394. $select->condition('n.nid', $nids, 'IN');
  1395. $select->addTag('node_access');
  1396. $nids = $select->execute()->fetchCol();
  1397. foreach ($nids as $nid) {
  1398. foreach ($node_links[$nid] as $mlid => $link) {
  1399. $node_links[$nid][$mlid]['access'] = TRUE;
  1400. }
  1401. }
  1402. }
  1403. _menu_tree_check_access($tree);
  1404. }
  1405. /**
  1406. * Sorts the menu tree and recursively checks access for each item.
  1407. */
  1408. function _menu_tree_check_access(&$tree) {
  1409. $new_tree = array();
  1410. foreach ($tree as $key => $v) {
  1411. $item = &$tree[$key]['link'];
  1412. _menu_link_translate($item);
  1413. if ($item['access'] || ($item['in_active_trail'] && strpos($item['href'], '%') !== FALSE)) {
  1414. if ($tree[$key]['below']) {
  1415. _menu_tree_check_access($tree[$key]['below']);
  1416. }
  1417. // The weights are made a uniform 5 digits by adding 50000 as an offset.
  1418. // After _menu_link_translate(), $item['title'] has the localized link title.
  1419. // Adding the mlid to the end of the index insures that it is unique.
  1420. $new_tree[(50000 + $item['weight']) . ' ' . $item['title'] . ' ' . $item['mlid']] = $tree[$key];
  1421. }
  1422. }
  1423. // Sort siblings in the tree based on the weights and localized titles.
  1424. ksort($new_tree);
  1425. $tree = $new_tree;
  1426. }
  1427. /**
  1428. * Sorts and returns the built data representing a menu tree.
  1429. *
  1430. * @param $links
  1431. * A flat array of menu links that are part of the menu. Each array element
  1432. * is an associative array of information about the menu link, containing the
  1433. * fields from the {menu_links} table, and optionally additional information
  1434. * from the {menu_router} table, if the menu item appears in both tables.
  1435. * This array must be ordered depth-first. See _menu_build_tree() for a sample
  1436. * query.
  1437. * @param $parents
  1438. * An array of the menu link ID values that are in the path from the current
  1439. * page to the root of the menu tree.
  1440. * @param $depth
  1441. * The minimum depth to include in the returned menu tree.
  1442. *
  1443. * @return
  1444. * An array of menu links in the form of a tree. Each item in the tree is an
  1445. * associative array containing:
  1446. * - link: The menu link item from $links, with additional element
  1447. * 'in_active_trail' (TRUE if the link ID was in $parents).
  1448. * - below: An array containing the sub-tree of this item, where each element
  1449. * is a tree item array with 'link' and 'below' elements. This array will be
  1450. * empty if the menu item has no items in its sub-tree having a depth
  1451. * greater than or equal to $depth.
  1452. */
  1453. function menu_tree_data(array $links, array $parents = array(), $depth = 1) {
  1454. // Reverse the array so we can use the more efficient array_pop() function.
  1455. $links = array_reverse($links);
  1456. return _menu_tree_data($links, $parents, $depth);
  1457. }
  1458. /**
  1459. * Builds the data representing a menu tree.
  1460. *
  1461. * The function is a bit complex because the rendering of a link depends on
  1462. * the next menu link.
  1463. */
  1464. function _menu_tree_data(&$links, $parents, $depth) {
  1465. $tree = array();
  1466. while ($item = array_pop($links)) {
  1467. // We need to determine if we're on the path to root so we can later build
  1468. // the correct active trail and breadcrumb.
  1469. $item['in_active_trail'] = in_array($item['mlid'], $parents);
  1470. // Add the current link to the tree.
  1471. $tree[$item['mlid']] = array(
  1472. 'link' => $item,
  1473. 'below' => array(),
  1474. );
  1475. // Look ahead to the next link, but leave it on the array so it's available
  1476. // to other recursive function calls if we return or build a sub-tree.
  1477. $next = end($links);
  1478. // Check whether the next link is the first in a new sub-tree.
  1479. if ($next && $next['depth'] > $depth) {
  1480. // Recursively call _menu_tree_data to build the sub-tree.
  1481. $tree[$item['mlid']]['below'] = _menu_tree_data($links, $parents, $next['depth']);
  1482. // Fetch next link after filling the sub-tree.
  1483. $next = end($links);
  1484. }
  1485. // Determine if we should exit the loop and return.
  1486. if (!$next || $next['depth'] < $depth) {
  1487. break;
  1488. }
  1489. }
  1490. return $tree;
  1491. }
  1492. /**
  1493. * Implements template_preprocess_HOOK() for theme_menu_tree().
  1494. */
  1495. function template_preprocess_menu_tree(&$variables) {
  1496. $variables['tree'] = $variables['tree']['#children'];
  1497. }
  1498. /**
  1499. * Returns HTML for a wrapper for a menu sub-tree.
  1500. *
  1501. * @param $variables
  1502. * An associative array containing:
  1503. * - tree: An HTML string containing the tree's items.
  1504. *
  1505. * @see template_preprocess_menu_tree()
  1506. * @ingroup themeable
  1507. */
  1508. function theme_menu_tree($variables) {
  1509. return '<ul class="menu">' . $variables['tree'] . '</ul>';
  1510. }
  1511. /**
  1512. * Returns HTML for a menu link and submenu.
  1513. *
  1514. * @param $variables
  1515. * An associative array containing:
  1516. * - element: Structured array data for a menu link.
  1517. *
  1518. * @ingroup themeable
  1519. */
  1520. function theme_menu_link(array $variables) {
  1521. $element = $variables['element'];
  1522. $sub_menu = '';
  1523. if ($element['#below']) {
  1524. $sub_menu = drupal_render($element['#below']);
  1525. }
  1526. $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  1527. return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
  1528. }
  1529. /**
  1530. * Returns HTML for a single local task link.
  1531. *
  1532. * @param $variables
  1533. * An associative array containing:
  1534. * - element: A render element containing:
  1535. * - #link: A menu link array with 'title', 'href', and 'localized_options'
  1536. * keys.
  1537. * - #active: A boolean indicating whether the local task is active.
  1538. *
  1539. * @ingroup themeable
  1540. */
  1541. function theme_menu_local_task($variables) {
  1542. $link = $variables['element']['#link'];
  1543. $link_text = $link['title'];
  1544. if (!empty($variables['element']['#active'])) {
  1545. // Add text to indicate active tab for non-visual users.
  1546. $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';
  1547. // If the link does not contain HTML already, check_plain() it now.
  1548. // After we set 'html'=TRUE the link will not be sanitized by l().
  1549. if (empty($link['localized_options']['html'])) {
  1550. $link['title'] = check_plain($link['title']);
  1551. }
  1552. $link['localized_options']['html'] = TRUE;
  1553. $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  1554. }
  1555. return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
  1556. }
  1557. /**
  1558. * Returns HTML for a single local action link.
  1559. *
  1560. * @param $variables
  1561. * An associative array containing:
  1562. * - element: A render element containing:
  1563. * - #link: A menu link array with 'title', 'href', and 'localized_options'
  1564. * keys.
  1565. *
  1566. * @ingroup themeable
  1567. */
  1568. function theme_menu_local_action($variables) {
  1569. $link = $variables['element']['#link'];
  1570. $output = '<li>';
  1571. if (isset($link['href'])) {
  1572. $output .= l($link['title'], $link['href'], isset($link['localized_options']) ? $link['localized_options'] : array());
  1573. }
  1574. elseif (!empty($link['localized_options']['html'])) {
  1575. $output .= $link['title'];
  1576. }
  1577. else {
  1578. $output .= check_plain($link['title']);
  1579. }
  1580. $output .= "</li>\n";
  1581. return $output;
  1582. }
  1583. /**
  1584. * Generates elements for the $arg array in the help hook.
  1585. */
  1586. function drupal_help_arg($arg = array()) {
  1587. // Note - the number of empty elements should be > MENU_MAX_PARTS.
  1588. return $arg + array('', '', '', '', '', '', '', '', '', '', '', '');
  1589. }
  1590. /**
  1591. * Returns the help associated with the active menu item.
  1592. */
  1593. function menu_get_active_help() {
  1594. $output = '';
  1595. $router_path = menu_tab_root_path();
  1596. // We will always have a path unless we are on a 403 or 404.
  1597. if (!$router_path) {
  1598. return '';
  1599. }
  1600. $arg = drupal_help_arg(arg(NULL));
  1601. foreach (module_implements('help') as $module) {
  1602. $function = $module . '_help';
  1603. // Lookup help for this path.
  1604. if ($help = $function($router_path, $arg)) {
  1605. $output .= $help . "\n";
  1606. }
  1607. }
  1608. return $output;
  1609. }
  1610. /**
  1611. * Gets the custom theme for the current page, if there is one.
  1612. *
  1613. * @param $initialize
  1614. * This parameter should only be used internally; it is set to TRUE in order
  1615. * to force the custom theme to be initialized for the current page request.
  1616. *
  1617. * @return
  1618. * The machine-readable name of the custom theme, if there is one.
  1619. *
  1620. * @see menu_set_custom_theme()
  1621. */
  1622. function menu_get_custom_theme($initialize = FALSE) {
  1623. $custom_theme = &drupal_static(__FUNCTION__);
  1624. // Skip this if the site is offline or being installed or updated, since the
  1625. // menu system may not be correctly initialized then.
  1626. if ($initialize && !_menu_site_is_offline(TRUE) && (!defined('MAINTENANCE_MODE') || (MAINTENANCE_MODE != 'update' && MAINTENANCE_MODE != 'install'))) {
  1627. // First allow modules to dynamically set a custom theme for the current
  1628. // page. Since we can only have one, the last module to return a valid
  1629. // theme takes precedence.
  1630. $custom_themes = array_filter(module_invoke_all('custom_theme'), 'drupal_theme_access');
  1631. if (!empty($custom_themes)) {
  1632. $custom_theme = array_pop($custom_themes);
  1633. }
  1634. // If there is a theme callback function for the current page, execute it.
  1635. // If this returns a valid theme, it will override any theme that was set
  1636. // by a hook_custom_theme() implementation above.
  1637. $router_item = menu_get_item();
  1638. if (!empty($router_item['access']) && !empty($router_item['theme_callback']) && function_exists($router_item['theme_callback'])) {
  1639. $theme_name = call_user_func_array($router_item['theme_callback'], $router_item['theme_arguments']);
  1640. if (drupal_theme_access($theme_name)) {
  1641. $custom_theme = $theme_name;
  1642. }
  1643. }
  1644. }
  1645. return $custom_theme;
  1646. }
  1647. /**
  1648. * Sets a custom theme for the current page, if there is one.
  1649. */
  1650. function menu_set_custom_theme() {
  1651. menu_get_custom_theme(TRUE);
  1652. }
  1653. /**
  1654. * Build a list of named menus.
  1655. */
  1656. function menu_get_names() {
  1657. $names = &drupal_static(__FUNCTION__);
  1658. if (empty($names)) {
  1659. $names = db_select('menu_links')
  1660. ->distinct()
  1661. ->fields('menu_links', array('menu_name'))
  1662. ->orderBy('menu_name')
  1663. ->execute()->fetchCol();
  1664. }
  1665. return $names;
  1666. }
  1667. /**
  1668. * Returns an array containing the names of system-defined (default) menus.
  1669. */
  1670. function menu_list_system_menus() {
  1671. return array(
  1672. 'navigation' => 'Navigation',
  1673. 'management' => 'Management',
  1674. 'user-menu' => 'User menu',
  1675. 'main-menu' => 'Main menu',
  1676. );
  1677. }
  1678. /**
  1679. * Returns an array of links to be rendered as the Main menu.
  1680. */
  1681. function menu_main_menu() {
  1682. return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'));
  1683. }
  1684. /**
  1685. * Returns an array of links to be rendered as the Secondary links.
  1686. */
  1687. function menu_secondary_menu() {
  1688. // If the secondary menu source is set as the primary menu, we display the
  1689. // second level of the primary menu.
  1690. if (variable_get('menu_secondary_links_source', 'user-menu') == variable_get('menu_main_links_source', 'main-menu')) {
  1691. return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'), 1);
  1692. }
  1693. else {
  1694. return menu_navigation_links(variable_get('menu_secondary_links_source', 'user-menu'), 0);
  1695. }
  1696. }
  1697. /**
  1698. * Returns an array of links for a navigation menu.
  1699. *
  1700. * @param $menu_name
  1701. * The name of the menu.
  1702. * @param $level
  1703. * Optional, the depth of the menu to be returned.
  1704. *
  1705. * @return
  1706. * An array of links of the specified menu and level.
  1707. */
  1708. function menu_navigation_links($menu_name, $level = 0) {
  1709. // Don't even bother querying the menu table if no menu is specified.
  1710. if (empty($menu_name)) {
  1711. return array();
  1712. }
  1713. // Get the menu hierarchy for the current page.
  1714. $tree = menu_tree_page_data($menu_name, $level + 1);
  1715. // Go down the active trail until the right level is reached.
  1716. while ($level-- > 0 && $tree) {
  1717. // Loop through the current level's items until we find one that is in trail.
  1718. while ($item = array_shift($tree)) {
  1719. if ($item['link']['in_active_trail']) {
  1720. // If the item is in the active trail, we continue in the subtree.
  1721. $tree = empty($item['below']) ? array() : $item['below'];
  1722. break;
  1723. }
  1724. }
  1725. }
  1726. // Create a single level of links.
  1727. $router_item = menu_get_item();
  1728. $links = array();
  1729. foreach ($tree as $item) {
  1730. if (!$item['link']['hidden']) {
  1731. $class = '';
  1732. $l = $item['link']['localized_options'];
  1733. $l['href'] = $item['link']['href'];
  1734. $l['title'] = $item['link']['title'];
  1735. if ($item['link']['in_active_trail']) {
  1736. $class = ' active-trail';
  1737. $l['attributes']['class'][] = 'active-trail';
  1738. }
  1739. // Normally, l() compares the href of every link with $_GET['q'] and sets
  1740. // the active class accordingly. But local tasks do not appear in menu
  1741. // trees, so if the current path is a local task, and this link is its
  1742. // tab root, then we have to set the class manually.
  1743. if ($item['link']['href'] == $router_item['tab_root_href'] && $item['link']['href'] != $_GET['q']) {
  1744. $l['attributes']['class'][] = 'active';
  1745. }
  1746. // Keyed with the unique mlid to generate classes in theme_links().
  1747. $links['menu-' . $item['link']['mlid'] . $class] = $l;
  1748. }
  1749. }
  1750. return $links;
  1751. }
  1752. /**
  1753. * Collects the local tasks (tabs), action links, and the root path.
  1754. *
  1755. * @param $level
  1756. * The level of tasks you ask for. Primary tasks are 0, secondary are 1.
  1757. *
  1758. * @return
  1759. * An array containing
  1760. * - tabs: Local tasks for the requested level:
  1761. * - count: The number of local tasks.
  1762. * - output: The themed output of local tasks.
  1763. * - actions: Action links for the requested level:
  1764. * - count: The number of action links.
  1765. * - output: The themed output of action links.
  1766. * - root_path: The router path for the current page. If the current page is
  1767. * a default local task, then this corresponds to the parent tab.
  1768. */
  1769. function menu_local_tasks($level = 0) {
  1770. $data = &drupal_static(__FUNCTION__);
  1771. $root_path = &drupal_static(__FUNCTION__ . ':root_path', '');
  1772. $empty = array(
  1773. 'tabs' => array('count' => 0, 'output' => array()),
  1774. 'actions' => array('count' => 0, 'output' => array()),
  1775. 'root_path' => &$root_path,
  1776. );
  1777. if (!isset($data)) {
  1778. $data = array();
  1779. // Set defaults in case there are no actions or tabs.
  1780. $actions = $empty['actions'];
  1781. $tabs = array();
  1782. $router_item = menu_get_item();
  1783. // If this router item points to its parent, start from the parents to
  1784. // compute tabs and actions.
  1785. if ($router_item && ($router_item['type'] & MENU_LINKS_TO_PARENT)) {
  1786. $router_item = menu_get_item($router_item['tab_parent_href']);
  1787. }
  1788. // If we failed to fetch a router item or the current user doesn't have
  1789. // access to it, don't bother computing the tabs.
  1790. if (!$router_item || !$router_item['access']) {
  1791. return $empty;
  1792. }
  1793. // Get all tabs (also known as local tasks) and the root page.
  1794. $cid = 'local_tasks:' . $router_item['tab_root'];
  1795. if ($cache = cache_get($cid, 'cache_menu')) {
  1796. $result = $cache->data;
  1797. }
  1798. else {
  1799. $result = db_select('menu_router', NULL, array('fetch' => PDO::FETCH_ASSOC))
  1800. ->fields('menu_router')
  1801. ->condition('tab_root', $router_item['tab_root'])
  1802. ->condition('context', MENU_CONTEXT_INLINE, '<>')
  1803. ->orderBy('weight')
  1804. ->orderBy('title')
  1805. ->execute()
  1806. ->fetchAll();
  1807. cache_set($cid, $result, 'cache_menu');
  1808. }
  1809. $map = $router_item['original_map'];
  1810. $children = array();
  1811. $tasks = array();
  1812. $root_path = $router_item['path'];
  1813. foreach ($result as $item) {
  1814. _menu_translate($item, $map, TRUE);
  1815. if ($item['tab_parent']) {
  1816. // All tabs, but not the root page.
  1817. $children[$item['tab_parent']][$item['path']] = $item;
  1818. }
  1819. // Store the translated item for later use.
  1820. $tasks[$item['path']] = $item;
  1821. }
  1822. // Find all tabs below the current path.
  1823. $path = $router_item['path'];
  1824. // Tab parenting may skip levels, so the number of parts in the path may not
  1825. // equal the depth. Thus we use the $depth counter (offset by 1000 for ksort).
  1826. $depth = 1001;
  1827. $actions['count'] = 0;
  1828. $actions['output'] = array();
  1829. while (isset($children[$path])) {
  1830. $tabs_current = array();
  1831. $actions_current = array();
  1832. $next_path = '';
  1833. $tab_count = 0;
  1834. $action_count = 0;
  1835. foreach ($children[$path] as $item) {
  1836. // Local tasks can be normal items too, so bitmask with
  1837. // MENU_IS_LOCAL_TASK before checking.
  1838. if (!($item['type'] & MENU_IS_LOCAL_TASK)) {
  1839. // This item is not a tab, skip it.
  1840. continue;
  1841. }
  1842. if ($item['access']) {
  1843. $link = $item;
  1844. // The default task is always active. As tabs can be normal items
  1845. // too, so bitmask with MENU_LINKS_TO_PARENT before checking.
  1846. if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
  1847. // Find the first parent which is not a default local task or action.
  1848. for ($p = $item['tab_parent']; ($tasks[$p]['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT; $p = $tasks[$p]['tab_parent']);
  1849. // Use the path of the parent instead.
  1850. $link['href'] = $tasks[$p]['href'];
  1851. // Mark the link as active, if the current path happens to be the
  1852. // path of the default local task itself (i.e., instead of its
  1853. // tab_parent_href or tab_root_href). Normally, links for default
  1854. // local tasks link to their parent, but the path of default local
  1855. // tasks can still be accessed directly, in which case this link
  1856. // would not be marked as active, since l() only compares the href
  1857. // with $_GET['q'].
  1858. if ($link['href'] != $_GET['q']) {
  1859. $link['localized_options']['attributes']['class'][] = 'active';
  1860. }
  1861. $tabs_current[] = array(
  1862. '#theme' => 'menu_local_task',
  1863. '#link' => $link,
  1864. '#active' => TRUE,
  1865. );
  1866. $next_path = $item['path'];
  1867. $tab_count++;
  1868. }
  1869. else {
  1870. // Actions can be normal items too, so bitmask with
  1871. // MENU_IS_LOCAL_ACTION before checking.
  1872. if (($item['type'] & MENU_IS_LOCAL_ACTION) == MENU_IS_LOCAL_ACTION) {
  1873. // The item is an action, display it as such.
  1874. $actions_current[] = array(
  1875. '#theme' => 'menu_local_action',
  1876. '#link' => $link,
  1877. );
  1878. $action_count++;
  1879. }
  1880. else {
  1881. // Otherwise, it's a normal tab.
  1882. $tabs_current[] = array(
  1883. '#theme' => 'menu_local_task',
  1884. '#link' => $link,
  1885. );
  1886. $tab_count++;
  1887. }
  1888. }
  1889. }
  1890. }
  1891. $path = $next_path;
  1892. $tabs[$depth]['count'] = $tab_count;
  1893. $tabs[$depth]['output'] = $tabs_current;
  1894. $actions['count'] += $action_count;
  1895. $actions['output'] = array_merge($actions['output'], $actions_current);
  1896. $depth++;
  1897. }
  1898. $data['actions'] = $actions;
  1899. // Find all tabs at the same level or above the current one.
  1900. $parent = $router_item['tab_parent'];
  1901. $path = $router_item['path'];
  1902. $current = $router_item;
  1903. $depth = 1000;
  1904. while (isset($children[$parent])) {
  1905. $tabs_current = array();
  1906. $next_path = '';
  1907. $next_parent = '';
  1908. $count = 0;
  1909. foreach ($children[$parent] as $item) {
  1910. // Skip local actions.
  1911. if ($item['type'] & MENU_IS_LOCAL_ACTION) {
  1912. continue;
  1913. }
  1914. if ($item['access']) {
  1915. $count++;
  1916. $link = $item;
  1917. // Local tasks can be normal items too, so bitmask with
  1918. // MENU_LINKS_TO_PARENT before checking.
  1919. if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
  1920. // Find the first parent which is not a default local task.
  1921. for ($p = $item['tab_parent']; ($tasks[$p]['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT; $p = $tasks[$p]['tab_parent']);
  1922. // Use the path of the parent instead.
  1923. $link['href'] = $tasks[$p]['href'];
  1924. if ($item['path'] == $router_item['path']) {
  1925. $root_path = $tasks[$p]['path'];
  1926. }
  1927. }
  1928. // We check for the active tab.
  1929. if ($item['path'] == $path) {
  1930. // Mark the link as active, if the current path is a (second-level)
  1931. // local task of a default local task. Since this default local task
  1932. // links to its parent, l() will not mark it as active, as it only
  1933. // compares the link's href to $_GET['q'].
  1934. if ($link['href'] != $_GET['q']) {
  1935. $link['localized_options']['attributes']['class'][] = 'active';
  1936. }
  1937. $tabs_current[] = array(
  1938. '#theme' => 'menu_local_task',
  1939. '#link' => $link,
  1940. '#active' => TRUE,
  1941. );
  1942. $next_path = $item['tab_parent'];
  1943. if (isset($tasks[$next_path])) {
  1944. $next_parent = $tasks[$next_path]['tab_parent'];
  1945. }
  1946. }
  1947. else {
  1948. $tabs_current[] = array(
  1949. '#theme' => 'menu_local_task',
  1950. '#link' => $link,
  1951. );
  1952. }
  1953. }
  1954. }
  1955. $path = $next_path;
  1956. $parent = $next_parent;
  1957. $tabs[$depth]['count'] = $count;
  1958. $tabs[$depth]['output'] = $tabs_current;
  1959. $depth--;
  1960. }
  1961. // Sort by depth.
  1962. ksort($tabs);
  1963. // Remove the depth, we are interested only in their relative placement.
  1964. $tabs = array_values($tabs);
  1965. $data['tabs'] = $tabs;
  1966. // Allow modules to alter local tasks or dynamically append further tasks.
  1967. drupal_alter('menu_local_tasks', $data, $router_item, $root_path);
  1968. }
  1969. if (isset($data['tabs'][$level])) {
  1970. return array(
  1971. 'tabs' => $data['tabs'][$level],
  1972. 'actions' => $data['actions'],
  1973. 'root_path' => $root_path,
  1974. );
  1975. }
  1976. // @todo If there are no tabs, then there still can be actions; for example,
  1977. // when added via hook_menu_local_tasks_alter().
  1978. elseif (!empty($data['actions']['output'])) {
  1979. return array('actions' => $data['actions']) + $empty;
  1980. }
  1981. return $empty;
  1982. }
  1983. /**
  1984. * Retrieves contextual links for a path based on registered local tasks.
  1985. *
  1986. * This leverages the menu system to retrieve the first layer of registered
  1987. * local tasks for a given system path. All local tasks of the tab type
  1988. * MENU_CONTEXT_INLINE are taken into account.
  1989. *
  1990. * For example, when considering the following registered local tasks:
  1991. * - node/%node/view (default local task) with no 'context' defined
  1992. * - node/%node/edit with context: MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE
  1993. * - node/%node/revisions with context: MENU_CONTEXT_PAGE
  1994. * - node/%node/report-as-spam with context: MENU_CONTEXT_INLINE
  1995. *
  1996. * If the path "node/123" is passed to this function, then it will return the
  1997. * links for 'edit' and 'report-as-spam'.
  1998. *
  1999. * @param $module
  2000. * The name of the implementing module. This is used to prefix the key for
  2001. * each contextual link, which is transformed into a CSS class during
  2002. * rendering by theme_links(). For example, if $module is 'block' and the
  2003. * retrieved local task path argument is 'edit', then the resulting CSS class
  2004. * will be 'block-edit'.
  2005. * @param $parent_path
  2006. * The static menu router path of the object to retrieve local tasks for, for
  2007. * example 'node' or 'admin/structure/block/manage'.
  2008. * @param $args
  2009. * A list of dynamic path arguments to append to $parent_path to form the
  2010. * fully-qualified menu router path; for example, array(123) for a certain
  2011. * node or array('system', 'navigation') for a certain block.
  2012. *
  2013. * @return
  2014. * A list of menu router items that are local tasks for the passed-in path.
  2015. *
  2016. * @see contextual_links_preprocess()
  2017. * @see hook_menu()
  2018. */
  2019. function menu_contextual_links($module, $parent_path, $args) {
  2020. static $path_empty = array();
  2021. $links = array();
  2022. // Performance: In case a previous invocation for the same parent path did not
  2023. // return any links, we immediately return here.
  2024. if (isset($path_empty[$parent_path]) && strpos($parent_path, '%') !== FALSE) {
  2025. return $links;
  2026. }
  2027. // Construct the item-specific parent path.
  2028. $path = $parent_path . '/' . implode('/', $args);
  2029. // Get the router item for the given parent link path.
  2030. $router_item = menu_get_item($path);
  2031. if (!$router_item || !$router_item['access']) {
  2032. $path_empty[$parent_path] = TRUE;
  2033. return $links;
  2034. }
  2035. $data = &drupal_static(__FUNCTION__, array());
  2036. $root_path = $router_item['path'];
  2037. // Performance: For a single, normalized path (such as 'node/%') we only query
  2038. // available tasks once per request.
  2039. if (!isset($data[$root_path])) {
  2040. // Get all contextual links that are direct children of the router item and
  2041. // not of the tab type 'view'.
  2042. $data[$root_path] = db_select('menu_router', 'm')
  2043. ->fields('m')
  2044. ->condition('tab_parent', $router_item['tab_root'])
  2045. ->condition('context', MENU_CONTEXT_NONE, '<>')
  2046. ->condition('context', MENU_CONTEXT_PAGE, '<>')
  2047. ->orderBy('weight')
  2048. ->orderBy('title')
  2049. ->execute()
  2050. ->fetchAllAssoc('path', PDO::FETCH_ASSOC);
  2051. }
  2052. $parent_length = drupal_strlen($root_path) + 1;
  2053. $map = $router_item['original_map'];
  2054. foreach ($data[$root_path] as $item) {
  2055. // Extract the actual "task" string from the path argument.
  2056. $key = drupal_substr($item['path'], $parent_length);
  2057. // Denormalize and translate the contextual link.
  2058. _menu_translate($item, $map, TRUE);
  2059. if (!$item['access']) {
  2060. continue;
  2061. }
  2062. // All contextual links are keyed by the actual "task" path argument,
  2063. // prefixed with the name of the implementing module.
  2064. $links[$module . '-' . $key] = $item;
  2065. }
  2066. // Allow modules to alter contextual links.
  2067. drupal_alter('menu_contextual_links', $links, $router_item, $root_path);
  2068. // Performance: If the current user does not have access to any links for this
  2069. // router path and no other module added further links, we assign FALSE here
  2070. // to skip the entire process the next time the same router path is requested.
  2071. if (empty($links)) {
  2072. $path_empty[$parent_path] = TRUE;
  2073. }
  2074. return $links;
  2075. }
  2076. /**
  2077. * Returns the rendered local tasks at the top level.
  2078. */
  2079. function menu_primary_local_tasks() {
  2080. $links = menu_local_tasks(0);
  2081. // Do not display single tabs.
  2082. return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
  2083. }
  2084. /**
  2085. * Returns the rendered local tasks at the second level.
  2086. */
  2087. function menu_secondary_local_tasks() {
  2088. $links = menu_local_tasks(1);
  2089. // Do not display single tabs.
  2090. return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
  2091. }
  2092. /**
  2093. * Returns the rendered local actions at the current level.
  2094. */
  2095. function menu_local_actions() {
  2096. $links = menu_local_tasks();
  2097. return $links['actions']['output'];
  2098. }
  2099. /**
  2100. * Returns the router path, or the path for a default local task's parent.
  2101. */
  2102. function menu_tab_root_path() {
  2103. $links = menu_local_tasks();
  2104. return $links['root_path'];
  2105. }
  2106. /**
  2107. * Returns a renderable element for the primary and secondary tabs.
  2108. */
  2109. function menu_local_tabs() {
  2110. return array(
  2111. '#theme' => 'menu_local_tasks',
  2112. '#primary' => menu_primary_local_tasks(),
  2113. '#secondary' => menu_secondary_local_tasks(),
  2114. );
  2115. }
  2116. /**
  2117. * Returns HTML for primary and secondary local tasks.
  2118. *
  2119. * @param $variables
  2120. * An associative array containing:
  2121. * - primary: (optional) An array of local tasks (tabs).
  2122. * - secondary: (optional) An array of local tasks (tabs).
  2123. *
  2124. * @ingroup themeable
  2125. * @see menu_local_tasks()
  2126. */
  2127. function theme_menu_local_tasks(&$variables) {
  2128. $output = '';
  2129. if (!empty($variables['primary'])) {
  2130. $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>';
  2131. $variables['primary']['#prefix'] .= '<ul class="tabs primary">';
  2132. $variables['primary']['#suffix'] = '</ul>';
  2133. $output .= drupal_render($variables['primary']);
  2134. }
  2135. if (!empty($variables['secondary'])) {
  2136. $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>';
  2137. $variables['secondary']['#prefix'] .= '<ul class="tabs secondary">';
  2138. $variables['secondary']['#suffix'] = '</ul>';
  2139. $output .= drupal_render($variables['secondary']);
  2140. }
  2141. return $output;
  2142. }
  2143. /**
  2144. * Sets (or gets) the active menu for the current page.
  2145. *
  2146. * The active menu for the page determines the active trail.
  2147. *
  2148. * @return
  2149. * An array of menu machine names, in order of preference. The
  2150. * 'menu_default_active_menus' variable may be used to assert a menu order
  2151. * different from the order of creation, or to prevent a particular menu from
  2152. * being used at all in the active trail.
  2153. * E.g., $conf['menu_default_active_menus'] = array('navigation', 'main-menu')
  2154. */
  2155. function menu_set_active_menu_names($menu_names = NULL) {
  2156. $active = &drupal_static(__FUNCTION__);
  2157. if (isset($menu_names) && is_array($menu_names)) {
  2158. $active = $menu_names;
  2159. }
  2160. elseif (!isset($active)) {
  2161. $active = variable_get('menu_default_active_menus', array_keys(menu_list_system_menus()));
  2162. }
  2163. return $active;
  2164. }
  2165. /**
  2166. * Gets the active menu for the current page.
  2167. */
  2168. function menu_get_active_menu_names() {
  2169. return menu_set_active_menu_names();
  2170. }
  2171. /**
  2172. * Sets the active path, which determines which page is loaded.
  2173. *
  2174. * Note that this may not have the desired effect unless invoked very early
  2175. * in the page load, such as during hook_boot(), or unless you call
  2176. * menu_execute_active_handler() to generate your page output.
  2177. *
  2178. * @param $path
  2179. * A Drupal path - not a path alias.
  2180. */
  2181. function menu_set_active_item($path) {
  2182. $_GET['q'] = $path;
  2183. // Since the active item has changed, the active menu trail may also be out
  2184. // of date.
  2185. drupal_static_reset('menu_set_active_trail');
  2186. }
  2187. /**
  2188. * Sets the active trail (path to the menu tree root) of the current page.
  2189. *
  2190. * Any trail set by this function will only be used for functionality that calls
  2191. * menu_get_active_trail(). Drupal core only uses trails set here for
  2192. * breadcrumbs and the page title and not for menu trees or page content.
  2193. * Additionally, breadcrumbs set by drupal_set_breadcrumb() will override any
  2194. * trail set here.
  2195. *
  2196. * To affect the trail used by menu trees, use menu_tree_set_path(). To affect
  2197. * the page content, use menu_set_active_item() instead.
  2198. *
  2199. * @param $new_trail
  2200. * Menu trail to set; the value is saved in a static variable and can be
  2201. * retrieved by menu_get_active_trail(). The format of this array should be
  2202. * the same as the return value of menu_get_active_trail().
  2203. *
  2204. * @return
  2205. * The active trail. See menu_get_active_trail() for details.
  2206. */
  2207. function menu_set_active_trail($new_trail = NULL) {
  2208. $trail = &drupal_static(__FUNCTION__);
  2209. if (isset($new_trail)) {
  2210. $trail = $new_trail;
  2211. }
  2212. elseif (!isset($trail)) {
  2213. $trail = array();
  2214. $trail[] = array(
  2215. 'title' => t('Home'),
  2216. 'href' => '<front>',
  2217. 'link_path' => '',
  2218. 'localized_options' => array(),
  2219. 'type' => 0,
  2220. );
  2221. // Try to retrieve a menu link corresponding to the current path. If more
  2222. // than one exists, the link from the most preferred menu is returned.
  2223. $preferred_link = menu_link_get_preferred();
  2224. $current_item = menu_get_item();
  2225. // There is a link for the current path.
  2226. if ($preferred_link) {
  2227. // Pass TRUE for $only_active_trail to make menu_tree_page_data() build
  2228. // a stripped down menu tree containing the active trail only, in case
  2229. // the given menu has not been built in this request yet.
  2230. $tree = menu_tree_page_data($preferred_link['menu_name'], NULL, TRUE);
  2231. list($key, $curr) = each($tree);
  2232. }
  2233. // There is no link for the current path.
  2234. else {
  2235. $preferred_link = $current_item;
  2236. $curr = FALSE;
  2237. }
  2238. while ($curr) {
  2239. $link = $curr['link'];
  2240. if ($link['in_active_trail']) {
  2241. // Add the link to the trail, unless it links to its parent.
  2242. if (!($link['type'] & MENU_LINKS_TO_PARENT)) {
  2243. // The menu tree for the active trail may contain additional links
  2244. // that have not been translated yet, since they contain dynamic
  2245. // argument placeholders (%). Such links are not contained in regular
  2246. // menu trees, and have only been loaded for the additional
  2247. // translation that happens here, so as to be able to display them in
  2248. // the breadcumb for the current page.
  2249. // @see _menu_tree_check_access()
  2250. // @see _menu_link_translate()
  2251. if (strpos($link['href'], '%') !== FALSE) {
  2252. _menu_link_translate($link, TRUE);
  2253. }
  2254. if ($link['access']) {
  2255. $trail[] = $link;
  2256. }
  2257. }
  2258. $tree = $curr['below'] ? $curr['below'] : array();
  2259. }
  2260. list($key, $curr) = each($tree);
  2261. }
  2262. // Make sure the current page is in the trail to build the page title, by
  2263. // appending either the preferred link or the menu router item for the
  2264. // current page. Exclude it if we are on the front page.
  2265. $last = end($trail);
  2266. if ($preferred_link && $last['href'] != $preferred_link['href'] && !drupal_is_front_page()) {
  2267. $trail[] = $preferred_link;
  2268. }
  2269. }
  2270. return $trail;
  2271. }
  2272. /**
  2273. * Looks up the preferred menu link for a given system path.
  2274. *
  2275. * @param $path
  2276. * The path; for example, 'node/5'. The function will find the corresponding
  2277. * menu link ('node/5' if it exists, or fallback to 'node/%').
  2278. * @param $selected_menu
  2279. * The name of a menu used to restrict the search for a preferred menu link.
  2280. * If not specified, all the menus returned by menu_get_active_menu_names()
  2281. * will be used.
  2282. *
  2283. * @return
  2284. * A fully translated menu link, or FALSE if no matching menu link was
  2285. * found. The most specific menu link ('node/5' preferred over 'node/%') in
  2286. * the most preferred menu (as defined by menu_get_active_menu_names()) is
  2287. * returned.
  2288. */
  2289. function menu_link_get_preferred($path = NULL, $selected_menu = NULL) {
  2290. $preferred_links = &drupal_static(__FUNCTION__);
  2291. if (!isset($path)) {
  2292. $path = $_GET['q'];
  2293. }
  2294. if (empty($selected_menu)) {
  2295. // Use an illegal menu name as the key for the preferred menu link.
  2296. $selected_menu = MENU_PREFERRED_LINK;
  2297. }
  2298. if (!isset($preferred_links[$path])) {
  2299. // Look for the correct menu link by building a list of candidate paths,
  2300. // which are ordered by priority (translated hrefs are preferred over
  2301. // untranslated paths). Afterwards, the most relevant path is picked from
  2302. // the menus, ordered by menu preference.
  2303. $item = menu_get_item($path);
  2304. $path_candidates = array();
  2305. // 1. The current item href.
  2306. $path_candidates[$item['href']] = $item['href'];
  2307. // 2. The tab root href of the current item (if any).
  2308. if ($item['tab_parent'] && ($tab_root = menu_get_item($item['tab_root_href']))) {
  2309. $path_candidates[$tab_root['href']] = $tab_root['href'];
  2310. }
  2311. // 3. The current item path (with wildcards).
  2312. $path_candidates[$item['path']] = $item['path'];
  2313. // 4. The tab root path of the current item (if any).
  2314. if (!empty($tab_root)) {
  2315. $path_candidates[$tab_root['path']] = $tab_root['path'];
  2316. }
  2317. // Retrieve a list of menu names, ordered by preference.
  2318. $menu_names = menu_get_active_menu_names();
  2319. // Put the selected menu at the front of the list.
  2320. array_unshift($menu_names, $selected_menu);
  2321. $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
  2322. $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
  2323. $query->fields('ml');
  2324. // Weight must be taken from {menu_links}, not {menu_router}.
  2325. $query->addField('ml', 'weight', 'link_weight');
  2326. $query->fields('m');
  2327. $query->condition('ml.link_path', $path_candidates, 'IN');
  2328. $query->addTag('preferred_menu_links');
  2329. // Sort candidates by link path and menu name.
  2330. $candidates = array();
  2331. foreach ($query->execute() as $candidate) {
  2332. $candidate['weight'] = $candidate['link_weight'];
  2333. $candidates[$candidate['link_path']][$candidate['menu_name']] = $candidate;
  2334. // Add any menus not already in the menu name search list.
  2335. if (!in_array($candidate['menu_name'], $menu_names)) {
  2336. $menu_names[] = $candidate['menu_name'];
  2337. }
  2338. }
  2339. // Store the most specific link for each menu. Also save the most specific
  2340. // link of the most preferred menu in $preferred_link.
  2341. foreach ($path_candidates as $link_path) {
  2342. if (isset($candidates[$link_path])) {
  2343. foreach ($menu_names as $menu_name) {
  2344. if (empty($preferred_links[$path][$menu_name]) && isset($candidates[$link_path][$menu_name])) {
  2345. $candidate_item = $candidates[$link_path][$menu_name];
  2346. $map = explode('/', $path);
  2347. _menu_translate($candidate_item, $map);
  2348. if ($candidate_item['access']) {
  2349. $preferred_links[$path][$menu_name] = $candidate_item;
  2350. if (empty($preferred_links[$path][MENU_PREFERRED_LINK])) {
  2351. // Store the most specific link.
  2352. $preferred_links[$path][MENU_PREFERRED_LINK] = $candidate_item;
  2353. }
  2354. }
  2355. }
  2356. }
  2357. }
  2358. }
  2359. }
  2360. return isset($preferred_links[$path][$selected_menu]) ? $preferred_links[$path][$selected_menu] : FALSE;
  2361. }
  2362. /**
  2363. * Gets the active trail (path to root menu root) of the current page.
  2364. *
  2365. * If a trail is supplied to menu_set_active_trail(), that value is returned. If
  2366. * a trail is not supplied to menu_set_active_trail(), the path to the current
  2367. * page is calculated and returned. The calculated trail is also saved as a
  2368. * static value for use by subsequent calls to menu_get_active_trail().
  2369. *
  2370. * @return
  2371. * Path to menu root of the current page, as an array of menu link items,
  2372. * starting with the site's home page. Each link item is an associative array
  2373. * with the following components:
  2374. * - title: Title of the item.
  2375. * - href: Drupal path of the item.
  2376. * - localized_options: Options for passing into the l() function.
  2377. * - type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to
  2378. * indicate it's not really in the menu (used for the home page item).
  2379. */
  2380. function menu_get_active_trail() {
  2381. return menu_set_active_trail();
  2382. }
  2383. /**
  2384. * Gets the breadcrumb for the current page, as determined by the active trail.
  2385. *
  2386. * @see menu_set_active_trail()
  2387. */
  2388. function menu_get_active_breadcrumb() {
  2389. $breadcrumb = array();
  2390. // No breadcrumb for the front page.
  2391. if (drupal_is_front_page()) {
  2392. return $breadcrumb;
  2393. }
  2394. $item = menu_get_item();
  2395. if (!empty($item['access'])) {
  2396. $active_trail = menu_get_active_trail();
  2397. // Allow modules to alter the breadcrumb, if possible, as that is much
  2398. // faster than rebuilding an entirely new active trail.
  2399. drupal_alter('menu_breadcrumb', $active_trail, $item);
  2400. // Don't show a link to the current page in the breadcrumb trail.
  2401. $end = end($active_trail);
  2402. if ($item['href'] == $end['href']) {
  2403. array_pop($active_trail);
  2404. }
  2405. // Remove the tab root (parent) if the current path links to its parent.
  2406. // Normally, the tab root link is included in the breadcrumb, as soon as we
  2407. // are on a local task or any other child link. However, if we are on a
  2408. // default local task (e.g., node/%/view), then we do not want the tab root
  2409. // link (e.g., node/%) to appear, as it would be identical to the current
  2410. // page. Since this behavior also needs to work recursively (i.e., on
  2411. // default local tasks of default local tasks), and since the last non-task
  2412. // link in the trail is used as page title (see menu_get_active_title()),
  2413. // this condition cannot be cleanly integrated into menu_get_active_trail().
  2414. // menu_get_active_trail() already skips all links that link to their parent
  2415. // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
  2416. // itself, we always remove the last link in the trail, if the current
  2417. // router item links to its parent.
  2418. if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
  2419. array_pop($active_trail);
  2420. }
  2421. foreach ($active_trail as $parent) {
  2422. $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
  2423. }
  2424. }
  2425. return $breadcrumb;
  2426. }
  2427. /**
  2428. * Gets the title of the current page, as determined by the active trail.
  2429. */
  2430. function menu_get_active_title() {
  2431. $active_trail = menu_get_active_trail();
  2432. foreach (array_reverse($active_trail) as $item) {
  2433. if (!(bool) ($item['type'] & MENU_IS_LOCAL_TASK)) {
  2434. return $item['title'];
  2435. }
  2436. }
  2437. }
  2438. /**
  2439. * Gets a translated, access-checked menu link that is ready for rendering.
  2440. *
  2441. * This function should never be called from within node_load() or any other
  2442. * function used as a menu object load function since an infinite recursion may
  2443. * occur.
  2444. *
  2445. * @param $mlid
  2446. * The mlid of the menu item.
  2447. *
  2448. * @return
  2449. * A menu link, with $item['access'] filled and link translated for
  2450. * rendering.
  2451. */
  2452. function menu_link_load($mlid) {
  2453. if (is_numeric($mlid)) {
  2454. $query = db_select('menu_links', 'ml');
  2455. $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
  2456. $query->fields('ml');
  2457. // Weight should be taken from {menu_links}, not {menu_router}.
  2458. $query->addField('ml', 'weight', 'link_weight');
  2459. $query->fields('m');
  2460. $query->condition('ml.mlid', $mlid);
  2461. if ($item = $query->execute()->fetchAssoc()) {
  2462. $item['weight'] = $item['link_weight'];
  2463. _menu_link_translate($item);
  2464. return $item;
  2465. }
  2466. }
  2467. return FALSE;
  2468. }
  2469. /**
  2470. * Clears the cached cached data for a single named menu.
  2471. */
  2472. function menu_cache_clear($menu_name = 'navigation') {
  2473. $cache_cleared = &drupal_static(__FUNCTION__, array());
  2474. if (empty($cache_cleared[$menu_name])) {
  2475. cache_clear_all('links:' . $menu_name . ':', 'cache_menu', TRUE);
  2476. $cache_cleared[$menu_name] = 1;
  2477. }
  2478. elseif ($cache_cleared[$menu_name] == 1) {
  2479. drupal_register_shutdown_function('cache_clear_all', 'links:' . $menu_name . ':', 'cache_menu', TRUE);
  2480. $cache_cleared[$menu_name] = 2;
  2481. }
  2482. // Also clear the menu system static caches.
  2483. menu_reset_static_cache();
  2484. }
  2485. /**
  2486. * Clears all cached menu data.
  2487. *
  2488. * This should be called any time broad changes
  2489. * might have been made to the router items or menu links.
  2490. */
  2491. function menu_cache_clear_all() {
  2492. cache_clear_all('*', 'cache_menu', TRUE);
  2493. menu_reset_static_cache();
  2494. }
  2495. /**
  2496. * Resets the menu system static cache.
  2497. */
  2498. function menu_reset_static_cache() {
  2499. drupal_static_reset('_menu_build_tree');
  2500. drupal_static_reset('menu_tree');
  2501. drupal_static_reset('menu_tree_all_data');
  2502. drupal_static_reset('menu_tree_page_data');
  2503. drupal_static_reset('menu_load_all');
  2504. drupal_static_reset('menu_link_get_preferred');
  2505. }
  2506. /**
  2507. * Checks whether a menu_rebuild() is necessary.
  2508. */
  2509. function _menu_check_rebuild() {
  2510. // To absolutely ensure that the menu rebuild is required, re-load the
  2511. // variables in case they were set by another process.
  2512. $variables = variable_initialize();
  2513. if (empty($variables['menu_rebuild_needed']) && !empty($variables['menu_masks'])) {
  2514. unset($GLOBALS['conf']['menu_rebuild_needed']);
  2515. $GLOBALS['conf']['menu_masks'] = $variables['menu_masks'];
  2516. return FALSE;
  2517. }
  2518. return TRUE;
  2519. }
  2520. /**
  2521. * Populates the database tables used by various menu functions.
  2522. *
  2523. * This function will clear and populate the {menu_router} table, add entries
  2524. * to {menu_links} for new router items, and then remove stale items from
  2525. * {menu_links}. If called from update.php or install.php, it will also
  2526. * schedule a call to itself on the first real page load from
  2527. * menu_execute_active_handler(), because the maintenance page environment
  2528. * is different and leaves stale data in the menu tables.
  2529. *
  2530. * @return
  2531. * TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
  2532. * in parallel and the current thread just waited for completion.
  2533. */
  2534. function menu_rebuild() {
  2535. if (!lock_acquire('menu_rebuild')) {
  2536. // Wait for another request that is already doing this work.
  2537. // We choose to block here since otherwise the router item may not
  2538. // be available in menu_execute_active_handler() resulting in a 404.
  2539. lock_wait('menu_rebuild');
  2540. if (_menu_check_rebuild()) {
  2541. // If we get here and menu_masks was not set, then it is possible a menu
  2542. // is being reloaded, or that the process rebuilding the menu was unable
  2543. // to complete successfully. A missing menu_masks variable could result
  2544. // in a 404, so re-run the function.
  2545. return menu_rebuild();
  2546. }
  2547. return FALSE;
  2548. }
  2549. $transaction = db_transaction();
  2550. try {
  2551. list($menu, $masks) = menu_router_build();
  2552. _menu_router_save($menu, $masks);
  2553. _menu_navigation_links_rebuild($menu);
  2554. // Clear the menu, page and block caches.
  2555. menu_cache_clear_all();
  2556. _menu_clear_page_cache();
  2557. if (defined('MAINTENANCE_MODE')) {
  2558. variable_set('menu_rebuild_needed', TRUE);
  2559. }
  2560. else {
  2561. variable_del('menu_rebuild_needed');
  2562. }
  2563. }
  2564. catch (Exception $e) {
  2565. $transaction->rollback();
  2566. watchdog_exception('menu', $e);
  2567. }
  2568. // Explicitly commit the transaction now; this ensures that the database
  2569. // operations during the menu rebuild are committed before the lock is made
  2570. // available again, since locks may not always reside in the same database
  2571. // connection. The lock is acquired outside of the transaction so should also
  2572. // be released outside of it.
  2573. unset($transaction);
  2574. lock_release('menu_rebuild');
  2575. return TRUE;
  2576. }
  2577. /**
  2578. * Collects and alters the menu definitions.
  2579. */
  2580. function menu_router_build() {
  2581. // We need to manually call each module so that we can know which module
  2582. // a given item came from.
  2583. $callbacks = array();
  2584. foreach (module_implements('menu') as $module) {
  2585. $router_items = call_user_func($module . '_menu');
  2586. if (isset($router_items) && is_array($router_items)) {
  2587. foreach (array_keys($router_items) as $path) {
  2588. $router_items[$path]['module'] = $module;
  2589. }
  2590. $callbacks = array_merge($callbacks, $router_items);
  2591. }
  2592. }
  2593. // Alter the menu as defined in modules, keys are like user/%user.
  2594. drupal_alter('menu', $callbacks);
  2595. list($menu, $masks) = _menu_router_build($callbacks);
  2596. _menu_router_cache($menu);
  2597. return array($menu, $masks);
  2598. }
  2599. /**
  2600. * Stores the menu router if we have it in memory.
  2601. */
  2602. function _menu_router_cache($new_menu = NULL) {
  2603. $menu = &drupal_static(__FUNCTION__);
  2604. if (isset($new_menu)) {
  2605. $menu = $new_menu;
  2606. }
  2607. return $menu;
  2608. }
  2609. /**
  2610. * Gets the menu router.
  2611. */
  2612. function menu_get_router() {
  2613. // Check first if we have it in memory already.
  2614. $menu = _menu_router_cache();
  2615. if (empty($menu)) {
  2616. list($menu, $masks) = menu_router_build();
  2617. }
  2618. return $menu;
  2619. }
  2620. /**
  2621. * Builds a link from a router item.
  2622. */
  2623. function _menu_link_build($item) {
  2624. // Suggested items are disabled by default.
  2625. if ($item['type'] == MENU_SUGGESTED_ITEM) {
  2626. $item['hidden'] = 1;
  2627. }
  2628. // Hide all items that are not visible in the tree.
  2629. elseif (!($item['type'] & MENU_VISIBLE_IN_TREE)) {
  2630. $item['hidden'] = -1;
  2631. }
  2632. // Note, we set this as 'system', so that we can be sure to distinguish all
  2633. // the menu links generated automatically from entries in {menu_router}.
  2634. $item['module'] = 'system';
  2635. $item += array(
  2636. 'menu_name' => 'navigation',
  2637. 'link_title' => $item['title'],
  2638. 'link_path' => $item['path'],
  2639. 'hidden' => 0,
  2640. 'options' => empty($item['description']) ? array() : array('attributes' => array('title' => $item['description'])),
  2641. );
  2642. return $item;
  2643. }
  2644. /**
  2645. * Builds menu links for the items in the menu router.
  2646. */
  2647. function _menu_navigation_links_rebuild($menu) {
  2648. // Add normal and suggested items as links.
  2649. $menu_links = array();
  2650. foreach ($menu as $path => $item) {
  2651. if ($item['_visible']) {
  2652. $menu_links[$path] = $item;
  2653. $sort[$path] = $item['_number_parts'];
  2654. }
  2655. }
  2656. if ($menu_links) {
  2657. // Keep an array of processed menu links, to allow menu_link_save() to
  2658. // check this for parents instead of querying the database.
  2659. $parent_candidates = array();
  2660. // Make sure no child comes before its parent.
  2661. array_multisort($sort, SORT_NUMERIC, $menu_links);
  2662. foreach ($menu_links as $key => $item) {
  2663. $existing_item = db_select('menu_links')
  2664. ->fields('menu_links')
  2665. ->condition('link_path', $item['path'])
  2666. ->condition('module', 'system')
  2667. ->execute()->fetchAssoc();
  2668. if ($existing_item) {
  2669. $item['mlid'] = $existing_item['mlid'];
  2670. // A change in hook_menu may move the link to a different menu
  2671. if (empty($item['menu_name']) || ($item['menu_name'] == $existing_item['menu_name'])) {
  2672. $item['menu_name'] = $existing_item['menu_name'];
  2673. $item['plid'] = $existing_item['plid'];
  2674. }
  2675. else {
  2676. // It moved to a new menu. Let menu_link_save() try to find a new
  2677. // parent based on the path.
  2678. unset($item['plid']);
  2679. }
  2680. $item['has_children'] = $existing_item['has_children'];
  2681. $item['updated'] = $existing_item['updated'];
  2682. }
  2683. if ($existing_item && $existing_item['customized']) {
  2684. $parent_candidates[$existing_item['mlid']] = $existing_item;
  2685. }
  2686. else {
  2687. $item = _menu_link_build($item);
  2688. menu_link_save($item, $existing_item, $parent_candidates);
  2689. $parent_candidates[$item['mlid']] = $item;
  2690. unset($menu_links[$key]);
  2691. }
  2692. }
  2693. }
  2694. $paths = array_keys($menu);
  2695. // Updated and customized items whose router paths are gone need new ones.
  2696. $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
  2697. ->fields('menu_links', array(
  2698. 'link_path',
  2699. 'mlid',
  2700. 'router_path',
  2701. 'updated',
  2702. ))
  2703. ->condition(db_or()
  2704. ->condition('updated', 1)
  2705. ->condition(db_and()
  2706. ->condition('router_path', $paths, 'NOT IN')
  2707. ->condition('external', 0)
  2708. ->condition('customized', 1)
  2709. )
  2710. )
  2711. ->execute();
  2712. foreach ($result as $item) {
  2713. $router_path = _menu_find_router_path($item['link_path']);
  2714. if (!empty($router_path) && ($router_path != $item['router_path'] || $item['updated'])) {
  2715. // If the router path and the link path matches, it's surely a working
  2716. // item, so we clear the updated flag.
  2717. $updated = $item['updated'] && $router_path != $item['link_path'];
  2718. db_update('menu_links')
  2719. ->fields(array(
  2720. 'router_path' => $router_path,
  2721. 'updated' => (int) $updated,
  2722. ))
  2723. ->condition('mlid', $item['mlid'])
  2724. ->execute();
  2725. }
  2726. }
  2727. // Find any item whose router path does not exist any more.
  2728. $result = db_select('menu_links')
  2729. ->fields('menu_links')
  2730. ->condition('router_path', $paths, 'NOT IN')
  2731. ->condition('external', 0)
  2732. ->condition('updated', 0)
  2733. ->condition('customized', 0)
  2734. ->orderBy('depth', 'DESC')
  2735. ->execute();
  2736. // Remove all such items. Starting from those with the greatest depth will
  2737. // minimize the amount of re-parenting done by menu_link_delete().
  2738. foreach ($result as $item) {
  2739. _menu_delete_item($item, TRUE);
  2740. }
  2741. }
  2742. /**
  2743. * Clones an array of menu links.
  2744. *
  2745. * @param $links
  2746. * An array of menu links to clone.
  2747. * @param $menu_name
  2748. * (optional) The name of a menu that the links will be cloned for. If not
  2749. * set, the cloned links will be in the same menu as the original set of
  2750. * links that were passed in.
  2751. *
  2752. * @return
  2753. * An array of menu links with the same properties as the passed-in array,
  2754. * but with the link identifiers removed so that a new link will be created
  2755. * when any of them is passed in to menu_link_save().
  2756. *
  2757. * @see menu_link_save()
  2758. */
  2759. function menu_links_clone($links, $menu_name = NULL) {
  2760. foreach ($links as &$link) {
  2761. unset($link['mlid']);
  2762. unset($link['plid']);
  2763. if (isset($menu_name)) {
  2764. $link['menu_name'] = $menu_name;
  2765. }
  2766. }
  2767. return $links;
  2768. }
  2769. /**
  2770. * Returns an array containing all links for a menu.
  2771. *
  2772. * @param $menu_name
  2773. * The name of the menu whose links should be returned.
  2774. *
  2775. * @return
  2776. * An array of menu links.
  2777. */
  2778. function menu_load_links($menu_name) {
  2779. $links = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC))
  2780. ->fields('ml')
  2781. ->condition('ml.menu_name', $menu_name)
  2782. // Order by weight so as to be helpful for menus that are only one level
  2783. // deep.
  2784. ->orderBy('weight')
  2785. ->execute()
  2786. ->fetchAll();
  2787. foreach ($links as &$link) {
  2788. $link['options'] = unserialize($link['options']);
  2789. }
  2790. return $links;
  2791. }
  2792. /**
  2793. * Deletes all links for a menu.
  2794. *
  2795. * @param $menu_name
  2796. * The name of the menu whose links will be deleted.
  2797. */
  2798. function menu_delete_links($menu_name) {
  2799. $links = menu_load_links($menu_name);
  2800. foreach ($links as $link) {
  2801. // To speed up the deletion process, we reset some link properties that
  2802. // would trigger re-parenting logic in _menu_delete_item() and
  2803. // _menu_update_parental_status().
  2804. $link['has_children'] = FALSE;
  2805. $link['plid'] = 0;
  2806. _menu_delete_item($link);
  2807. }
  2808. }
  2809. /**
  2810. * Delete one or several menu links.
  2811. *
  2812. * @param $mlid
  2813. * A valid menu link mlid or NULL. If NULL, $path is used.
  2814. * @param $path
  2815. * The path to the menu items to be deleted. $mlid must be NULL.
  2816. */
  2817. function menu_link_delete($mlid, $path = NULL) {
  2818. if (isset($mlid)) {
  2819. _menu_delete_item(db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc());
  2820. }
  2821. else {
  2822. $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $path));
  2823. foreach ($result as $link) {
  2824. _menu_delete_item($link);
  2825. }
  2826. }
  2827. }
  2828. /**
  2829. * Deletes a single menu link.
  2830. *
  2831. * @param $item
  2832. * Item to be deleted.
  2833. * @param $force
  2834. * Forces deletion. Internal use only, setting to TRUE is discouraged.
  2835. *
  2836. * @see menu_link_delete()
  2837. */
  2838. function _menu_delete_item($item, $force = FALSE) {
  2839. $item = is_object($item) ? get_object_vars($item) : $item;
  2840. if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) {
  2841. // Children get re-attached to the item's parent.
  2842. if ($item['has_children']) {
  2843. $result = db_query("SELECT mlid FROM {menu_links} WHERE plid = :plid", array(':plid' => $item['mlid']));
  2844. foreach ($result as $m) {
  2845. $child = menu_link_load($m->mlid);
  2846. $child['plid'] = $item['plid'];
  2847. menu_link_save($child);
  2848. }
  2849. }
  2850. // Notify modules we are deleting the item.
  2851. module_invoke_all('menu_link_delete', $item);
  2852. db_delete('menu_links')->condition('mlid', $item['mlid'])->execute();
  2853. // Update the has_children status of the parent.
  2854. _menu_update_parental_status($item);
  2855. menu_cache_clear($item['menu_name']);
  2856. _menu_clear_page_cache();
  2857. }
  2858. }
  2859. /**
  2860. * Saves a menu link.
  2861. *
  2862. * After calling this function, rebuild the menu cache using
  2863. * menu_cache_clear_all().
  2864. *
  2865. * @param $item
  2866. * An associative array representing a menu link item, with elements:
  2867. * - link_path: (required) The path of the menu item, which should be
  2868. * normalized first by calling drupal_get_normal_path() on it.
  2869. * - link_title: (required) Title to appear in menu for the link.
  2870. * - menu_name: (optional) The machine name of the menu for the link.
  2871. * Defaults to 'navigation'.
  2872. * - weight: (optional) Integer to determine position in menu. Default is 0.
  2873. * - expanded: (optional) Boolean that determines if the item is expanded.
  2874. * - options: (optional) An array of options, see l() for more.
  2875. * - mlid: (optional) Menu link identifier, the primary integer key for each
  2876. * menu link. Can be set to an existing value, or to 0 or NULL
  2877. * to insert a new link.
  2878. * - plid: (optional) The mlid of the parent.
  2879. * - router_path: (optional) The path of the relevant router item.
  2880. * @param $existing_item
  2881. * Optional, the current record from the {menu_links} table as an array.
  2882. * @param $parent_candidates
  2883. * Optional array of menu links keyed by mlid. Used by
  2884. * _menu_navigation_links_rebuild() only.
  2885. *
  2886. * @return
  2887. * The mlid of the saved menu link, or FALSE if the menu link could not be
  2888. * saved.
  2889. */
  2890. function menu_link_save(&$item, $existing_item = array(), $parent_candidates = array()) {
  2891. drupal_alter('menu_link', $item);
  2892. // This is the easiest way to handle the unique internal path '<front>',
  2893. // since a path marked as external does not need to match a router path.
  2894. $item['external'] = (url_is_external($item['link_path']) || $item['link_path'] == '<front>') ? 1 : 0;
  2895. // Load defaults.
  2896. $item += array(
  2897. 'menu_name' => 'navigation',
  2898. 'weight' => 0,
  2899. 'link_title' => '',
  2900. 'hidden' => 0,
  2901. 'has_children' => 0,
  2902. 'expanded' => 0,
  2903. 'options' => array(),
  2904. 'module' => 'menu',
  2905. 'customized' => 0,
  2906. 'updated' => 0,
  2907. );
  2908. if (isset($item['mlid'])) {
  2909. if (!$existing_item) {
  2910. $existing_item = db_query('SELECT * FROM {menu_links} WHERE mlid = :mlid', array('mlid' => $item['mlid']))->fetchAssoc();
  2911. }
  2912. if ($existing_item) {
  2913. $existing_item['options'] = unserialize($existing_item['options']);
  2914. }
  2915. }
  2916. else {
  2917. $existing_item = FALSE;
  2918. }
  2919. // Try to find a parent link. If found, assign it and derive its menu.
  2920. $parent = _menu_link_find_parent($item, $parent_candidates);
  2921. if (!empty($parent['mlid'])) {
  2922. $item['plid'] = $parent['mlid'];
  2923. $item['menu_name'] = $parent['menu_name'];
  2924. }
  2925. // If no corresponding parent link was found, move the link to the top-level.
  2926. else {
  2927. $item['plid'] = 0;
  2928. }
  2929. $menu_name = $item['menu_name'];
  2930. if (!$existing_item) {
  2931. $item['mlid'] = db_insert('menu_links')
  2932. ->fields(array(
  2933. 'menu_name' => $item['menu_name'],
  2934. 'plid' => $item['plid'],
  2935. 'link_path' => $item['link_path'],
  2936. 'hidden' => $item['hidden'],
  2937. 'external' => $item['external'],
  2938. 'has_children' => $item['has_children'],
  2939. 'expanded' => $item['expanded'],
  2940. 'weight' => $item['weight'],
  2941. 'module' => $item['module'],
  2942. 'link_title' => $item['link_title'],
  2943. 'options' => serialize($item['options']),
  2944. 'customized' => $item['customized'],
  2945. 'updated' => $item['updated'],
  2946. ))
  2947. ->execute();
  2948. }
  2949. // Directly fill parents for top-level links.
  2950. if ($item['plid'] == 0) {
  2951. $item['p1'] = $item['mlid'];
  2952. for ($i = 2; $i <= MENU_MAX_DEPTH; $i++) {
  2953. $item["p$i"] = 0;
  2954. }
  2955. $item['depth'] = 1;
  2956. }
  2957. // Otherwise, ensure that this link's depth is not beyond the maximum depth
  2958. // and fill parents based on the parent link.
  2959. else {
  2960. if ($item['has_children'] && $existing_item) {
  2961. $limit = MENU_MAX_DEPTH - menu_link_children_relative_depth($existing_item) - 1;
  2962. }
  2963. else {
  2964. $limit = MENU_MAX_DEPTH - 1;
  2965. }
  2966. if ($parent['depth'] > $limit) {
  2967. return FALSE;
  2968. }
  2969. $item['depth'] = $parent['depth'] + 1;
  2970. _menu_link_parents_set($item, $parent);
  2971. }
  2972. // Need to check both plid and menu_name, since plid can be 0 in any menu.
  2973. if ($existing_item && ($item['plid'] != $existing_item['plid'] || $menu_name != $existing_item['menu_name'])) {
  2974. _menu_link_move_children($item, $existing_item);
  2975. }
  2976. // Find the router_path.
  2977. if (empty($item['router_path']) || !$existing_item || ($existing_item['link_path'] != $item['link_path'])) {
  2978. if ($item['external']) {
  2979. $item['router_path'] = '';
  2980. }
  2981. else {
  2982. // Find the router path which will serve this path.
  2983. $item['parts'] = explode('/', $item['link_path'], MENU_MAX_PARTS);
  2984. $item['router_path'] = _menu_find_router_path($item['link_path']);
  2985. }
  2986. }
  2987. // If every value in $existing_item is the same in the $item, there is no
  2988. // reason to run the update queries or clear the caches. We use
  2989. // array_intersect_key() with the $item as the first parameter because
  2990. // $item may have additional keys left over from building a router entry.
  2991. // The intersect removes the extra keys, allowing a meaningful comparison.
  2992. if (!$existing_item || (array_intersect_key($item, $existing_item) != $existing_item)) {
  2993. db_update('menu_links')
  2994. ->fields(array(
  2995. 'menu_name' => $item['menu_name'],
  2996. 'plid' => $item['plid'],
  2997. 'link_path' => $item['link_path'],
  2998. 'router_path' => $item['router_path'],
  2999. 'hidden' => $item['hidden'],
  3000. 'external' => $item['external'],
  3001. 'has_children' => $item['has_children'],
  3002. 'expanded' => $item['expanded'],
  3003. 'weight' => $item['weight'],
  3004. 'depth' => $item['depth'],
  3005. 'p1' => $item['p1'],
  3006. 'p2' => $item['p2'],
  3007. 'p3' => $item['p3'],
  3008. 'p4' => $item['p4'],
  3009. 'p5' => $item['p5'],
  3010. 'p6' => $item['p6'],
  3011. 'p7' => $item['p7'],
  3012. 'p8' => $item['p8'],
  3013. 'p9' => $item['p9'],
  3014. 'module' => $item['module'],
  3015. 'link_title' => $item['link_title'],
  3016. 'options' => serialize($item['options']),
  3017. 'customized' => $item['customized'],
  3018. ))
  3019. ->condition('mlid', $item['mlid'])
  3020. ->execute();
  3021. // Check the has_children status of the parent.
  3022. _menu_update_parental_status($item);
  3023. menu_cache_clear($menu_name);
  3024. if ($existing_item && $menu_name != $existing_item['menu_name']) {
  3025. menu_cache_clear($existing_item['menu_name']);
  3026. }
  3027. // Notify modules we have acted on a menu item.
  3028. $hook = 'menu_link_insert';
  3029. if ($existing_item) {
  3030. $hook = 'menu_link_update';
  3031. }
  3032. module_invoke_all($hook, $item);
  3033. // Now clear the cache.
  3034. _menu_clear_page_cache();
  3035. }
  3036. return $item['mlid'];
  3037. }
  3038. /**
  3039. * Finds a possible parent for a given menu link.
  3040. *
  3041. * Because the parent of a given link might not exist anymore in the database,
  3042. * we apply a set of heuristics to determine a proper parent:
  3043. *
  3044. * - use the passed parent link if specified and existing.
  3045. * - else, use the first existing link down the previous link hierarchy
  3046. * - else, for system menu links (derived from hook_menu()), reparent
  3047. * based on the path hierarchy.
  3048. *
  3049. * @param $menu_link
  3050. * A menu link.
  3051. * @param $parent_candidates
  3052. * An array of menu links keyed by mlid.
  3053. *
  3054. * @return
  3055. * A menu link structure of the possible parent or FALSE if no valid parent
  3056. * has been found.
  3057. */
  3058. function _menu_link_find_parent($menu_link, $parent_candidates = array()) {
  3059. $parent = FALSE;
  3060. // This item is explicitely top-level, skip the rest of the parenting.
  3061. if (isset($menu_link['plid']) && empty($menu_link['plid'])) {
  3062. return $parent;
  3063. }
  3064. // If we have a parent link ID, try to use that.
  3065. $candidates = array();
  3066. if (isset($menu_link['plid'])) {
  3067. $candidates[] = $menu_link['plid'];
  3068. }
  3069. // Else, if we have a link hierarchy try to find a valid parent in there.
  3070. if (!empty($menu_link['depth']) && $menu_link['depth'] > 1) {
  3071. for ($depth = $menu_link['depth'] - 1; $depth >= 1; $depth--) {
  3072. $candidates[] = $menu_link['p' . $depth];
  3073. }
  3074. }
  3075. foreach ($candidates as $mlid) {
  3076. if (isset($parent_candidates[$mlid])) {
  3077. $parent = $parent_candidates[$mlid];
  3078. }
  3079. else {
  3080. $parent = db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc();
  3081. }
  3082. if ($parent) {
  3083. return $parent;
  3084. }
  3085. }
  3086. // If everything else failed, try to derive the parent from the path
  3087. // hierarchy. This only makes sense for links derived from menu router
  3088. // items (ie. from hook_menu()).
  3089. if ($menu_link['module'] == 'system') {
  3090. $query = db_select('menu_links');
  3091. $query->condition('module', 'system');
  3092. // We always respect the link's 'menu_name'; inheritance for router items is
  3093. // ensured in _menu_router_build().
  3094. $query->condition('menu_name', $menu_link['menu_name']);
  3095. // Find the parent - it must be unique.
  3096. $parent_path = $menu_link['link_path'];
  3097. do {
  3098. $parent = FALSE;
  3099. $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));
  3100. $new_query = clone $query;
  3101. $new_query->condition('link_path', $parent_path);
  3102. // Only valid if we get a unique result.
  3103. if ($new_query->countQuery()->execute()->fetchField() == 1) {
  3104. $parent = $new_query->fields('menu_links')->execute()->fetchAssoc();
  3105. }
  3106. } while ($parent === FALSE && $parent_path);
  3107. }
  3108. return $parent;
  3109. }
  3110. /**
  3111. * Clears the page and block caches at most twice per page load.
  3112. */
  3113. function _menu_clear_page_cache() {
  3114. $cache_cleared = &drupal_static(__FUNCTION__, 0);
  3115. // Clear the page and block caches, but at most twice, including at
  3116. // the end of the page load when there are multiple links saved or deleted.
  3117. if ($cache_cleared == 0) {
  3118. cache_clear_all();
  3119. // Keep track of which menus have expanded items.
  3120. _menu_set_expanded_menus();
  3121. $cache_cleared = 1;
  3122. }
  3123. elseif ($cache_cleared == 1) {
  3124. drupal_register_shutdown_function('cache_clear_all');
  3125. // Keep track of which menus have expanded items.
  3126. drupal_register_shutdown_function('_menu_set_expanded_menus');
  3127. $cache_cleared = 2;
  3128. }
  3129. }
  3130. /**
  3131. * Updates a list of menus with expanded items.
  3132. */
  3133. function _menu_set_expanded_menus() {
  3134. $names = db_query("SELECT menu_name FROM {menu_links} WHERE expanded <> 0 GROUP BY menu_name")->fetchCol();
  3135. variable_set('menu_expanded', $names);
  3136. }
  3137. /**
  3138. * Finds the router path which will serve this path.
  3139. *
  3140. * @param $link_path
  3141. * The path for we are looking up its router path.
  3142. *
  3143. * @return
  3144. * A path from $menu keys or empty if $link_path points to a nonexisting
  3145. * place.
  3146. */
  3147. function _menu_find_router_path($link_path) {
  3148. // $menu will only have data during a menu rebuild.
  3149. $menu = _menu_router_cache();
  3150. $router_path = $link_path;
  3151. $parts = explode('/', $link_path, MENU_MAX_PARTS);
  3152. $ancestors = menu_get_ancestors($parts);
  3153. if (empty($menu)) {
  3154. // Not during a menu rebuild, so look up in the database.
  3155. $router_path = (string) db_select('menu_router')
  3156. ->fields('menu_router', array('path'))
  3157. ->condition('path', $ancestors, 'IN')
  3158. ->orderBy('fit', 'DESC')
  3159. ->range(0, 1)
  3160. ->execute()->fetchField();
  3161. }
  3162. elseif (!isset($menu[$router_path])) {
  3163. // Add an empty router path as a fallback.
  3164. $ancestors[] = '';
  3165. foreach ($ancestors as $key => $router_path) {
  3166. if (isset($menu[$router_path])) {
  3167. // Exit the loop leaving $router_path as the first match.
  3168. break;
  3169. }
  3170. }
  3171. // If we did not find the path, $router_path will be the empty string
  3172. // at the end of $ancestors.
  3173. }
  3174. return $router_path;
  3175. }
  3176. /**
  3177. * Inserts, updates, or deletes an uncustomized menu link related to a module.
  3178. *
  3179. * @param $module
  3180. * The name of the module.
  3181. * @param $op
  3182. * Operation to perform: insert, update or delete.
  3183. * @param $link_path
  3184. * The path this link points to.
  3185. * @param $link_title
  3186. * Title of the link to insert or new title to update the link to.
  3187. * Unused for delete.
  3188. *
  3189. * @return
  3190. * The insert op returns the mlid of the new item. Others op return NULL.
  3191. */
  3192. function menu_link_maintain($module, $op, $link_path, $link_title) {
  3193. switch ($op) {
  3194. case 'insert':
  3195. $menu_link = array(
  3196. 'link_title' => $link_title,
  3197. 'link_path' => $link_path,
  3198. 'module' => $module,
  3199. );
  3200. return menu_link_save($menu_link);
  3201. break;
  3202. case 'update':
  3203. $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path AND module = :module AND customized = 0", array(':link_path' => $link_path, ':module' => $module))->fetchAll(PDO::FETCH_ASSOC);
  3204. foreach ($result as $link) {
  3205. $link['link_title'] = $link_title;
  3206. $link['options'] = unserialize($link['options']);
  3207. menu_link_save($link);
  3208. }
  3209. break;
  3210. case 'delete':
  3211. menu_link_delete(NULL, $link_path);
  3212. break;
  3213. }
  3214. }
  3215. /**
  3216. * Finds the depth of an item's children relative to its depth.
  3217. *
  3218. * For example, if the item has a depth of 2, and the maximum of any child in
  3219. * the menu link tree is 5, the relative depth is 3.
  3220. *
  3221. * @param $item
  3222. * An array representing a menu link item.
  3223. *
  3224. * @return
  3225. * The relative depth, or zero.
  3226. *
  3227. */
  3228. function menu_link_children_relative_depth($item) {
  3229. $query = db_select('menu_links');
  3230. $query->addField('menu_links', 'depth');
  3231. $query->condition('menu_name', $item['menu_name']);
  3232. $query->orderBy('depth', 'DESC');
  3233. $query->range(0, 1);
  3234. $i = 1;
  3235. $p = 'p1';
  3236. while ($i <= MENU_MAX_DEPTH && $item[$p]) {
  3237. $query->condition($p, $item[$p]);
  3238. $p = 'p' . ++$i;
  3239. }
  3240. $max_depth = $query->execute()->fetchField();
  3241. return ($max_depth > $item['depth']) ? $max_depth - $item['depth'] : 0;
  3242. }
  3243. /**
  3244. * Updates the children of a menu link that is being moved.
  3245. *
  3246. * The menu name, parents (p1 - p6), and depth are updated for all children of
  3247. * the link, and the has_children status of the previous parent is updated.
  3248. */
  3249. function _menu_link_move_children($item, $existing_item) {
  3250. $query = db_update('menu_links');
  3251. $query->fields(array('menu_name' => $item['menu_name']));
  3252. $p = 'p1';
  3253. $expressions = array();
  3254. for ($i = 1; $i <= $item['depth']; $p = 'p' . ++$i) {
  3255. $expressions[] = array($p, ":p_$i", array(":p_$i" => $item[$p]));
  3256. }
  3257. $j = $existing_item['depth'] + 1;
  3258. while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
  3259. $expressions[] = array('p' . $i++, 'p' . $j++, array());
  3260. }
  3261. while ($i <= MENU_MAX_DEPTH) {
  3262. $expressions[] = array('p' . $i++, 0, array());
  3263. }
  3264. $shift = $item['depth'] - $existing_item['depth'];
  3265. if ($shift > 0) {
  3266. // The order of expressions must be reversed so the new values don't
  3267. // overwrite the old ones before they can be used because "Single-table
  3268. // UPDATE assignments are generally evaluated from left to right"
  3269. // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
  3270. $expressions = array_reverse($expressions);
  3271. }
  3272. foreach ($expressions as $expression) {
  3273. $query->expression($expression[0], $expression[1], $expression[2]);
  3274. }
  3275. $query->expression('depth', 'depth + :depth', array(':depth' => $shift));
  3276. $query->condition('menu_name', $existing_item['menu_name']);
  3277. $p = 'p1';
  3278. for ($i = 1; $i <= MENU_MAX_DEPTH && $existing_item[$p]; $p = 'p' . ++$i) {
  3279. $query->condition($p, $existing_item[$p]);
  3280. }
  3281. $query->execute();
  3282. // Check the has_children status of the parent, while excluding this item.
  3283. _menu_update_parental_status($existing_item, TRUE);
  3284. }
  3285. /**
  3286. * Checks and updates the 'has_children' status for the parent of a link.
  3287. */
  3288. function _menu_update_parental_status($item, $exclude = FALSE) {
  3289. // If plid == 0, there is nothing to update.
  3290. if ($item['plid']) {
  3291. // Check if at least one visible child exists in the table.
  3292. $query = db_select('menu_links');
  3293. $query->addField('menu_links', 'mlid');
  3294. $query->condition('menu_name', $item['menu_name']);
  3295. $query->condition('hidden', 0);
  3296. $query->condition('plid', $item['plid']);
  3297. $query->range(0, 1);
  3298. if ($exclude) {
  3299. $query->condition('mlid', $item['mlid'], '<>');
  3300. }
  3301. $parent_has_children = ((bool) $query->execute()->fetchField()) ? 1 : 0;
  3302. db_update('menu_links')
  3303. ->fields(array('has_children' => $parent_has_children))
  3304. ->condition('mlid', $item['plid'])
  3305. ->execute();
  3306. }
  3307. }
  3308. /**
  3309. * Sets the p1 through p9 values for a menu link being saved.
  3310. */
  3311. function _menu_link_parents_set(&$item, $parent) {
  3312. $i = 1;
  3313. while ($i < $item['depth']) {
  3314. $p = 'p' . $i++;
  3315. $item[$p] = $parent[$p];
  3316. }
  3317. $p = 'p' . $i++;
  3318. // The parent (p1 - p9) corresponding to the depth always equals the mlid.
  3319. $item[$p] = $item['mlid'];
  3320. while ($i <= MENU_MAX_DEPTH) {
  3321. $p = 'p' . $i++;
  3322. $item[$p] = 0;
  3323. }
  3324. }
  3325. /**
  3326. * Builds the router table based on the data from hook_menu().
  3327. */
  3328. function _menu_router_build($callbacks) {
  3329. // First pass: separate callbacks from paths, making paths ready for
  3330. // matching. Calculate fitness, and fill some default values.
  3331. $menu = array();
  3332. $masks = array();
  3333. foreach ($callbacks as $path => $item) {
  3334. $load_functions = array();
  3335. $to_arg_functions = array();
  3336. $fit = 0;
  3337. $move = FALSE;
  3338. $parts = explode('/', $path, MENU_MAX_PARTS);
  3339. $number_parts = count($parts);
  3340. // We store the highest index of parts here to save some work in the fit
  3341. // calculation loop.
  3342. $slashes = $number_parts - 1;
  3343. // Extract load and to_arg functions.
  3344. foreach ($parts as $k => $part) {
  3345. $match = FALSE;
  3346. // Look for wildcards in the form allowed to be used in PHP functions,
  3347. // because we are using these to construct the load function names.
  3348. if (preg_match('/^%(|' . DRUPAL_PHP_FUNCTION_PATTERN . ')$/', $part, $matches)) {
  3349. if (empty($matches[1])) {
  3350. $match = TRUE;
  3351. $load_functions[$k] = NULL;
  3352. }
  3353. else {
  3354. if (function_exists($matches[1] . '_to_arg')) {
  3355. $to_arg_functions[$k] = $matches[1] . '_to_arg';
  3356. $load_functions[$k] = NULL;
  3357. $match = TRUE;
  3358. }
  3359. if (function_exists($matches[1] . '_load')) {
  3360. $function = $matches[1] . '_load';
  3361. // Create an array of arguments that will be passed to the _load
  3362. // function when this menu path is checked, if 'load arguments'
  3363. // exists.
  3364. $load_functions[$k] = isset($item['load arguments']) ? array($function => $item['load arguments']) : $function;
  3365. $match = TRUE;
  3366. }
  3367. }
  3368. }
  3369. if ($match) {
  3370. $parts[$k] = '%';
  3371. }
  3372. else {
  3373. $fit |= 1 << ($slashes - $k);
  3374. }
  3375. }
  3376. if ($fit) {
  3377. $move = TRUE;
  3378. }
  3379. else {
  3380. // If there is no %, it fits maximally.
  3381. $fit = (1 << $number_parts) - 1;
  3382. }
  3383. $masks[$fit] = 1;
  3384. $item['_load_functions'] = $load_functions;
  3385. $item['to_arg_functions'] = empty($to_arg_functions) ? '' : serialize($to_arg_functions);
  3386. $item += array(
  3387. 'title' => '',
  3388. 'weight' => 0,
  3389. 'type' => MENU_NORMAL_ITEM,
  3390. 'module' => '',
  3391. '_number_parts' => $number_parts,
  3392. '_parts' => $parts,
  3393. '_fit' => $fit,
  3394. );
  3395. $item += array(
  3396. '_visible' => (bool) ($item['type'] & MENU_VISIBLE_IN_BREADCRUMB),
  3397. '_tab' => (bool) ($item['type'] & MENU_IS_LOCAL_TASK),
  3398. );
  3399. if ($move) {
  3400. $new_path = implode('/', $item['_parts']);
  3401. $menu[$new_path] = $item;
  3402. $sort[$new_path] = $number_parts;
  3403. }
  3404. else {
  3405. $menu[$path] = $item;
  3406. $sort[$path] = $number_parts;
  3407. }
  3408. }
  3409. array_multisort($sort, SORT_NUMERIC, $menu);
  3410. // Apply inheritance rules.
  3411. foreach ($menu as $path => $v) {
  3412. $item = &$menu[$path];
  3413. if (!$item['_tab']) {
  3414. // Non-tab items.
  3415. $item['tab_parent'] = '';
  3416. $item['tab_root'] = $path;
  3417. }
  3418. // If not specified, assign the default tab type for local tasks.
  3419. elseif (!isset($item['context'])) {
  3420. $item['context'] = MENU_CONTEXT_PAGE;
  3421. }
  3422. for ($i = $item['_number_parts'] - 1; $i; $i--) {
  3423. $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
  3424. if (isset($menu[$parent_path])) {
  3425. $parent = &$menu[$parent_path];
  3426. // If we have no menu name, try to inherit it from parent items.
  3427. if (!isset($item['menu_name'])) {
  3428. // If the parent item of this item does not define a menu name (and no
  3429. // previous iteration assigned one already), try to find the menu name
  3430. // of the parent item in the currently stored menu links.
  3431. if (!isset($parent['menu_name'])) {
  3432. $menu_name = db_query("SELECT menu_name FROM {menu_links} WHERE router_path = :router_path AND module = 'system'", array(':router_path' => $parent_path))->fetchField();
  3433. if ($menu_name) {
  3434. $parent['menu_name'] = $menu_name;
  3435. }
  3436. }
  3437. // If the parent item defines a menu name, inherit it.
  3438. if (!empty($parent['menu_name'])) {
  3439. $item['menu_name'] = $parent['menu_name'];
  3440. }
  3441. }
  3442. if (!isset($item['tab_parent'])) {
  3443. // Parent stores the parent of the path.
  3444. $item['tab_parent'] = $parent_path;
  3445. }
  3446. if (!isset($item['tab_root']) && !$parent['_tab']) {
  3447. $item['tab_root'] = $parent_path;
  3448. }
  3449. // If an access callback is not found for a default local task we use
  3450. // the callback from the parent, since we expect them to be identical.
  3451. // In all other cases, the access parameters must be specified.
  3452. if (($item['type'] == MENU_DEFAULT_LOCAL_TASK) && !isset($item['access callback']) && isset($parent['access callback'])) {
  3453. $item['access callback'] = $parent['access callback'];
  3454. if (!isset($item['access arguments']) && isset($parent['access arguments'])) {
  3455. $item['access arguments'] = $parent['access arguments'];
  3456. }
  3457. }
  3458. // Same for page callbacks.
  3459. if (!isset($item['page callback']) && isset($parent['page callback'])) {
  3460. $item['page callback'] = $parent['page callback'];
  3461. if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
  3462. $item['page arguments'] = $parent['page arguments'];
  3463. }
  3464. if (!isset($item['file path']) && isset($parent['file path'])) {
  3465. $item['file path'] = $parent['file path'];
  3466. }
  3467. if (!isset($item['file']) && isset($parent['file'])) {
  3468. $item['file'] = $parent['file'];
  3469. if (empty($item['file path']) && isset($item['module']) && isset($parent['module']) && $item['module'] != $parent['module']) {
  3470. $item['file path'] = drupal_get_path('module', $parent['module']);
  3471. }
  3472. }
  3473. }
  3474. // Same for delivery callbacks.
  3475. if (!isset($item['delivery callback']) && isset($parent['delivery callback'])) {
  3476. $item['delivery callback'] = $parent['delivery callback'];
  3477. }
  3478. // Same for theme callbacks.
  3479. if (!isset($item['theme callback']) && isset($parent['theme callback'])) {
  3480. $item['theme callback'] = $parent['theme callback'];
  3481. if (!isset($item['theme arguments']) && isset($parent['theme arguments'])) {
  3482. $item['theme arguments'] = $parent['theme arguments'];
  3483. }
  3484. }
  3485. // Same for load arguments: if a loader doesn't have any explict
  3486. // arguments, try to find arguments in the parent.
  3487. if (!isset($item['load arguments'])) {
  3488. foreach ($item['_load_functions'] as $k => $function) {
  3489. // This loader doesn't have any explict arguments...
  3490. if (!is_array($function)) {
  3491. // ... check the parent for a loader at the same position
  3492. // using the same function name and defining arguments...
  3493. if (isset($parent['_load_functions'][$k]) && is_array($parent['_load_functions'][$k]) && key($parent['_load_functions'][$k]) === $function) {
  3494. // ... and inherit the arguments on the child.
  3495. $item['_load_functions'][$k] = $parent['_load_functions'][$k];
  3496. }
  3497. }
  3498. }
  3499. }
  3500. }
  3501. }
  3502. if (!isset($item['access callback']) && isset($item['access arguments'])) {
  3503. // Default callback.
  3504. $item['access callback'] = 'user_access';
  3505. }
  3506. if (!isset($item['access callback']) || empty($item['page callback'])) {
  3507. $item['access callback'] = 0;
  3508. }
  3509. if (is_bool($item['access callback'])) {
  3510. $item['access callback'] = intval($item['access callback']);
  3511. }
  3512. $item['load_functions'] = empty($item['_load_functions']) ? '' : serialize($item['_load_functions']);
  3513. $item += array(
  3514. 'access arguments' => array(),
  3515. 'access callback' => '',
  3516. 'page arguments' => array(),
  3517. 'page callback' => '',
  3518. 'delivery callback' => '',
  3519. 'title arguments' => array(),
  3520. 'title callback' => 't',
  3521. 'theme arguments' => array(),
  3522. 'theme callback' => '',
  3523. 'description' => '',
  3524. 'position' => '',
  3525. 'context' => 0,
  3526. 'tab_parent' => '',
  3527. 'tab_root' => $path,
  3528. 'path' => $path,
  3529. 'file' => '',
  3530. 'file path' => '',
  3531. 'include file' => '',
  3532. );
  3533. // Calculate out the file to be included for each callback, if any.
  3534. if ($item['file']) {
  3535. $file_path = $item['file path'] ? $item['file path'] : drupal_get_path('module', $item['module']);
  3536. $item['include file'] = $file_path . '/' . $item['file'];
  3537. }
  3538. }
  3539. // Sort the masks so they are in order of descending fit.
  3540. $masks = array_keys($masks);
  3541. rsort($masks);
  3542. return array($menu, $masks);
  3543. }
  3544. /**
  3545. * Saves data from menu_router_build() to the router table.
  3546. */
  3547. function _menu_router_save($menu, $masks) {
  3548. // Delete the existing router since we have some data to replace it.
  3549. db_truncate('menu_router')->execute();
  3550. // Prepare insert object.
  3551. $insert = db_insert('menu_router')
  3552. ->fields(array(
  3553. 'path',
  3554. 'load_functions',
  3555. 'to_arg_functions',
  3556. 'access_callback',
  3557. 'access_arguments',
  3558. 'page_callback',
  3559. 'page_arguments',
  3560. 'delivery_callback',
  3561. 'fit',
  3562. 'number_parts',
  3563. 'context',
  3564. 'tab_parent',
  3565. 'tab_root',
  3566. 'title',
  3567. 'title_callback',
  3568. 'title_arguments',
  3569. 'theme_callback',
  3570. 'theme_arguments',
  3571. 'type',
  3572. 'description',
  3573. 'position',
  3574. 'weight',
  3575. 'include_file',
  3576. ));
  3577. $num_records = 0;
  3578. foreach ($menu as $path => $item) {
  3579. // Fill in insert object values.
  3580. $insert->values(array(
  3581. 'path' => $item['path'],
  3582. 'load_functions' => $item['load_functions'],
  3583. 'to_arg_functions' => $item['to_arg_functions'],
  3584. 'access_callback' => $item['access callback'],
  3585. 'access_arguments' => serialize($item['access arguments']),
  3586. 'page_callback' => $item['page callback'],
  3587. 'page_arguments' => serialize($item['page arguments']),
  3588. 'delivery_callback' => $item['delivery callback'],
  3589. 'fit' => $item['_fit'],
  3590. 'number_parts' => $item['_number_parts'],
  3591. 'context' => $item['context'],
  3592. 'tab_parent' => $item['tab_parent'],
  3593. 'tab_root' => $item['tab_root'],
  3594. 'title' => $item['title'],
  3595. 'title_callback' => $item['title callback'],
  3596. 'title_arguments' => ($item['title arguments'] ? serialize($item['title arguments']) : ''),
  3597. 'theme_callback' => $item['theme callback'],
  3598. 'theme_arguments' => serialize($item['theme arguments']),
  3599. 'type' => $item['type'],
  3600. 'description' => $item['description'],
  3601. 'position' => $item['position'],
  3602. 'weight' => $item['weight'],
  3603. 'include_file' => $item['include file'],
  3604. ));
  3605. // Execute in batches to avoid the memory overhead of all of those records
  3606. // in the query object.
  3607. if (++$num_records == 20) {
  3608. $insert->execute();
  3609. $num_records = 0;
  3610. }
  3611. }
  3612. // Insert any remaining records.
  3613. $insert->execute();
  3614. // Store the masks.
  3615. variable_set('menu_masks', $masks);
  3616. return $menu;
  3617. }
  3618. /**
  3619. * Checks whether the site is in maintenance mode.
  3620. *
  3621. * This function will log the current user out and redirect to front page
  3622. * if the current user has no 'access site in maintenance mode' permission.
  3623. *
  3624. * @param $check_only
  3625. * If this is set to TRUE, the function will perform the access checks and
  3626. * return the site offline status, but not log the user out or display any
  3627. * messages.
  3628. *
  3629. * @return
  3630. * FALSE if the site is not in maintenance mode, the user login page is
  3631. * displayed, or the user has the 'access site in maintenance mode'
  3632. * permission. TRUE for anonymous users not being on the login page when the
  3633. * site is in maintenance mode.
  3634. */
  3635. function _menu_site_is_offline($check_only = FALSE) {
  3636. // Check if site is in maintenance mode.
  3637. if (variable_get('maintenance_mode', 0)) {
  3638. if (user_access('access site in maintenance mode')) {
  3639. // Ensure that the maintenance mode message is displayed only once
  3640. // (allowing for page redirects) and specifically suppress its display on
  3641. // the maintenance mode settings page.
  3642. if (!$check_only && $_GET['q'] != 'admin/config/development/maintenance') {
  3643. if (user_access('administer site configuration')) {
  3644. drupal_set_message(t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance'))), 'status', FALSE);
  3645. }
  3646. else {
  3647. drupal_set_message(t('Operating in maintenance mode.'), 'status', FALSE);
  3648. }
  3649. }
  3650. }
  3651. else {
  3652. return TRUE;
  3653. }
  3654. }
  3655. return FALSE;
  3656. }
  3657. /**
  3658. * @} End of "defgroup menu".
  3659. */