menu.inc 135 KB

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