menu.inc 139 KB

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