menu.inc 135 KB

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