menu.inc 136 KB

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