metatag.module 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287
  1. <?php
  2. /**
  3. * @file
  4. * Primary hook implementations for Metatag.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function metatag_help($path, $arg) {
  10. if ($path == 'admin/config/search/metatags') {
  11. return '<p>' . t('To view a summary of the default meta tags and the inheritance, click on a meta tag type.') . '</p>';
  12. }
  13. elseif ($path == 'admin/help#metatag') {
  14. return '<p>' . t('The Metatag module provides a options to let each page have customized meta data added to the "meta" tags in the HEAD section of the document.') . '</p>';
  15. }
  16. elseif ($path == 'admin/config/search/metatags/bulk-revert') {
  17. return '<p>' . t('This form <strong>will wipe out</strong> all custom meta tags for the selected entities, reverting them to the default configuration assigned at the <a href="@url">Defaults tab</a>. For example, if the meta tags are changed for an article they will be removed if the "Node: Article" checkbox is selected.', array('@url' => url('admin/config/search/metatags'))) . '</p>';
  18. }
  19. }
  20. /**
  21. * Implements hook_theme().
  22. */
  23. function metatag_theme() {
  24. $info['metatag'] = array(
  25. 'render element' => 'element',
  26. 'file' => 'metatag.theme.inc',
  27. );
  28. $info['metatag_http_equiv'] = array(
  29. 'render element' => 'element',
  30. 'file' => 'metatag.theme.inc',
  31. );
  32. $info['metatag_link_rel'] = array(
  33. 'render element' => 'element',
  34. 'file' => 'metatag.theme.inc',
  35. );
  36. $info['metatag_link_rev'] = array(
  37. 'render element' => 'element',
  38. 'file' => 'metatag.theme.inc',
  39. );
  40. $info['metatag_property'] = array(
  41. 'render element' => 'element',
  42. 'file' => 'metatag.theme.inc',
  43. );
  44. return $info;
  45. }
  46. /**
  47. * Implements hook_ctools_plugin_api().
  48. */
  49. function metatag_ctools_plugin_api($owner, $api) {
  50. if ($owner == 'metatag' && $api == 'metatag') {
  51. return array('version' => 1);
  52. }
  53. }
  54. /**
  55. * Implements hook_ctools_plugin_directory().
  56. */
  57. function metatag_ctools_plugin_directory($owner, $plugin_type) {
  58. if ($owner == 'ctools' && $plugin_type == 'content_types') {
  59. return "plugins/$plugin_type";
  60. }
  61. }
  62. /**
  63. * Implements hook_hook_info().
  64. */
  65. function metatag_hook_info() {
  66. $hooks = array(
  67. 'metatag_config_default',
  68. 'metatag_config_default_alter',
  69. 'metatag_config_delete',
  70. 'metatag_config_insert',
  71. 'metatag_config_instance_info',
  72. 'metatag_config_instance_info_alter',
  73. 'metatag_config_load',
  74. 'metatag_config_load_presave',
  75. 'metatag_config_update',
  76. 'metatag_info',
  77. 'metatag_info_alter',
  78. );
  79. return array_fill_keys($hooks, array('group' => 'metatag'));
  80. }
  81. /**
  82. * Implements hook_permission().
  83. */
  84. function metatag_permission() {
  85. $permissions['administer meta tags'] = array(
  86. 'title' => t('Administer meta tags'),
  87. 'restrict access' => TRUE,
  88. 'description' => t('Control the main settings pages and modify per-object meta tags.'),
  89. );
  90. $permissions['edit meta tags'] = array(
  91. 'title' => t('Edit meta tags'),
  92. 'description' => t('Modify meta tags on individual entity records (nodes, terms, users, etc).'),
  93. );
  94. // Optional extended edit permissions.
  95. if (variable_get('metatag_extended_permissions', FALSE)) {
  96. $permissions['edit meta tags']['description'] .= '<br />' . t('<em>Extended Permissions</em> has been enabled. Roles have the :admin permission will see all meta tags on edit forms, otherwise the permissions below will control which meta tags are available and are needed in addition to <em>Edit meta tags</em>.', array(':admin' => t('Administer meta tags')));
  97. $metatags = metatag_get_info();
  98. foreach ($metatags['tags'] as $metatag_name => $metatag) {
  99. $permissions['edit meta tag: ' . $metatag_name] = array(
  100. 'title' => t('Extended permission: Edit :tag meta tag', array(':tag' => $metatag['label'])),
  101. 'description' => t('Customize the :tag meta tag on individual forms.', array(':tag' => $metatag['label'])),
  102. );
  103. }
  104. }
  105. return $permissions;
  106. }
  107. /**
  108. * Implements hook_menu().
  109. */
  110. function metatag_menu() {
  111. $items['admin/config/search/metatags'] = array(
  112. 'title' => 'Metatag',
  113. 'description' => 'Configure Metatag defaults.',
  114. 'page callback' => 'metatag_config_overview',
  115. 'access arguments' => array('administer meta tags'),
  116. 'file' => 'metatag.admin.inc',
  117. );
  118. $items['admin/config/search/metatags/config'] = array(
  119. 'title' => 'Defaults',
  120. 'type' => MENU_DEFAULT_LOCAL_TASK,
  121. 'weight' => -10,
  122. );
  123. $items['admin/config/search/metatags/config/add'] = array(
  124. 'title' => 'Add default meta tags',
  125. 'page callback' => 'drupal_get_form',
  126. 'page arguments' => array('metatag_config_add_form'),
  127. 'access arguments' => array('administer meta tags'),
  128. 'file' => 'metatag.admin.inc',
  129. 'type' => MENU_LOCAL_ACTION,
  130. );
  131. $items['admin/config/search/metatags/config/%metatag_config'] = array(
  132. 'title callback' => 'metatag_config_title',
  133. 'title arguments' => array(5),
  134. 'page callback' => 'drupal_get_form',
  135. 'page arguments' => array('metatag_config_edit_form', 5),
  136. 'access arguments' => array('administer meta tags'),
  137. 'file' => 'metatag.admin.inc',
  138. );
  139. $items['admin/config/search/metatags/config/%metatag_config/edit'] = array(
  140. 'title' => 'Edit',
  141. 'type' => MENU_DEFAULT_LOCAL_TASK,
  142. 'weight' => -10,
  143. );
  144. $items['admin/config/search/metatags/config/%metatag_config/enable'] = array(
  145. 'title' => 'Enable',
  146. 'page callback' => 'metatag_config_enable',
  147. 'page arguments' => array(5),
  148. 'access callback' => 'metatag_config_access',
  149. 'access arguments' => array('enable', 5),
  150. 'file' => 'metatag.admin.inc',
  151. );
  152. $items['admin/config/search/metatags/config/%metatag_config/disable'] = array(
  153. 'title' => 'Disable',
  154. 'page callback' => 'metatag_config_disable',
  155. 'page arguments' => array(5),
  156. 'access callback' => 'metatag_config_access',
  157. 'access arguments' => array('disable', 5),
  158. 'file' => 'metatag.admin.inc',
  159. );
  160. $items['admin/config/search/metatags/config/%metatag_config/revert'] = array(
  161. 'title' => 'Revert',
  162. 'page callback' => 'drupal_get_form',
  163. 'page arguments' => array('metatag_config_delete_form', 5),
  164. 'access callback' => 'metatag_config_access',
  165. 'access arguments' => array('revert', 5),
  166. 'file' => 'metatag.admin.inc',
  167. 'type' => MENU_LOCAL_TASK,
  168. );
  169. $items['admin/config/search/metatags/config/%metatag_config/delete'] = array(
  170. 'title' => 'Delete',
  171. 'page callback' => 'drupal_get_form',
  172. 'page arguments' => array('metatag_config_delete_form', 5),
  173. 'access callback' => 'metatag_config_access',
  174. 'access arguments' => array('delete', 5),
  175. 'file' => 'metatag.admin.inc',
  176. );
  177. $items['admin/config/search/metatags/config/%metatag_config/export'] = array(
  178. 'title' => 'Export',
  179. 'page callback' => 'metatag_config_export_form',
  180. 'page arguments' => array(5),
  181. 'access arguments' => array('administer meta tags'),
  182. 'file' => 'metatag.admin.inc',
  183. 'type' => MENU_LOCAL_TASK,
  184. 'weight' => 10,
  185. );
  186. $items['admin/config/search/metatags/settings'] = array(
  187. 'title' => 'Settings',
  188. 'page callback' => 'drupal_get_form',
  189. 'page arguments' => array('metatag_admin_settings_form'),
  190. 'access arguments' => array('administer meta tags'),
  191. 'type' => MENU_LOCAL_TASK,
  192. 'weight' => 30,
  193. 'file' => 'metatag.admin.inc',
  194. );
  195. $items['admin/config/search/metatags/bulk-revert'] = array(
  196. 'title' => 'Bulk revert',
  197. 'page callback' => 'drupal_get_form',
  198. 'page arguments' => array('metatag_bulk_revert_form'),
  199. 'access arguments' => array('administer meta tags'),
  200. 'type' => MENU_LOCAL_TASK,
  201. 'weight' => 40,
  202. 'file' => 'metatag.admin.inc',
  203. );
  204. // Optional integration with the i18n_string module for translating the
  205. // configurations. Note: this should also check for 'metatag_i18n_disabled'
  206. // but doing so would require rebuilding the menu cache every time the Metatag
  207. // settings page was saved, which may not be advised. Instead the links to
  208. // these pages on the config pages *do* check the variable, which is close
  209. // enough.
  210. if (module_exists('i18n_string')) {
  211. $items['admin/config/search/metatags/config/%metatag_config/translate'] = array(
  212. 'title' => 'Translate',
  213. 'access arguments' => array('administer meta tags'),
  214. 'page callback' => 'i18n_string_object_translate_page',
  215. 'page arguments' => array('metatag_config', 5),
  216. 'type' => MENU_LOCAL_TASK,
  217. );
  218. $items['admin/config/search/metatags/config/%metatag_config/translate/%i18n_language'] = array(
  219. 'title' => 'Translate',
  220. 'access arguments' => array('administer meta tags'),
  221. 'page callback' => 'i18n_string_object_translate_page',
  222. 'page arguments' => array('metatag_config', 5, 7),
  223. 'type' => MENU_CALLBACK,
  224. );
  225. }
  226. return $items;
  227. }
  228. /**
  229. * Implements hook_flush_caches().
  230. */
  231. function metatag_flush_caches() {
  232. return array('cache_metatag');
  233. }
  234. /**
  235. * Implements hook_action_info().
  236. * Provides integration with Views bulk operations.
  237. */
  238. function metatag_action_info() {
  239. return array(
  240. 'metatag_modify_metatags_action' => array(
  241. 'type' => 'entity',
  242. 'label' => t('Modify entity metatags'),
  243. 'configurable' => FALSE,
  244. 'vbo_configurable' => TRUE,
  245. 'behavior' => array('changes_property'),
  246. 'triggers' => array('any'),
  247. 'permissions' => array('edit meta tags'),
  248. ),
  249. );
  250. }
  251. /**
  252. * Updates entity metatags with values from the action form.
  253. *
  254. * @param object $entity
  255. * The entity housing the metatags to modify.
  256. * @param array $context
  257. * Contextual information passed from the View bulk operation configuration
  258. * form. The updated metatag values for the entity are stored in
  259. * $context['updates'].
  260. */
  261. function metatag_modify_metatags_action($entity, $context) {
  262. if (empty($entity)) {
  263. drupal_set_message(t("Error while trying to update an entity's metatags."),
  264. 'warning', FALSE);
  265. return;
  266. }
  267. $updates = $context['updates'];
  268. $language = $entity->language;
  269. // Reset metatags to the entity default configs.
  270. if ($context['reset_default']) {
  271. $instance = $context['entity_type'] . ':' . $entity->type;
  272. $entity_defaults = metatag_config_load_with_defaults($instance);
  273. // Clean up empty values.
  274. foreach ($entity_defaults as $name => $tag) {
  275. if (empty($tag['value'])) {
  276. unset($entity_defaults[$name]);
  277. }
  278. }
  279. $entity->metatags[$language] = $entity_defaults;
  280. }
  281. // Otherwise, we're updating existing values. Ensure that the entity has any
  282. // metatags already set. If so then merge the updates to avoid overwriting
  283. // existing values that may exist as an array. E.g. robots.
  284. elseif (!empty($entity->metatags) && !empty($entity->metatags[$language])) {
  285. foreach ($updates as $tag => $value_array) {
  286. if (is_array($updates[$tag]['value']) && !empty($entity->metatags[$language][$tag]['value'])) {
  287. $entity->metatags[$language][$tag]['value'] = array_merge($entity->metatags[$language][$tag]['value'],
  288. array_filter($updates[$tag]['value']));
  289. }
  290. elseif (!empty($updates[$tag]['value'])) {
  291. $entity->metatags[$language][$tag]['value'] = $updates[$tag]['value'];
  292. }
  293. }
  294. }
  295. // Otherwise just set the net new tags.
  296. else {
  297. $entity->metatags[$language] = $updates;
  298. }
  299. entity_save($context['entity_type'], $entity);
  300. }
  301. /**
  302. * The Views bulk operation configuration form for modifying metatags.
  303. *
  304. * @param array $context
  305. * Contextual information passed from the View bulk operation configuration
  306. * form.
  307. *
  308. * @return array
  309. * A form API compatible array.
  310. */
  311. function metatag_modify_metatags_action_form($context) {
  312. $form = array(
  313. '#entity_type' => $context['entity_type'],
  314. );
  315. // There can be multiple instances being edited here. So the 2nd param passed
  316. // here is as generic as possible.
  317. metatag_metatags_form($form, 'global');
  318. // Force the metatags tab to be fully visible and save a click from the user.
  319. $form['metatags']['#collapsed'] = FALSE;
  320. $form['metatags']['#collapsible'] = FALSE;
  321. // If we're reseting to the entity default, then we don't need to show the
  322. // form fields.
  323. $form['metatags']['#states'] = array(
  324. 'visible' => array(
  325. ':input[name="reset_default"]' => array('checked' => FALSE),
  326. ),
  327. );
  328. // Add an option to reset selected entities to the default configuration.
  329. $form['reset_default'] = array(
  330. '#type' => 'checkbox',
  331. '#title' => t('Reset to metatag defaults'),
  332. '#default_value' => FALSE,
  333. '#description' => t('Check to <strong>fully reset all metatags</strong> on
  334. the entities being modified to their <a href="@settings">default
  335. configuration</a>.', array(
  336. '@settings' => url('admin/config/search/metatags'),
  337. )),
  338. );
  339. return $form;
  340. }
  341. /**
  342. * Submit handler for metatag_modify_metatags_action_form(). Filters out
  343. * the user entered values from the defaults and returns the updated values to
  344. * the $context array.
  345. *
  346. * @return array
  347. * The updated metatag values that is ultimately keyed at $context['updates'].
  348. */
  349. function metatag_modify_metatags_action_submit($form, &$form_state) {
  350. $updates = $form_state['values']['metatags'][LANGUAGE_NONE];
  351. $defaults = metatag_config_load_with_defaults($form['#entity_type']);
  352. // Filter out the true updates.
  353. metatag_filter_values_from_defaults($updates, $defaults);
  354. return array(
  355. 'updates' => $updates,
  356. 'reset_default' => $form_state['values']['reset_default'],
  357. );
  358. }
  359. /**
  360. * Load a metatag configuration record with all the defaults merged in.
  361. *
  362. * For example, given the configuration instance 'node:article', this function
  363. * will load the configuration records for 'node:article', then 'node', and
  364. * then finally 'global', with each attempt using an array merge.
  365. *
  366. * The levels of defaults is arranged by splitting the $instance variable by
  367. * the colon character, and always using a 'global' instance at the end.
  368. */
  369. function metatag_config_load_with_defaults($instance, $include_global = TRUE) {
  370. $defaults = &drupal_static(__FUNCTION__, array());
  371. // Use the current page's locale.
  372. $langcode = $GLOBALS['language_content']->language;
  373. // Statically cache defaults since they can include multiple levels.
  374. $cid = "config:{$instance}:{$langcode}" . ($include_global ? ':withglobal' : ':withoutglobal');
  375. if (!isset($defaults[$cid])) {
  376. if ($cache = metatag_cache_get($cid)) {
  377. $defaults[$cid] = $cache->data;
  378. }
  379. else {
  380. $defaults[$cid] = array();
  381. $instances = metatag_config_get_parent_instances($instance, $include_global);
  382. $configs = metatag_config_load_multiple($instances);
  383. foreach ($instances as $key) {
  384. // Ignore disabled configurations.
  385. if (!isset($configs[$key]) || !empty($configs[$key]->disabled)) {
  386. continue;
  387. }
  388. // Add config to the defaults array.
  389. if (!empty($configs[$key]->config)) {
  390. $defaults[$cid] += $configs[$key]->config;
  391. }
  392. }
  393. metatag_cache_set($cid, $defaults[$cid]);
  394. }
  395. }
  396. return $defaults[$cid];
  397. }
  398. /**
  399. * Load a metatag configuration record.
  400. */
  401. function metatag_config_load($instance) {
  402. $results = metatag_config_load_multiple(array($instance));
  403. return !empty($results[$instance]) ? $results[$instance] : FALSE;
  404. }
  405. /**
  406. * Load multiple metatag configuration records.
  407. */
  408. function metatag_config_load_multiple(array $instances) {
  409. // Load the data.
  410. ctools_include('export');
  411. $configs = ctools_export_load_object('metatag_config', 'names', $instances);
  412. // "Fix" any records that might be using old values. Ideally these will be
  413. // permanently fixed by being re-saved or re-exported.
  414. foreach (metatag_config_get_replacements() as $old_tag => $new_tag) {
  415. foreach ($configs as $instance => $config) {
  416. if (isset($config->config[$old_tag])) {
  417. $config->config[$new_tag] = $config->config[$old_tag];
  418. unset($config->config[$old_tag]);
  419. }
  420. }
  421. }
  422. // Translate the configuration.
  423. if (module_exists('i18n_string') && !variable_get('metatag_i18n_disabled', FALSE)) {
  424. $options = array();
  425. // By default disable the watchdog logging of translation messages.
  426. $options['watchdog'] = variable_get('metatag_i18n_enable_watchdog', FALSE);
  427. foreach ($configs as $instance => &$config) {
  428. foreach ($config->config as $tag => &$value) {
  429. if (isset($value['value']) && is_string($value['value'])) {
  430. $value['value'] = i18n_string_translate(array(
  431. 'metatag',
  432. 'metatag_config',
  433. $instance,
  434. $tag,
  435. ),
  436. $value['value'],
  437. $options);
  438. }
  439. }
  440. }
  441. }
  442. return $configs;
  443. }
  444. /**
  445. * Identify the meta tags that have been deprecated and replaced by others.
  446. */
  447. function metatag_config_get_replacements() {
  448. $replacements = &drupal_static(__FUNCTION__);
  449. if (!isset($replacements)) {
  450. $replacements = array();
  451. foreach (metatag_get_info('tags') as $tag_name => $tag_info) {
  452. if (!empty($tag_info['replaces'])) {
  453. if (!is_array($tag_info['replaces'])) {
  454. $tag_info['replaces'] = array($tag_info['replaces']);
  455. }
  456. foreach ($tag_info['replaces'] as $replaces) {
  457. $replacements[$replaces] = $tag_name;
  458. }
  459. }
  460. }
  461. }
  462. return $replacements;
  463. }
  464. /**
  465. * Save a metatag configuration record to the database.
  466. */
  467. function metatag_config_save($config) {
  468. $config->is_new = empty($config->cid);
  469. // Allow modules to alter the configuration before it is saved using
  470. // hook_metatag_config_presave().
  471. module_invoke_all('metatag_config_presave', $config);
  472. if ($config->is_new) {
  473. drupal_write_record('metatag_config', $config);
  474. // Allow modules to act upon the record insertion using
  475. // hook_metatag_config_insert().
  476. module_invoke_all('metatag_config_insert', $config);
  477. }
  478. else {
  479. drupal_write_record('metatag_config', $config, array('cid'));
  480. // Allow modules to act upon the record update using
  481. // hook_metatag_config_insert().
  482. module_invoke_all('metatag_config_update', $config);
  483. }
  484. unset($config->is_new);
  485. // Clear any caches.
  486. metatag_config_cache_clear();
  487. }
  488. /**
  489. * Delete a metatag configuration record.
  490. */
  491. function metatag_config_delete($config) {
  492. db_delete('metatag_config')
  493. ->condition('instance', $config->instance)
  494. ->execute();
  495. // Allow modules to act upon the record deletion using
  496. // hook_metatag_config_delete().
  497. module_invoke_all('metatag_config_delete', $config);
  498. // Clear any caches.
  499. metatag_config_cache_clear();
  500. }
  501. /**
  502. * Clear the metatag configuration cache.
  503. */
  504. function metatag_config_cache_clear() {
  505. cache_clear_all('*', 'cache_metatag', TRUE);
  506. drupal_static_reset('metatag_config_load_with_defaults');
  507. drupal_static_reset('metatag_entity_supports_metatags');
  508. drupal_static_reset('metatag_config_instance_info');
  509. drupal_static_reset('metatag_get_info');
  510. ctools_include('export');
  511. ctools_export_load_object_reset('metatag_config');
  512. }
  513. /**
  514. * Load an entity's tags.
  515. *
  516. * @param string $entity_type
  517. * The entity type to load.
  518. * @param int $entity_id
  519. * The ID of the entity to load.
  520. * @param mixed $revision_id
  521. * Optional revision ID to load instead of the entity ID.
  522. *
  523. * @return array
  524. * An array of tag data keyed by language for the entity's current active
  525. * revision.
  526. */
  527. function metatag_metatags_load($entity_type, $entity_id, $revision_id = NULL) {
  528. // A specific revision ID was not requested, so get the active revision ID.
  529. if (is_null($revision_id)) {
  530. // Unfortunately, the only way of getting the active revision ID is to
  531. // first load the entity, and then extract the ID. This is a bit
  532. // performance intensive, but it seems to be the only way of doing it.
  533. $entities = entity_load($entity_type, array($entity_id));
  534. if (!empty($entities[$entity_id])) {
  535. // We only care about the revision_id.
  536. list(, $revision_id,) = entity_extract_ids($entity_type, $entities[$entity_id]);
  537. }
  538. }
  539. // This returns an array nested by the entity ID, the revision ID and the
  540. // langcode.
  541. $metatags = metatag_metatags_load_multiple($entity_type, array($entity_id), array($revision_id));
  542. // Look for records for the requested revision ID.
  543. if (isset($metatags[$entity_id][$revision_id])) {
  544. return $metatags[$entity_id][$revision_id];
  545. }
  546. // Getting to this point means that no meta tags were identified earlier, so
  547. // return an empty array.
  548. return array();
  549. }
  550. /**
  551. * Load tags for multiple entities.
  552. *
  553. * @param string $entity_type
  554. * The entity type to load.
  555. * @param array $entity_ids
  556. * The list of entity IDs.
  557. * @param array $revision_ids
  558. * Optional revision ID to load instead of the entity ID.
  559. *
  560. * @return array
  561. * An array of tag data, keyed by entity ID, revision ID and language.
  562. */
  563. function metatag_metatags_load_multiple($entity_type, array $entity_ids, array $revision_ids = array()) {
  564. // Double check entity IDs are all numeric.
  565. $entity_ids = array_filter($entity_ids, 'is_numeric');
  566. if (empty($entity_ids)) {
  567. return array();
  568. }
  569. // Ensure that the revision IDs are all numeric too.
  570. $revision_ids = array_filter($revision_ids, 'is_numeric');
  571. // Verify that there aren't any empty values copied in from
  572. // metatag_metatags_load(). Note: a zero indicates that the entity record does
  573. // not support revisions, so this is ok to do.
  574. $revision_ids = array_filter($revision_ids);
  575. // Also need to check if the metatag table exists since this condition could
  576. // fire before the table has been installed yet.
  577. if (!variable_get('metatag_schema_installed', FALSE)) {
  578. if (db_table_exists('metatag')) {
  579. variable_set('metatag_schema_installed', TRUE);
  580. }
  581. else {
  582. watchdog('metatag', 'The system tried to load metatag data before the schema was fully loaded.', array(), WATCHDOG_WARNING);
  583. return array();
  584. }
  585. }
  586. // Verify that the metatag.revision_id field has been added to the {metatag}
  587. // table schema.
  588. if (!variable_get('metatag_has_revision_id', FALSE)) {
  589. if (db_field_exists('metatag', 'revision_id')) {
  590. variable_set('metatag_has_revision_id', TRUE);
  591. }
  592. else {
  593. watchdog('metatag', 'The database updates need to be ran.', array(), WATCHDOG_WARNING);
  594. return array();
  595. }
  596. }
  597. // Get all translations of tag data for this entity.
  598. $query = db_select('metatag', 'm')
  599. ->fields('m', array('entity_id', 'revision_id', 'language', 'data'))
  600. ->condition('m.entity_type', $entity_type);
  601. // Filter by revision_ids if they are available. If not, filter by entity_ids.
  602. if (!empty($revision_ids)) {
  603. $query->condition('m.revision_id', $revision_ids, 'IN');
  604. }
  605. else {
  606. $query->condition('m.entity_id', $entity_ids, 'IN');
  607. }
  608. $result = $query->execute();
  609. // Marshal it into an array keyed by entity ID. Each value is an array of
  610. // translations keyed by language code.
  611. $metatags = array();
  612. while ($record = $result->fetchObject()) {
  613. $data = unserialize($record->data);
  614. // "Fix" any records that might be using old values. Ideally these will be
  615. // permanently fixed by being re-saved or re-exported.
  616. foreach (metatag_config_get_replacements() as $old_tag => $new_tag) {
  617. if (isset($data[$old_tag])) {
  618. $data[$new_tag] = $data[$old_tag];
  619. unset($data[$old_tag]);
  620. }
  621. }
  622. $metatags[$record->entity_id][$record->revision_id][$record->language] = $data;
  623. }
  624. return $metatags;
  625. }
  626. /**
  627. * Save an entity's tags.
  628. *
  629. * @param string $entity_type
  630. * The entity type to load.
  631. * @param int $entity_id
  632. * The entity's primary ID.
  633. * @param int $revision_id
  634. * The entity's revision ID.
  635. * @param array $metatags
  636. * All of the tag information, keyed by the language code. Most meta tags use
  637. * the 'value' element, so the structure should look like:
  638. * array(
  639. * LANGUAGE_NONE => array(
  640. * 'title' => array(
  641. * 'value' => "This node's title!",
  642. * ),
  643. * 'og:title' => array(
  644. * 'value' => "This node's title for Open Graph!",
  645. * ),
  646. * 'og:image' => array(
  647. * 'value' => "[node:field_thumbnail]",
  648. * ),
  649. * ),
  650. * );
  651. * @param string|null $bundle
  652. * The bundle of the entity that is being saved. Optional.
  653. */
  654. function metatag_metatags_save($entity_type, $entity_id, $revision_id, $metatags, $bundle = NULL) {
  655. // Check that $entity_id is numeric because of Entity API and string IDs.
  656. if (!is_numeric($entity_id)) {
  657. return;
  658. }
  659. // Don't do anything if the entity type is not supported.
  660. if (!metatag_entity_supports_metatags($entity_type)) {
  661. return;
  662. }
  663. // Verify the entity bundle is supported, if not available just check the
  664. // entity type.
  665. if (!empty($bundle)) {
  666. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  667. return;
  668. }
  669. }
  670. else {
  671. if (!metatag_entity_supports_metatags($entity_type)) {
  672. return;
  673. }
  674. }
  675. // The revision_id must be a numeric value; some entities use NULL for the
  676. // revision so change that to a zero.
  677. if (is_null($revision_id)) {
  678. $revision_id = 0;
  679. }
  680. // Handle scenarios where the metatags are completely empty, this will have
  681. // the effect of erasing the meta tags for those this entity.
  682. if (empty($metatags)) {
  683. $metatags = array();
  684. // Add an empty array record for each language.
  685. $languages = db_query("SELECT language
  686. FROM {metatag}
  687. WHERE (entity_type = :type)
  688. AND (entity_id = :id)
  689. AND (revision_id = :revision)",
  690. array(
  691. ':type' => $entity_type,
  692. ':id' => $entity_id,
  693. ':revision' => $revision_id,
  694. ))->fetchCol();
  695. foreach ($languages as $oldlang) {
  696. $metatags[$oldlang] = array();
  697. }
  698. }
  699. // Update each of the per-language metatag configurations in turn.
  700. foreach ($metatags as $langcode => $new_metatags) {
  701. // Allow other modules to alter the meta tags prior to saving using
  702. // hook_metatag_presave().
  703. foreach (module_implements('metatag_presave') as $module) {
  704. $function = "{$module}_metatag_presave";
  705. $function($new_metatags, $entity_type, $entity_id, $revision_id, $langcode);
  706. }
  707. // If the data array is empty, there is no data to actually save, so just
  708. // delete the record from the database.
  709. if (empty($new_metatags)) {
  710. db_delete('metatag')
  711. ->condition('entity_type', $entity_type)
  712. ->condition('entity_id', $entity_id)
  713. ->condition('revision_id', $revision_id)
  714. ->condition('language', $langcode)
  715. ->execute();
  716. }
  717. // Otherwise save the data for this entity.
  718. else {
  719. db_merge('metatag')
  720. ->key(array(
  721. 'entity_type' => $entity_type,
  722. 'entity_id' => $entity_id,
  723. 'language' => $langcode,
  724. 'revision_id' => $revision_id,
  725. ))
  726. ->fields(array(
  727. 'data' => serialize($new_metatags),
  728. ))
  729. ->execute();
  730. }
  731. }
  732. // Clear cached data.
  733. metatag_metatags_cache_clear($entity_type, $entity_id);
  734. // Clear the entity cache.
  735. entity_get_controller($entity_type)->resetCache(array($entity_id));
  736. }
  737. /**
  738. * Delete an entity's tags.
  739. *
  740. * @param string $entity_type
  741. * The entity type.
  742. * @param int $entity_id
  743. * The entity's ID.
  744. * @param int $revision_id
  745. * The entity's VID.
  746. * @param string $langcode
  747. * The language ID of the entry to delete. If left blank, all language
  748. * entries for this entity will be deleted.
  749. */
  750. function metatag_metatags_delete($entity_type, $entity_id, $revision_id = NULL, $langcode = NULL) {
  751. $revision_ids = array();
  752. if (!empty($revision_id)) {
  753. $revision_ids[] = $revision_id;
  754. }
  755. return metatag_metatags_delete_multiple($entity_type, array($entity_id), $revision_ids, $langcode);
  756. }
  757. /**
  758. * Delete multiple entities' tags.
  759. *
  760. * @param string $entity_type
  761. * The entity type.
  762. * @param array $entity_ids
  763. * The list of IDs.
  764. * @param array $revision_ids
  765. * An optional list of revision IDs; if omitted all revisions will be deleted.
  766. * @param string $langcode
  767. * The language ID of the entities to delete. If left blank, all language
  768. * entries for the enities will be deleted.
  769. *
  770. * @return bool
  771. * If any problems were encountered will return FALSE, otherwise TRUE.
  772. */
  773. function metatag_metatags_delete_multiple($entity_type, array $entity_ids, array $revision_ids = array(), $langcode = NULL) {
  774. // Double check entity IDs and revision IDs are numeric.
  775. $entity_ids = array_filter($entity_ids, 'is_numeric');
  776. $revision_ids = array_filter($revision_ids, 'is_numeric');
  777. if (!empty($entity_ids) || !empty($revision_ids)) {
  778. $transaction = db_transaction();
  779. try {
  780. // Let other modules know about the records being deleted using
  781. // hook_metatag_metatags_delete().
  782. module_invoke_all('metatag_metatags_delete', $entity_type, $entity_ids, $revision_ids, $langcode);
  783. // Set the entity to delete.
  784. $query = db_delete('metatag')
  785. ->condition('entity_type', $entity_type);
  786. // If revision IDs were specified then just use those in the query.
  787. if (!empty($revision_ids)) {
  788. $query->condition('revision_id', $revision_ids, 'IN');
  789. }
  790. // No revision IDs were specified, so work from the entity IDs.
  791. else {
  792. $query->condition('entity_id', $entity_ids, 'IN');
  793. }
  794. // Limit to a language if one was specified.
  795. if (!empty($langcode)) {
  796. $query->condition('language', $langcode);
  797. }
  798. // Perform the deletion(s).
  799. $query->execute();
  800. // Clear cached data.
  801. metatag_metatags_cache_clear($entity_type, $entity_ids);
  802. // Clear the caches for these entities.
  803. entity_get_controller($entity_type)->resetCache($entity_ids);
  804. return TRUE;
  805. }
  806. catch (Exception $e) {
  807. $transaction->rollback();
  808. watchdog_exception('metatag', $e);
  809. throw $e;
  810. }
  811. }
  812. else {
  813. watchdog('metatag', 'No entity IDs or revision IDs were submitted to metatag_metatags_delete_multiple().');
  814. }
  815. return FALSE;
  816. }
  817. /**
  818. * Clear the cached records for a given entity type or entity ID.
  819. *
  820. * @param string $entity_type
  821. * The entity type to clear.
  822. */
  823. function metatag_metatags_cache_clear($entity_type, $entity_ids = NULL) {
  824. if (empty($entity_ids)) {
  825. cache_clear_all("output:$entity_type", 'cache_metatag', TRUE);
  826. }
  827. else {
  828. if (!is_array($entity_ids)) {
  829. $entity_ids = array($entity_ids);
  830. }
  831. foreach ($entity_ids as $entity_id) {
  832. cache_clear_all("output:$entity_type:$entity_id", 'cache_metatag');
  833. }
  834. }
  835. }
  836. /**
  837. * Implements hook_entity_load().
  838. */
  839. function metatag_entity_load($entities, $entity_type) {
  840. // Wrap this in a try-catch block to work around occasions when the schema
  841. // hasn't been updated yet.
  842. try {
  843. if (metatag_entity_supports_metatags($entity_type)) {
  844. // Get the revision_ids.
  845. $revision_ids = array();
  846. // Track the entity IDs for values to load.
  847. $entity_ids = array();
  848. // Some entities don't support revisions.
  849. $supports_revisions = TRUE;
  850. // Extract the revision ID and verify the entity's bundle is supported.
  851. foreach ($entities as $key => $entity) {
  852. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  853. // Verify that each entity bundle supports Metatag.
  854. if (metatag_entity_supports_metatags($entity_type, $bundle)) {
  855. $entity_ids[] = $entity_id;
  856. if (!empty($revision_id)) {
  857. $revision_ids[] = $revision_id;
  858. }
  859. }
  860. }
  861. // Only proceed if either there were revision IDs identified, or the
  862. // entity doesn't support revisions anyway.
  863. if (!empty($entity_ids)) {
  864. // Load all meta tags for these entities.
  865. $metatags = metatag_metatags_load_multiple($entity_type, $entity_ids, $revision_ids);
  866. // Assign the metatag records for the correct revision ID.
  867. if (!empty($metatags)) {
  868. foreach ($entities as $entity_id => $entity) {
  869. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  870. $revision_id = intval($revision_id);
  871. $entities[$entity_id]->metatags = isset($metatags[$entity_id][$revision_id]) ? $metatags[$entity_id][$revision_id] : array();
  872. }
  873. }
  874. }
  875. }
  876. }
  877. catch (Exception $e) {
  878. watchdog('metatag', 'Error loading meta tag data, do the <a href="@update">database updates</a> need to be run? The error occurred when loading record(s) %ids for the %type entity type. The error message was: %error',
  879. array(
  880. '@update' => base_path() . 'update.php',
  881. '%ids' => implode(', ', array_keys($entities)),
  882. '%type' => $entity_type,
  883. '%error' => $e->getMessage(),
  884. ),
  885. WATCHDOG_WARNING);
  886. // Don't display the same message twice for Drush.
  887. if (drupal_is_cli()) {
  888. drupal_set_message(t('Run your updates, like drush updb.'));
  889. }
  890. // Only message people who can see it in watchdog and can likely fix it.
  891. elseif (user_access('access site reports')) {
  892. drupal_set_message(t('Error loading meta tag data, do the <a href="@update">database updates</a> need to be run?', array('@update' => base_path() . 'update.php')), 'error');
  893. }
  894. }
  895. }
  896. /**
  897. * Implements hook_entity_insert().
  898. */
  899. function metatag_entity_insert($entity, $entity_type) {
  900. if (isset($entity->metatags)) {
  901. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  902. // Verify that this entity type / bundle is supported.
  903. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  904. return;
  905. }
  906. $revision_id = intval($revision_id);
  907. // Determine the entity's language.
  908. $langcode = entity_language($entity_type, $entity);
  909. // Unfortunately due to how core works, the normal entity_language()
  910. // function returns 'und' instead of the node's language during node
  911. // creation.
  912. if ((empty($langcode) || $langcode == LANGUAGE_NONE) && !empty($entity->language)) {
  913. $langcode = $entity->language;
  914. }
  915. // If no language was still found, use the 'no language' value.
  916. if (empty($langcode)) {
  917. $langcode = LANGUAGE_NONE;
  918. }
  919. // Work-around for initial entity creation where a language was selection
  920. // but where it's different to the form's value.
  921. if (!isset($entity->metatags[$langcode]) && isset($entity->metatags[LANGUAGE_NONE])) {
  922. $entity->metatags[$langcode] = $entity->metatags[LANGUAGE_NONE];
  923. unset($entity->metatags[LANGUAGE_NONE]);
  924. }
  925. // Support for Workbench Moderation.
  926. if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
  927. return;
  928. }
  929. metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $bundle);
  930. }
  931. }
  932. /**
  933. * Implements hook_entity_update().
  934. */
  935. function metatag_entity_update($entity, $entity_type) {
  936. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  937. // If this entity object isn't allowed meta tags, don't continue.
  938. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  939. return;
  940. }
  941. $revision_id = intval($revision_id);
  942. if (isset($entity->metatags)) {
  943. // Determine the entity's new language. This will always be accurate as the
  944. // language value will already have been updated by the time this function
  945. // executes, and it will be loaded for the correct edit process.
  946. $new_language = metatag_entity_get_language($entity_type, $entity);
  947. // If applicable, determine the entity's original language. This cannot be
  948. // obtained via the normal API as that data will already have been updated,
  949. // instead check to see if the entity has an old-fasioned 'language' value.
  950. if (isset($entity->original) && isset($entity->language) && isset($entity->original->language)) {
  951. $old_language = $entity->original->language;
  952. // If the language has changed then additional checking needs to be done.
  953. // Need to compare against the entity's raw language value as they will
  954. // be different when updating a translated entity, versus an untranslated
  955. // entity or a source entity for translation, and give a false positive.
  956. if ($new_language == $entity->language && $new_language != $old_language) {
  957. // If this entity is not translated, or if it is translated but the
  958. // translation was previously created, then some language cleanup needs
  959. // to be done.
  960. if (!isset($entity->translation) || (isset($entity->translation) && !empty($entity->translation['created']))) {
  961. // Delete the old language record. This will not affect old revisions.
  962. db_delete('metatag')
  963. ->condition('entity_type', $entity_type)
  964. ->condition('entity_id', $entity_id)
  965. ->condition('revision_id', $revision_id)
  966. ->condition('language', $old_language)
  967. ->execute();
  968. // Swap out the metatag values for the two languages.
  969. if (isset($entity->metatags[$old_language])) {
  970. $entity->metatags[$new_language] = $entity->metatags[$old_language];
  971. unset($entity->metatags[$old_language]);
  972. }
  973. }
  974. }
  975. }
  976. // Support for Workbench Moderation.
  977. if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
  978. return;
  979. }
  980. // Save the record.
  981. metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $bundle);
  982. }
  983. else {
  984. // Still ensure the meta tag output is cached.
  985. metatag_metatags_cache_clear($entity_type, $entity_id);
  986. }
  987. }
  988. /**
  989. * Implements hook_entity_delete().
  990. */
  991. function metatag_entity_delete($entity, $entity_type) {
  992. list($entity_id) = entity_extract_ids($entity_type, $entity);
  993. metatag_metatags_delete($entity_type, $entity_id);
  994. }
  995. /**
  996. * Implements hook_field_attach_delete_revision().
  997. */
  998. function metatag_field_attach_delete_revision($entity_type, $entity) {
  999. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  1000. $revision_id = intval($revision_id);
  1001. metatag_metatags_delete($entity_type, $entity_id, $revision_id);
  1002. }
  1003. /**
  1004. * Build and alter metatag instance name.
  1005. *
  1006. * @param object $entity
  1007. * The entity object to generate the metatags instance name for.
  1008. * @param string $entity_type
  1009. * The entity type of the entity.
  1010. * @param string $bundle
  1011. * The bundle of the entity.
  1012. *
  1013. * @return string
  1014. * The resulting name of the config instance.
  1015. */
  1016. function metatag_get_entity_metatags_instance($entity, $entity_type, $bundle) {
  1017. $instance = "{$entity_type}:{$bundle}";
  1018. drupal_alter('metatag_get_entity_metatags_instance', $instance, $entity, $entity_type, $bundle);
  1019. return $instance;
  1020. }
  1021. /**
  1022. * Implements hook_entity_view().
  1023. *
  1024. * Provides additional argument to allow the display to be forced, to work
  1025. * around problems elsewhere in the APIs.
  1026. */
  1027. function metatag_entity_view($entity, $entity_type, $view_mode, $langcode, $force = FALSE) {
  1028. // Only run this function once per page load, for an entity which is allowed
  1029. // metatags.
  1030. static $i_will_say_this_only_once = FALSE;
  1031. // Only proceed if this entity object is the page being viewed.
  1032. if (_metatag_entity_is_page($entity_type, $entity)) {
  1033. // Get the entity's extra information.
  1034. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  1035. // If this entity object isn't allowed meta tags, don't continue.
  1036. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  1037. return;
  1038. }
  1039. // Some API calls need to force the data loading.
  1040. if (!$force) {
  1041. // Only run this function once per page load.
  1042. if ($i_will_say_this_only_once) {
  1043. return;
  1044. }
  1045. $i_will_say_this_only_once = TRUE;
  1046. }
  1047. // CTools uses 'page_manager' view mode to indicate the full entity display
  1048. // page rather than 'full', so streamline the internal processes.
  1049. if ($view_mode == 'page_manager') {
  1050. $view_mode = 'full';
  1051. }
  1052. // Generate metatags output.
  1053. if ($output = metatag_generate_entity_metatags($entity, $entity_type, $langcode, $view_mode)) {
  1054. $instance = metatag_get_entity_metatags_instance($entity, $entity_type, $bundle);
  1055. // We need to register the term's metatags, so we can later fetch them.
  1056. // @see metatag_page_build().
  1057. metatag_page_set_metatags($instance, $output);
  1058. }
  1059. }
  1060. }
  1061. /**
  1062. * Generate the metatags for a given entity.
  1063. *
  1064. * @param object $entity
  1065. * The entity object to generate the metatags for.
  1066. * @param string $entity_type
  1067. * The entity type of the entity.
  1068. * @param string $langcode
  1069. * The language code used for rendering the entity.
  1070. * @param string $view_mode
  1071. * The view mode the entity is rendered in.
  1072. * @param bool $cached
  1073. * TRUE if metatags can be loaded from and saved to the cache. FALSE if the
  1074. * cache should be bypassed.
  1075. *
  1076. * @return mixed
  1077. * A renderable array of metatags for the given entity.
  1078. * If this entity object isn't allowed meta tags, return FALSE (empty).
  1079. */
  1080. function metatag_generate_entity_metatags($entity, $entity_type, $langcode = NULL, $view_mode = 'full', $cached = TRUE) {
  1081. // Obtain some details of the entity that are needed elsewhere.
  1082. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  1083. // If this entity object isn't allowed meta tags, don't continue.
  1084. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  1085. return;
  1086. }
  1087. $revision_id = intval($revision_id);
  1088. // Check if a specific metatag config exists, otherwise just use the global
  1089. // one, stripping out the bundle.
  1090. $instance = metatag_get_entity_metatags_instance($entity, $entity_type, $bundle);
  1091. if (!metatag_config_load_with_defaults($instance, FALSE)) {
  1092. $instance = "{$entity_type}";
  1093. }
  1094. // Determine the language this entity actually uses.
  1095. $entity_language = metatag_entity_get_language($entity_type, $entity);
  1096. // If no language was requested, try the language defined for this page
  1097. // request.
  1098. if (empty($langcode)) {
  1099. $langcode = $GLOBALS['language_content']->language;
  1100. }
  1101. // This entity doesn't have any languages defined, i.e. it uses 'und'. This
  1102. // can't conflict with loading the wrong language as entities either have no
  1103. // language or they have specific one(s), they can't have both.
  1104. if ($entity_language == LANGUAGE_NONE) {
  1105. $langcode = LANGUAGE_NONE;
  1106. }
  1107. // If there are no meta tags for the currently identified language, and there
  1108. // *are* meta tags defined for the entity's default language, use the entity's
  1109. // default language's values, unless the "Don't load entity's default
  1110. // language values if no languages match" option is enabled on the advanced
  1111. // settings page.
  1112. elseif (empty($entity->metatags[$langcode]) && !empty($entity->metatags[$entity_language]) && !variable_get('metatag_entity_no_lang_default', FALSE)) {
  1113. $langcode = $entity_language;
  1114. }
  1115. // Other scenarios.
  1116. else {
  1117. // There's no need to do anything else - either there are meta tag values
  1118. // created for the requested language or there aren't.
  1119. }
  1120. $cid = FALSE;
  1121. $key = FALSE;
  1122. $metatag_variants = array();
  1123. // Caching is enabled.
  1124. if ($cached && variable_get('metatag_cache_output', FALSE)) {
  1125. // All possible variants of the metatags for this entity are stored in a
  1126. // single cache entry.
  1127. $cid = "output:$entity_type:$entity_id";
  1128. // All applicable pieces for this current page.
  1129. $key_parts = array(
  1130. 'entity_type' => $entity_type,
  1131. 'bundle' => $bundle,
  1132. 'entity_id' => $entity_id,
  1133. 'revision_id' => $revision_id,
  1134. // Cache separately based on the language of the passed-in entity and the
  1135. // overall active language of the page.
  1136. 'langcode' => $langcode,
  1137. 'language_content' => $GLOBALS['language_content']->language,
  1138. 'view_mode' => $view_mode,
  1139. );
  1140. $key = metatag_cache_default_cid_parts($key_parts);
  1141. if ($cache = metatag_cache_get($cid)) {
  1142. $metatag_variants = $cache->data;
  1143. }
  1144. }
  1145. // If a cached object exists for this key, return it.
  1146. if (!empty($key) && isset($metatag_variants[$key])) {
  1147. $output = $metatag_variants[$key];
  1148. }
  1149. // Otherwise, generate the output tags.
  1150. else {
  1151. // Separate the meta tags.
  1152. $metatags = isset($entity->metatags) ? $entity->metatags : array();
  1153. // Build options for meta tag rendering.
  1154. $options = array(
  1155. 'entity' => $entity,
  1156. 'entity_type' => $entity_type,
  1157. 'view_mode' => $view_mode,
  1158. );
  1159. // Ensure we actually pass a language object rather than language code.
  1160. $languages = language_list();
  1161. if (isset($languages[$langcode])) {
  1162. $options['language'] = $languages[$langcode];
  1163. }
  1164. // Include token replacement data. Don't reload the entity object as doing
  1165. // so would conflict with content editorial workflows.
  1166. if (!empty($entity_id)) {
  1167. $token_type = token_get_entity_mapping('entity', $entity_type);
  1168. $options['token data'][$token_type] = $entity;
  1169. }
  1170. // Render the metatags and save to the cache.
  1171. $output = metatag_metatags_view($instance, $metatags, $options);
  1172. // If output caching is enabled, store the data for later.
  1173. if (!empty($key) && !empty($cid)) {
  1174. $metatag_variants[$key] = $output;
  1175. metatag_cache_set($cid, $metatag_variants);
  1176. }
  1177. }
  1178. return $output;
  1179. }
  1180. /**
  1181. * Generate the metatags for a given entity.
  1182. *
  1183. * @param object $entity_id
  1184. * The entity id of the entity to generate the metatags for.
  1185. * @param string $entity_type
  1186. * The entity type of the entity to generate the metatags for.
  1187. * @param string $langcode
  1188. * The language code used for rendering the entity.
  1189. *
  1190. * @return array
  1191. * A renderable array of metatags for the given entity.
  1192. */
  1193. function metatags_get_entity_metatags($entity_id, $entity_type, $langcode = NULL) {
  1194. $entities = entity_load($entity_type, array($entity_id));
  1195. $entity = reset($entities);
  1196. return !empty($entity) ? metatag_generate_entity_metatags($entity, $entity_type, $langcode) : array();
  1197. }
  1198. /**
  1199. * Build a renderable array of meta tag output.
  1200. *
  1201. * @param string $instance
  1202. * The configuration instance key of the meta tags to use, e.g.
  1203. * "node:article".
  1204. * @param array $metatags
  1205. * An array of meta tag data.
  1206. * @param array $options
  1207. * (optional) An array of options including the following keys and values:
  1208. * - language: A language object.
  1209. * - token data: An array of data to pass into token_replace() during
  1210. * meta tag value generation.
  1211. */
  1212. function metatag_metatags_view($instance, array $metatags = array(), array $options = array()) {
  1213. $output = array();
  1214. // Convert language codes to a language object.
  1215. if (isset($options['language']) && is_string($options['language'])) {
  1216. $languages = language_list();
  1217. $options['language'] = isset($languages[$options['language']]) ? $languages[$options['language']] : NULL;
  1218. }
  1219. if (empty($options['language'])) {
  1220. $options['language'] = $GLOBALS['language_content'];
  1221. }
  1222. // If there are any tags, determine the translation to display.
  1223. if (!empty($metatags)) {
  1224. // Get the display language; default to the entity's language.
  1225. if (isset($options['language']) && isset($options['language']->language) && isset($metatags[$options['language']->language])) {
  1226. $metatags = $metatags[$options['language']->language];
  1227. }
  1228. // If no language requested, use the no-language value.
  1229. elseif (!empty($metatags[LANGUAGE_NONE])) {
  1230. $metatags = $metatags[LANGUAGE_NONE];
  1231. }
  1232. else {
  1233. $metatags = array();
  1234. }
  1235. }
  1236. // Add any default tags to the mix.
  1237. $metatags += metatag_config_load_with_defaults($instance);
  1238. $options['instance'] = $instance;
  1239. // Don't output meta tags that only contain the pager.
  1240. $current_pager = metatag_get_current_pager();
  1241. foreach ($metatags as $metatag => $data) {
  1242. if ((!empty($data['value']) || (isset($data['value']) && is_numeric($data['value'])))
  1243. && $metatag_instance = metatag_get_instance($metatag, $data)) {
  1244. $tag_output = $metatag_instance->getElement($options);
  1245. // Don't output the pager if that's all there is.
  1246. if ($tag_output != $current_pager) {
  1247. $output[$metatag] = $tag_output;
  1248. }
  1249. }
  1250. }
  1251. // Allow the output meta tags to be modified using
  1252. // hook_metatag_metatags_view_alter().
  1253. drupal_alter('metatag_metatags_view', $output, $instance, $options);
  1254. return $output;
  1255. }
  1256. /**
  1257. * Get the pager string for the current page.
  1258. *
  1259. * @return string
  1260. * Returns a string based upon the 'metatag_pager_string' variable and the
  1261. * current page number.
  1262. */
  1263. function metatag_get_current_pager() {
  1264. if (isset($_GET['page']) && !empty($_GET['page']) && is_numeric($_GET['page'])) {
  1265. $page = intval($_GET['page']) + 1;
  1266. if ($page > 1) {
  1267. $pager = variable_get('metatag_pager_string', 'Page PAGER | ');
  1268. return str_replace('PAGER', $page, $pager);
  1269. }
  1270. }
  1271. }
  1272. /**
  1273. * Returns metatags values.
  1274. */
  1275. function metatag_metatags_values($instance, array $metatags = array(), array $options = array()) {
  1276. $values = array();
  1277. // Apply defaults to the data for each language.
  1278. foreach ($metatags as $language => $metatag) {
  1279. $metatags[$language] += metatag_config_load_with_defaults($instance);
  1280. }
  1281. // Generate output only if we have a valid language.
  1282. if (isset($options['language']) && is_string($options['language']) && isset($metatags[$options['language']])) {
  1283. $language = $options['language'];
  1284. // Convert language codes to a language object.
  1285. $languages = language_list();
  1286. $options['language'] = isset($languages[$language]) ? $languages[$language] : NULL;
  1287. $options['instance'] = $instance;
  1288. // Get output elements.
  1289. foreach ($metatags[$language] as $metatag => $data) {
  1290. if ($metatag_instance = metatag_get_instance($metatag, $data)) {
  1291. $values[$metatag] = $metatag_instance->getValue($options);
  1292. }
  1293. }
  1294. }
  1295. return array_filter($values, 'drupal_strlen');
  1296. }
  1297. /**
  1298. * Build a FAPI array for editing meta tags.
  1299. *
  1300. * @param array $form
  1301. * The current FAPI array.
  1302. * @param string $instance
  1303. * The configuration instance key of the metatags to use, e.g. "node:article".
  1304. * @param array $metatags
  1305. * An array of metatag data.
  1306. * @param array $options
  1307. * (optional) An array of options including the following keys and values:
  1308. * - token types: An array of token types to be passed to theme_token_tree().
  1309. */
  1310. function metatag_metatags_form(array &$form, $instance, array $metatags = array(), array $options = array()) {
  1311. $info = metatag_get_info();
  1312. if (empty($info['tags'])) {
  1313. return;
  1314. }
  1315. // Work out the language code to use, default to NONE.
  1316. $langcode = LANGUAGE_NONE;
  1317. if (!empty($form['#entity_type'])) {
  1318. if (!empty($form['#entity'])) {
  1319. $langcode = metatag_entity_get_language($form['#entity_type'], $form['#entity']);
  1320. }
  1321. else {
  1322. $entity_info = entity_get_info($form['#entity_type']);
  1323. if (!empty($entity_info['token type'])) {
  1324. $entity_key = '#' . $entity_info['token type'];
  1325. if (!empty($form[$entity_key])) {
  1326. $langcode = metatag_entity_get_language($form['#entity_type'], $form[$entity_key]);
  1327. }
  1328. }
  1329. }
  1330. }
  1331. // Merge in the default options.
  1332. $options += array(
  1333. 'token types' => array(),
  1334. 'defaults' => metatag_config_load_with_defaults($instance),
  1335. 'instance' => $instance,
  1336. );
  1337. // Trigger hook_metatag_token_types_alter().
  1338. // Allow the defined tokens to be modified.
  1339. drupal_alter('metatag_token_types', $options);
  1340. $form['metatags'] = array(
  1341. '#type' => 'fieldset',
  1342. '#title' => t('Meta tags'),
  1343. '#collapsible' => TRUE,
  1344. '#collapsed' => TRUE,
  1345. '#multilingual' => TRUE,
  1346. '#tree' => TRUE,
  1347. '#access' => user_access('edit meta tags') || user_access('administer meta tags'),
  1348. '#weight' => 40,
  1349. '#language' => $langcode,
  1350. '#attributes' => array(
  1351. 'class' => array('metatags-form'),
  1352. ),
  1353. );
  1354. $form['metatags'][$langcode] = array(
  1355. '#metatag_defaults' => $options['defaults'],
  1356. '#type' => 'container',
  1357. '#multilingual' => TRUE,
  1358. '#tree' => TRUE,
  1359. );
  1360. // Show a different intro message for entity pages vs config pages.
  1361. if (isset($form['#entity'])) {
  1362. $form['metatags']['intro_text'] = array(
  1363. '#markup' => '<p>' . t('Configure the meta tags below. Tokens, e.g. "[node:summary]", automatically insert the corresponding information from that field or value, which helps to avoid redundant meta data and possible search engine penalization; see the "Browse available tokens" popup for more details.') . '</p>',
  1364. '#weight' => -10,
  1365. );
  1366. }
  1367. else {
  1368. $form['metatags']['intro_text'] = array(
  1369. '#markup' => '<p>' . t('Configure the meta tags below. Use tokens (see the "Browse available tokens" popup) to avoid redundant meta data and search engine penalization. For example, a \'keyword\' value of "example" will be shown on all content using this configuration, whereas using the [node:field_keywords] automatically inserts the "keywords" values from the current entity (node, term, etc).') . '</p>',
  1370. '#weight' => -10,
  1371. );
  1372. }
  1373. // Only support vertical tabs if there is a vertical tab element.
  1374. foreach (element_children($form) as $key) {
  1375. if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'vertical_tabs') {
  1376. $form['metatags']['#group'] = $key;
  1377. $form['metatags']['#attached']['js']['vertical-tabs'] = drupal_get_path('module', 'metatag') . '/metatag.vertical-tabs.js';
  1378. break;
  1379. }
  1380. }
  1381. // Merge in the default meta tag configurations.
  1382. $metatags += $options['defaults'];
  1383. // This will be used later.
  1384. $group_metatag_access = array();
  1385. // Build the form for each metatag.
  1386. foreach ($info['tags'] as $metatag => $metatag_info) {
  1387. // @todo Replace context matching with hook_metatag_access().
  1388. if (isset($options['context']) && isset($metatag_info['context'])) {
  1389. if (!in_array($options['context'], $metatag_info['context'])) {
  1390. continue;
  1391. }
  1392. }
  1393. $metatag_instance = metatag_get_instance($metatag, isset($metatags[$metatag]) ? $metatags[$metatag] : array());
  1394. if (empty($metatag_instance)) {
  1395. continue;
  1396. }
  1397. // Get the form element from the meta tag class.
  1398. $metatag_form = $metatag_instance->getForm($options);
  1399. if (isset($metatag_form['value']['#default_value']) && is_array($metatag_form['value']['#default_value'])) {
  1400. $metatag_form['value']['#default_value'] = array_filter($metatag_form['value']['#default_value']);
  1401. }
  1402. // Add a default value form element.
  1403. if (isset($options['defaults'][$metatag]['value'])) {
  1404. if (is_array($options['defaults'][$metatag]['value'])) {
  1405. $options['defaults'][$metatag]['value'] = array_filter($options['defaults'][$metatag]['value']);
  1406. }
  1407. $metatag_form['default'] = array(
  1408. '#type' => 'hidden',
  1409. '#value' => $options['defaults'][$metatag]['value'],
  1410. );
  1411. }
  1412. // Optional extended edit permissions.
  1413. if (variable_get('metatag_extended_permissions', FALSE)) {
  1414. $metatag_form['#access'] = user_access('edit meta tag: ' . $metatag) || user_access('administer meta tags');
  1415. }
  1416. else {
  1417. $metatag_form['#access'] = $form['metatags']['#access'];
  1418. }
  1419. if (!empty($metatag_info['group'])) {
  1420. $group_key = $metatag_info['group'];
  1421. if (isset($info['groups'][$group_key]['label']) && !isset($form['metatags'][$langcode][$group_key])) {
  1422. $group = $info['groups'][$group_key] + array('form' => array(), 'description' => NULL);
  1423. $form['metatags'][$langcode][$group_key] = $group['form'] + array(
  1424. '#type' => 'fieldset',
  1425. '#title' => $group['label'],
  1426. '#description' => !empty($group['description']) ? $group['description'] : '',
  1427. '#collapsible' => TRUE,
  1428. '#collapsed' => TRUE,
  1429. );
  1430. }
  1431. $form['metatags'][$langcode][$group_key][$metatag] = $metatag_form + array(
  1432. '#parents' => array('metatags', $langcode, $metatag),
  1433. );
  1434. // Hide the fieldset itself if there is not at least one of the meta tag
  1435. // fields visible.
  1436. if (variable_get('metatag_extended_permissions', FALSE)) {
  1437. $form['metatags'][$langcode][$group_key]['#access'] = count(element_get_visible_children($form['metatags'][$langcode][$group_key])) > 0;
  1438. }
  1439. else {
  1440. $form['metatags'][$langcode][$group_key]['#access'] = $form['metatags']['#access'];
  1441. }
  1442. // Structure the access parameter into this array, and make use of it
  1443. // later when we move on. Besides, this foreach is getting heavy.
  1444. $group_metatag_access[$group_key] = $form['metatags'][$langcode][$group_key]['#access'];
  1445. }
  1446. else {
  1447. $form['metatags'][$langcode][$metatag] = $metatag_form;
  1448. }
  1449. }
  1450. // Hide the fieldset itself if there is not at least one of the meta tag
  1451. // fields visible; only bother checking this if the user had edit access in
  1452. // the first place.
  1453. if ($form['metatags']['#access'] && variable_get('metatag_extended_permissions', FALSE)) {
  1454. $form['metatags']['#access'] = count(element_get_visible_children($form['metatags'][$langcode])) > 0;
  1455. }
  1456. // Check the #access of each group. If it passed, we display options for
  1457. // tokens. By this we update the #description of each group.
  1458. if ($form['metatags']['#access']) {
  1459. // Check if each meta tag group is being displayed.
  1460. if (!empty($group_metatag_access)) {
  1461. // Built the token browser link. For value "all" theme_token_tree()
  1462. // compares with string, not array.
  1463. if (in_array('all', $options['token types'])) {
  1464. $options['token types'] = 'all';
  1465. }
  1466. $token_listing_link = theme('token_tree',
  1467. array(
  1468. 'token_types' => $options['token types'],
  1469. 'dialog' => TRUE,
  1470. )
  1471. );
  1472. foreach ($group_metatag_access as $group_key => $token_access) {
  1473. if ($token_access) {
  1474. // Update the description.
  1475. if (isset($form['metatags'][$langcode][$group_key]['#description'])) {
  1476. $form['metatags'][$langcode][$group_key]['#description'] .= '<br />';
  1477. }
  1478. else {
  1479. $form['metatags'][$langcode][$group_key]['#description'] = '';
  1480. }
  1481. // Add the token browser popup link.
  1482. $form['metatags'][$langcode][$group_key]['#description'] .= $token_listing_link;
  1483. }
  1484. }
  1485. }
  1486. }
  1487. // Add a submit handler to compare the submitted values against the default
  1488. // values.
  1489. $form += array('#submit' => array());
  1490. if (module_exists('commerce') && isset($form['#entity_type']) && $form['#entity_type'] == 'commerce_product') {
  1491. $form['actions']['submit']['#submit'][] = 'metatag_commerce_product_form_submit';
  1492. }
  1493. else {
  1494. array_unshift($form['#submit'], 'metatag_metatags_form_submit');
  1495. }
  1496. }
  1497. /**
  1498. * Form API submission callback.
  1499. *
  1500. * Unset meta tag values that equal their default values, and load any
  1501. * additional meta tag values for other languages so that they can be properly
  1502. * saved later on.
  1503. *
  1504. * @see metatag_metatags_save()
  1505. */
  1506. function metatag_metatags_form_submit($form, &$form_state) {
  1507. if (!empty($form_state['values']['metatags'])) {
  1508. // Unset meta tag values that equal their default values.
  1509. foreach ($form_state['values']['metatags'] as $langcode => $values) {
  1510. if (!empty($form['metatags'][$langcode]['#metatag_defaults'])) {
  1511. metatag_filter_values_from_defaults($form_state['values']['metatags'][$langcode], $form['metatags'][$langcode]['#metatag_defaults']);
  1512. }
  1513. }
  1514. // Need to load the entity's values for other languages, otherwise they will
  1515. // be incorrectly deleted later on.
  1516. if (isset($form['#entity']) && !empty($form['#entity']->metatags)) {
  1517. foreach ($form['#entity']->metatags as $langcode => $values) {
  1518. if (!isset($form_state['values']['metatags'][$langcode])) {
  1519. $form_state['values']['metatags'][$langcode] = $values;
  1520. }
  1521. }
  1522. }
  1523. }
  1524. }
  1525. /**
  1526. * Form API submission callback for Commerce product.
  1527. *
  1528. * Unlike metatag_metatags_form_submit.
  1529. *
  1530. * @see metatag_metatags_save()
  1531. */
  1532. function metatag_commerce_product_form_submit($form, &$form_state) {
  1533. // Trigger the normal meta tag form submission.
  1534. metatag_metatags_form_submit($form, $form_state);
  1535. // The entity being saved.
  1536. $entity_type = 'commerce_product';
  1537. $product = $form_state[$entity_type];
  1538. $entity_id = $product->product_id;
  1539. $revision_id = $product->revision_id;
  1540. // Get the full entity details.
  1541. list(, , $bundle) = entity_extract_ids($entity_type, $product);
  1542. // Update the meta tags for this entity type.
  1543. metatag_metatags_save($entity_type, $entity_id, $revision_id, $form_state['values']['metatags'], $bundle);
  1544. }
  1545. /**
  1546. * Implements hook_field_extra_fields().
  1547. */
  1548. function metatag_field_extra_fields() {
  1549. $extra = array();
  1550. foreach (entity_get_info() as $entity_type => $entity_info) {
  1551. if (!empty($entity_info['bundles'])) {
  1552. foreach (array_keys($entity_info['bundles']) as $bundle) {
  1553. if (metatag_entity_supports_metatags($entity_type, $bundle)) {
  1554. $extra[$entity_type][$bundle]['form']['metatags'] = array(
  1555. 'label' => t('Meta tags'),
  1556. 'description' => t('Meta tag module form elements.'),
  1557. 'weight' => 40,
  1558. );
  1559. }
  1560. }
  1561. }
  1562. }
  1563. return $extra;
  1564. }
  1565. /**
  1566. * Check whether the requested entity type (and bundle) support metatag.
  1567. *
  1568. * By default the entities are disabled, only certain entities will have been
  1569. * enabled during installation. If an entity type is enabled it is assumed that
  1570. * the entity bundles will also be enabled by default.
  1571. *
  1572. * @see metatag_entity_type_is_suitable()
  1573. */
  1574. function metatag_entity_supports_metatags($entity_type = NULL, $bundle = NULL) {
  1575. $entity_types = &drupal_static(__FUNCTION__);
  1576. // Identify which entities & bundles are supported the first time the
  1577. // function is called.
  1578. if (!isset($entity_types)) {
  1579. foreach (entity_get_info() as $entity_name => $entity_info) {
  1580. // Verify that this entity type is suitable.
  1581. $entity_types[$entity_name] = metatag_entity_type_is_suitable($entity_name, $entity_info);
  1582. // The entity type technically supports entities.
  1583. if (!empty($entity_types[$entity_name])) {
  1584. // Entiy types are enabled by default.
  1585. // Allow entities to be disabled by assigning a variable
  1586. // 'metatag_enable_{$entity_type}' the value FALSE, e.g.:
  1587. //
  1588. // // Disable metatags for file_entity.
  1589. // $conf['metatag_enable_file'] = FALSE;
  1590. //
  1591. // @see Settings page.
  1592. if (variable_get('metatag_enable_' . $entity_name, FALSE) == FALSE) {
  1593. $entity_types[$entity_name] = FALSE;
  1594. }
  1595. // Check each bundle.
  1596. else {
  1597. $entity_types[$entity_name] = array();
  1598. foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
  1599. // If only one bundle exists, take configuration for entity, to
  1600. // reflect options as they are available in the UI.
  1601. if (count($entity_info['bundles']) === 1) {
  1602. $entity_types[$entity_name][$bundle_name] = variable_get('metatag_enable_' . $entity_name, FALSE) == TRUE;
  1603. continue;
  1604. }
  1605. // Allow bundles to be disabled by assigning a variable
  1606. // 'metatag_enable_{$entity_type}__{$bundle}' the value FALSE, e.g.:
  1607. //
  1608. // // Disable metatags for carousel nodes.
  1609. // $conf['metatag_enable_node__carousel'] = FALSE;
  1610. //
  1611. // @see Settings page.
  1612. if (variable_get('metatag_enable_' . $entity_name . '__' . $bundle_name, TRUE) == FALSE) {
  1613. $entity_types[$entity_name][$bundle_name] = FALSE;
  1614. }
  1615. else {
  1616. $entity_types[$entity_name][$bundle_name] = TRUE;
  1617. }
  1618. }
  1619. }
  1620. }
  1621. }
  1622. }
  1623. // It was requested to check a specific entity.
  1624. if (isset($entity_type)) {
  1625. // It was also requested to check a specific bundle for this entity.
  1626. if (isset($bundle)) {
  1627. $supported = !empty($entity_types[$entity_type][$bundle]);
  1628. }
  1629. // Check the entity.
  1630. else {
  1631. $supported = !empty($entity_types[$entity_type]);
  1632. }
  1633. return $supported;
  1634. }
  1635. // If nothing specific was requested, return the complete list of supported
  1636. // entities & bundles.
  1637. return $entity_types;
  1638. }
  1639. /**
  1640. * Enable support for a specific entity type if setting does not exist.
  1641. *
  1642. * @param string $entity_type
  1643. * The entity type.
  1644. * @param string $bundle
  1645. * The bundle of the entity.
  1646. * @param bool $force_enable
  1647. * If TRUE, then the type is enabled regardless of any stored variables.
  1648. *
  1649. * @return bool
  1650. * TRUE if either the bundle or entity type was enabled by this function.
  1651. */
  1652. function metatag_entity_type_enable($entity_type, $bundle = NULL, $force_enable = FALSE) {
  1653. // The bundle was defined.
  1654. $bundle_set = FALSE;
  1655. if (isset($bundle)) {
  1656. $stored_bundle = variable_get('metatag_enable_' . $entity_type . '__' . $bundle, NULL);
  1657. if ($force_enable || !isset($stored_bundle)) {
  1658. variable_set('metatag_enable_' . $entity_type . '__' . $bundle, TRUE);
  1659. $bundle_set = TRUE;
  1660. }
  1661. }
  1662. // Always enable the entity type, because otherwise there's no point in
  1663. // enabling the bundle.
  1664. $entity_type_set = FALSE;
  1665. $stored_entity_type = variable_get('metatag_enable_' . $entity_type, NULL);
  1666. if ($force_enable || !isset($stored_entity_type)) {
  1667. variable_set('metatag_enable_' . $entity_type, TRUE);
  1668. $entity_type_set = TRUE;
  1669. }
  1670. // Clear the static cache so that the entity type / bundle will work.
  1671. drupal_static_reset('metatag_entity_supports_metatags');
  1672. return $bundle_set || $entity_type_set;
  1673. }
  1674. /**
  1675. * Disable support for a specific entity type.
  1676. *
  1677. * @param string $entity_type
  1678. * The entity type.
  1679. * @param string $bundle
  1680. * The bundle of the entity.
  1681. */
  1682. function metatag_entity_type_disable($entity_type, $bundle = NULL) {
  1683. // The bundle was defined.
  1684. if (isset($bundle)) {
  1685. variable_set('metatag_enable_' . $entity_type . '__' . $bundle, FALSE);
  1686. }
  1687. // The bundle was not defined.
  1688. else {
  1689. variable_set('metatag_enable_' . $entity_type, FALSE);
  1690. }
  1691. // Clear the static cache so that the entity type / bundle will work.
  1692. drupal_static_reset('metatag_entity_supports_metatags');
  1693. }
  1694. /**
  1695. * Add meta tags to be added later with metatag_page_build().
  1696. *
  1697. * @param string $instance
  1698. * The configuration instance key of the meta tags, e.g. "node:article".
  1699. * @param array $metatags
  1700. * An array of meta tags from metatag_metatags_view().
  1701. */
  1702. function metatag_page_set_metatags($instance, $metatags) {
  1703. $page_metatags = &drupal_static(__FUNCTION__, array());
  1704. $page_metatags[$instance] = $metatags;
  1705. }
  1706. /**
  1707. * Retrieve the array of meta tags to be added with metatag_page_build().
  1708. */
  1709. function metatag_page_get_metatags() {
  1710. // @todo Add alter to this result?
  1711. return drupal_static('metatag_page_set_metatags', array());
  1712. }
  1713. /**
  1714. * Implements hook_page_build().
  1715. */
  1716. function metatag_page_build(&$page) {
  1717. // By default do not add meta tags to admin pages. To enable meta tags on
  1718. // admin pages set the 'metatag_tag_admin_pages' variable to TRUE.
  1719. if (path_is_admin(current_path()) && !variable_get('metatag_tag_admin_pages', FALSE)) {
  1720. return;
  1721. }
  1722. // Special consideration for the Me module, which uses the "user/me" path and
  1723. // will cause problems.
  1724. if (arg(0) == 'user' && arg(1) == 'me' && function_exists('me_menu_alter')) {
  1725. return;
  1726. }
  1727. // The page region can be changed.
  1728. $region = variable_get('metatag_page_region', 'content');
  1729. // Ensure these arrays exist, otherwise several use cases will fail.
  1730. if (!isset($page[$region]) || !is_array($page[$region])) {
  1731. $page[$region] = array();
  1732. }
  1733. if (!isset($page[$region]['metatags']) || !is_array($page[$region]['metatags'])) {
  1734. $page[$region]['metatags'] = array();
  1735. }
  1736. // The front page has special consideration. Also, check if this is an error
  1737. // (403/404) page, those also require separate handling.
  1738. $instance = 'global:frontpage';
  1739. if ((drupal_is_front_page() && metatag_config_is_enabled($instance))
  1740. || ($instance = metatag_is_error_page())) {
  1741. // Generate the cache ID.
  1742. $cid_parts = array(
  1743. 'instance' => $instance,
  1744. );
  1745. $cid = metatag_cache_default_cid_parts($cid_parts);
  1746. if ($cache = metatag_cache_get($cid)) {
  1747. $metatags = $cache->data;
  1748. }
  1749. else {
  1750. $metatags = metatag_metatags_view($instance, array());
  1751. // If output caching is enabled, save this for later.
  1752. if (variable_get('metatag_cache_output', FALSE)) {
  1753. metatag_cache_set($cid, $metatags);
  1754. }
  1755. }
  1756. $page[$region]['metatags'][$instance] = $metatags;
  1757. }
  1758. // Load any meta tags assigned via metatag_page_set_metatags(). Note: this
  1759. // must include the necessary defaults.
  1760. else {
  1761. $page[$region]['metatags'] += metatag_page_get_metatags();
  1762. }
  1763. // If no meta tags were loaded at least load the global defaults. This may be
  1764. // disabled, see README.txt for details.
  1765. if (empty($page[$region]['metatags']) && variable_get('metatag_load_all_pages', TRUE)) {
  1766. $instance = 'global';
  1767. // Generate the cache ID.
  1768. $cid_parts = array(
  1769. 'instance' => $instance,
  1770. 'path' => request_path(),
  1771. );
  1772. $cid = metatag_cache_default_cid_parts($cid_parts);
  1773. if ($cache = metatag_cache_get($cid)) {
  1774. $metatags = $cache->data;
  1775. }
  1776. else {
  1777. $metatags = metatag_metatags_view($instance, array());
  1778. // If output caching is enabled, save this for later.
  1779. if (variable_get('metatag_cache_output', FALSE)) {
  1780. metatag_cache_set($cid, $metatags);
  1781. }
  1782. }
  1783. $page[$region]['metatags'][$instance] = $metatags;
  1784. }
  1785. }
  1786. /**
  1787. * Returns whether the current page is the page of the passed in entity.
  1788. *
  1789. * @param string $entity_type
  1790. * The entity type; e.g. 'node' or 'user'.
  1791. * @param object $entity
  1792. * The entity object.
  1793. *
  1794. * @return mixed
  1795. * TRUE if the current page is the page of the specified entity, or FALSE
  1796. * otherwise. If $entity_type == 'comment' return empty (FALSE).
  1797. */
  1798. function _metatag_entity_is_page($entity_type, $entity) {
  1799. // Exclude comment entities as this conflicts with comment_fragment.module.
  1800. if ($entity_type == 'comment') {
  1801. return;
  1802. }
  1803. $uri = entity_uri($entity_type, $entity);
  1804. $current_path = current_path();
  1805. // Support for Workbench Moderation - if this is a node, check if the content
  1806. // type supports moderation.
  1807. if ($entity_type == 'node' && function_exists('workbench_moderation_node_type_moderated') && workbench_moderation_node_type_moderated($entity->type) === TRUE) {
  1808. return !empty($uri['path']) && ($current_path == $uri['path'] || $current_path == $uri['path'] . '/draft');
  1809. }
  1810. // Support for core node revisions.
  1811. elseif (!empty($uri['path']) && strpos($current_path, $uri['path']) === 0 && strpos($current_path, '/revisions/') && strpos($current_path, '/view')) {
  1812. return TRUE;
  1813. }
  1814. // Any other page.
  1815. else {
  1816. return !empty($uri['path']) && $current_path == $uri['path'];
  1817. }
  1818. }
  1819. /**
  1820. * Implements hook_field_attach_rename_bundle().
  1821. */
  1822. function metatag_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  1823. $instance_old = $entity_type . ':' . $bundle_old;
  1824. $instance_new = $entity_type . ':' . $bundle_new;
  1825. if ($config = metatag_config_load($instance_old)) {
  1826. $config->instance = $instance_new;
  1827. metatag_config_save($config);
  1828. $config->instance = $instance_old;
  1829. metatag_config_delete($config);
  1830. }
  1831. }
  1832. /**
  1833. * Implements hook_field_attach_delete_bundle().
  1834. */
  1835. function metatag_field_attach_delete_bundle($entity_type, $bundle) {
  1836. $instance = $entity_type . ':' . $bundle;
  1837. if ($config = metatag_config_load($instance)) {
  1838. metatag_config_delete($config);
  1839. }
  1840. }
  1841. /**
  1842. * Implements hook_field_attach_form().
  1843. */
  1844. function metatag_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  1845. // Entity_Translation will trigger this hook again, skip it.
  1846. if (!empty($form_state['entity_translation']['is_translation'])) {
  1847. return;
  1848. }
  1849. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  1850. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  1851. return;
  1852. }
  1853. $instance = metatag_get_entity_metatags_instance($entity, $entity_type, $bundle);
  1854. // Grab the meta tags for display in the form if there are any.
  1855. if (!empty($entity->metatags)) {
  1856. // Identify the language to use with this entity.
  1857. $entity_language = metatag_entity_get_language($entity_type, $entity);
  1858. // If this is a new translation using Entity Translation, load the meta
  1859. // tags from the entity's original language.
  1860. if (module_exists('entity_translation') && empty($form['#entity_translation_source_form']) && ($handler = entity_translation_entity_form_get_handler($form, $form_state)) && isset($entity->metatags[$handler->getSourceLanguage()])) {
  1861. $metatags = $entity->metatags[$handler->getSourceLanguage()];
  1862. }
  1863. // Determine from where we should get the tags.
  1864. elseif (isset($entity->metatags[$langcode])) {
  1865. // Set the tags to the translation set matching that of the form.
  1866. $metatags = $entity->metatags[$langcode];
  1867. }
  1868. // There is no translation for this entity's tags in the current
  1869. // language. Instead, display tags in the language of the entity, the
  1870. // source language of translations. The will provide translators with the
  1871. // original text to translate.
  1872. elseif (isset($entity->metatags[$entity_language])) {
  1873. $metatags = $entity->metatags[$entity_language];
  1874. }
  1875. // This is a preview so set the tags to the raw submission data. No
  1876. // language has been set.
  1877. else {
  1878. $metatags = $entity->metatags;
  1879. }
  1880. }
  1881. else {
  1882. $metatags = array();
  1883. }
  1884. // Certain circumstances can result in $metatags not being an array.
  1885. if (!is_array($metatags)) {
  1886. $metatags = array();
  1887. }
  1888. $options['token types'] = array(
  1889. token_get_entity_mapping('entity', $entity_type),
  1890. );
  1891. $options['context'] = $entity_type;
  1892. // @todo Remove metatag_form_alter() when https://www.drupal.org/node/1284642 is fixed in core.
  1893. // metatag_metatags_form($form, $instance, $metatags, $options);
  1894. $form['#metatags'] = array(
  1895. 'instance' => $instance,
  1896. 'metatags' => $metatags,
  1897. 'options' => $options,
  1898. );
  1899. }
  1900. /**
  1901. * Implements hook_form_alter().
  1902. *
  1903. * @todo Remove this when https://www.drupal.org/node/1284642 is fixed in core.
  1904. */
  1905. function metatag_form_alter(&$form, $form_state, $form_id) {
  1906. if (!empty($form['#metatags']) && !isset($form['metatags'])) {
  1907. extract($form['#metatags']);
  1908. metatag_metatags_form($form, $instance, $metatags, $options);
  1909. unset($form['#metatags']);
  1910. }
  1911. }
  1912. /**
  1913. * Get the meta tag information array of a meta tag.
  1914. *
  1915. * @param string $name
  1916. * The meta tag name, e.g. description, for which the info shall be returned,
  1917. * or NULL to return an array with info about all meta tags.
  1918. */
  1919. function metatag_get_info($type = NULL, $name = NULL) {
  1920. // Use the advanced drupal_static() pattern, since this is called very often.
  1921. static $drupal_static_fast;
  1922. if (!isset($drupal_static_fast)) {
  1923. $drupal_static_fast['metatag_info'] = &drupal_static(__FUNCTION__);
  1924. }
  1925. $info = &$drupal_static_fast['metatag_info'];
  1926. global $language;
  1927. if (!isset($info)) {
  1928. // hook_metatag_info() includes translated strings, so each language is
  1929. // cached separately.
  1930. $cid = 'info:' . $language->language;
  1931. if ($cache = metatag_cache_get($cid)) {
  1932. $info = $cache->data;
  1933. }
  1934. else {
  1935. // Obtain all metatag specs defined in other modules using
  1936. // hook_metatag_info().
  1937. $info = module_invoke_all('metatag_info');
  1938. $info += array('tags' => array(), 'groups' => array());
  1939. // Merge in default values.
  1940. foreach ($info['tags'] as $key => $data) {
  1941. $info['tags'][$key] += array(
  1942. // Merge in default values.
  1943. 'name' => $key,
  1944. 'class' => 'DrupalTextMetaTag',
  1945. );
  1946. }
  1947. // Let other modules alter the entity info using
  1948. // hook_metatag_info_alter().
  1949. drupal_alter('metatag_info', $info);
  1950. metatag_cache_set($cid, $info);
  1951. }
  1952. }
  1953. if (isset($type) && isset($name)) {
  1954. return isset($info[$type][$name]) ? $info[$type][$name] : FALSE;
  1955. }
  1956. elseif (isset($type)) {
  1957. return isset($info[$type]) ? $info[$type] : array();
  1958. }
  1959. else {
  1960. return $info;
  1961. }
  1962. }
  1963. /**
  1964. * Return instance of metatag.
  1965. */
  1966. function metatag_get_instance($metatag, array $data = array()) {
  1967. $info = metatag_get_info('tags', $metatag);
  1968. if (!empty($info['class']) && class_exists($info['class'])) {
  1969. $class = $info['class'];
  1970. return new $class($info, $data);
  1971. }
  1972. }
  1973. /**
  1974. * Return the string value of a meta tag.
  1975. *
  1976. * @param string $metatag
  1977. * The meta tag string.
  1978. * @param array $data
  1979. * The array of data for the meta tag class instance.
  1980. * @param array $options
  1981. * An optional array of additional options to pass to the getValue() method
  1982. * of the meta tag class instance.
  1983. * - raw: A boolean if TRUE will not perform token replacement.
  1984. *
  1985. * @return string
  1986. * A string value.
  1987. */
  1988. function metatag_get_value($metatag, array $data, array $options = array()) {
  1989. $value = '';
  1990. if ($metatag_instance = metatag_get_instance($metatag, $data)) {
  1991. $options["instance"] = $metatag;
  1992. $value = $metatag_instance->getValue($options);
  1993. if (is_array($value)) {
  1994. $value = implode(', ', $value);
  1995. }
  1996. }
  1997. return $value;
  1998. }
  1999. /**
  2000. * Set a variable to be altered in metatag_preprocess_html().
  2001. *
  2002. * @see metatag_get_preprocess_variables()
  2003. * @see metatag_preprocess_html()
  2004. * @see metatag_preprocess_maintenance_page()
  2005. */
  2006. function metatag_set_preprocess_variable($hook, $variable, $value) {
  2007. $variables = &drupal_static(__FUNCTION__, array());
  2008. $variables[$hook][$variable] = $value;
  2009. }
  2010. /**
  2011. * Return an array of variables to be altered in preprocess functions.
  2012. *
  2013. * @see metatag_set_preprocess_variable()
  2014. * @see metatag_preprocess_html()
  2015. * @see metatag_preprocess_maintenance_page()
  2016. */
  2017. function metatag_get_preprocess_variables($hook) {
  2018. $variables = drupal_static('metatag_set_preprocess_variable', array());
  2019. return isset($variables[$hook]) ? $variables[$hook] : array();
  2020. }
  2021. /**
  2022. * Implements hook_preprocess_html().
  2023. */
  2024. function metatag_preprocess_html(&$variables) {
  2025. foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
  2026. $variables[$variable] = $value;
  2027. }
  2028. }
  2029. /**
  2030. * Implements hook_preprocess_maintenance_page().
  2031. */
  2032. function metatag_preprocess_maintenance_page(&$variables) {
  2033. foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
  2034. $variables[$variable] = $value;
  2035. }
  2036. }
  2037. /**
  2038. * Implements hook_html_head_alter().
  2039. *
  2040. * Hide tags added by core that are now handled by metatag.
  2041. */
  2042. function metatag_html_head_alter(&$elements) {
  2043. $metatags = array();
  2044. $other_tags = array();
  2045. foreach ($elements as $key => $data) {
  2046. // Identify meta tags added by the Metatag module.
  2047. if (strpos($key, 'metatag_') === 0) {
  2048. $metatags[] = $key;
  2049. }
  2050. // Identify meta tags added by other modules.
  2051. else {
  2052. $other_tags[] = $key;
  2053. }
  2054. }
  2055. // The meta tag keys to look for.
  2056. $metatag_keys = array('name', 'property');
  2057. // Attributes to look for.
  2058. $attributes = array('name', 'rel');
  2059. // Look for meta tags that were added by other modules and hide them.
  2060. foreach ($metatags as $metatag_name) {
  2061. $metatag = &$elements[$metatag_name];
  2062. // Setting the #access attribute to these will stop them from being output
  2063. // but still leave the tags present for other modules to interact with.
  2064. foreach ($other_tags as $other_tag) {
  2065. $other = &$elements[$other_tag];
  2066. // Look for other meta tags that have one of the defined attributes which
  2067. // matches one of the values from Metatag's tag.
  2068. foreach ($attributes as $attribute) {
  2069. if (isset($other['#attributes'], $other['#attributes'][$attribute]) && is_string($other['#attributes'][$attribute])) {
  2070. foreach ($metatag_keys as $metatag_key) {
  2071. if (isset($metatag[$metatag_key])) {
  2072. if (strtolower($other['#attributes'][$attribute]) == $metatag[$metatag_key]) {
  2073. $other['#access'] = FALSE;
  2074. }
  2075. }
  2076. }
  2077. }
  2078. }
  2079. }
  2080. }
  2081. // If the 'leave core tags' option is disabled then the following meta tags
  2082. // will be removed if they're provided by core.
  2083. if (!variable_get('metatag_leave_core_tags', FALSE)) {
  2084. $core_tags = array(
  2085. 'generator',
  2086. 'canonical',
  2087. 'shortlink',
  2088. // Leave the shortcut icon, that's more of a theming thing.
  2089. // 'shortcut icon',.
  2090. );
  2091. foreach ($elements as $name => &$element) {
  2092. // Ignore meta tags provided by Metatag.
  2093. if (strpos($name, 'metatag_') === 0) {
  2094. continue;
  2095. }
  2096. // Setting the #access attribute to these will stop them from being output
  2097. // but still leave the tags present for other modules to interact with.
  2098. foreach ($core_tags as $tag) {
  2099. if (!empty($element['#attributes']['rel']) && $element['#attributes']['rel'] == $tag) {
  2100. $element['#access'] = FALSE;
  2101. }
  2102. elseif (!empty($element['#attributes']['name']) && strtolower($element['#attributes']['name']) == $tag) {
  2103. $element['#access'] = FALSE;
  2104. }
  2105. }
  2106. }
  2107. }
  2108. }
  2109. /**
  2110. * Implements hook_get_form().
  2111. */
  2112. function metatag_metatag_get_form($metatag, array $data = array(), array $options = array()) {
  2113. $instance = metatag_get_instance($metatag, $data);
  2114. return $instance->getForm($options);
  2115. }
  2116. /**
  2117. * Returns Instance info if exists otherwise return FALSE.
  2118. */
  2119. function metatag_config_instance_info($instance = NULL) {
  2120. global $language;
  2121. $info = &drupal_static(__FUNCTION__);
  2122. // hook_metatag_info() includes translated strings, so each language is cached
  2123. // separately.
  2124. $cid = 'metatag:config:instance:info:' . $language->language;
  2125. if (!isset($info)) {
  2126. if ($cache = metatag_cache_get($cid)) {
  2127. $info = $cache->data;
  2128. }
  2129. else {
  2130. // Allow modules to act upon the record insertion using
  2131. // hook_metatag_config_instance_info().
  2132. $info = module_invoke_all('metatag_config_instance_info');
  2133. // Allow other modules to customize the data using
  2134. // hook_metatag_config_instance_info_alter().
  2135. drupal_alter('metatag_config_instance_info', $info);
  2136. metatag_cache_set($cid, $info);
  2137. }
  2138. }
  2139. if (isset($instance)) {
  2140. return isset($info[$instance]) ? $info[$instance] : FALSE;
  2141. }
  2142. else {
  2143. return $info;
  2144. }
  2145. }
  2146. /**
  2147. * Filter out meta tag values that equal the default values.
  2148. *
  2149. * @todo Use information in $values[$metatag]['default'] rather than a $defaults parameter.
  2150. */
  2151. function metatag_filter_values_from_defaults(array &$values, array $defaults = array()) {
  2152. foreach ($values as $metatag => $data) {
  2153. $default = isset($data['default']) ? $data['default'] : (isset($defaults[$metatag]['value']) ? $defaults[$metatag]['value'] : NULL);
  2154. if (isset($default) && isset($data['value']) && $default === $data['value']) {
  2155. // Meta tag has a default, and it matches user-submitted value.
  2156. unset($values[$metatag]);
  2157. }
  2158. elseif (!isset($default) && (is_string($data['value']) && !drupal_strlen($data['value']) || (is_array($data['value']) && !array_filter($data['value'])))) {
  2159. // Metatag does not have a default, and user did not submit a value.
  2160. unset($values[$metatag]);
  2161. }
  2162. if (isset($values[$metatag]['default'])) {
  2163. // Unset the default hidden value.
  2164. unset($values[$metatag]['default']);
  2165. }
  2166. }
  2167. }
  2168. /**
  2169. * Return all the parents of a given configuration instance.
  2170. *
  2171. * @param string $instance
  2172. * A meta tag configuration instance.
  2173. *
  2174. * @return array
  2175. * An array of instances starting with the $instance parameter, with the end
  2176. * of the array being the global instance.
  2177. */
  2178. function metatag_config_get_parent_instances($instance, $include_global = TRUE) {
  2179. $parents = array();
  2180. $segments = explode(':', $instance);
  2181. while (count($segments) > 0) {
  2182. $parents[] = implode(':', $segments);
  2183. array_pop($segments);
  2184. }
  2185. if ($include_global && end($parents) !== 'global') {
  2186. $parents[] = 'global';
  2187. }
  2188. reset($parents);
  2189. return $parents;
  2190. }
  2191. /**
  2192. * Get the proper label of a configuration instance.
  2193. *
  2194. * @param string $instance
  2195. * A meta tag configuration instance.
  2196. */
  2197. function metatag_config_instance_label($instance) {
  2198. $labels = &drupal_static(__FUNCTION__, array());
  2199. if (!isset($labels[$instance])) {
  2200. $instance_parts = explode(':', $instance);
  2201. $instance_part = array_pop($instance_parts);
  2202. if ($context = metatag_config_instance_info($instance)) {
  2203. $labels[$instance] = $context['label'];
  2204. }
  2205. else {
  2206. $labels[$instance] = t('Unknown (@instance)', array('@instance' => $instance_part));
  2207. }
  2208. // Normally the following would use metatag_config_get_parent_instances()
  2209. // but since we already sliced the instance by separator and removed the
  2210. // last segment, putting the array back together gives us this instance's
  2211. // parent.
  2212. if (!empty($instance_parts)) {
  2213. $labels[$instance] = metatag_config_instance_label(implode(':', $instance_parts)) . ': ' . $labels[$instance];
  2214. }
  2215. }
  2216. return $labels[$instance];
  2217. }
  2218. /**
  2219. * Title callback for meta tag configuration instances.
  2220. */
  2221. function metatag_config_title($config) {
  2222. return metatag_config_instance_label($config->instance);
  2223. }
  2224. /**
  2225. * Access callback for meta tag configuration instances.
  2226. */
  2227. function metatag_config_access($op, $config = NULL) {
  2228. if (!user_access('administer meta tags')) {
  2229. return FALSE;
  2230. }
  2231. if ($op == 'enable') {
  2232. return !empty($config->disabled);
  2233. }
  2234. elseif ($op == 'disable') {
  2235. return empty($config->disabled);
  2236. }
  2237. elseif ($op == 'delete') {
  2238. return ($config->export_type & EXPORT_IN_DATABASE) && !($config->export_type & EXPORT_IN_CODE);
  2239. }
  2240. elseif ($op == 'revert') {
  2241. return ($config->export_type & EXPORT_IN_DATABASE) && ($config->export_type & EXPORT_IN_CODE);
  2242. }
  2243. return FALSE;
  2244. }
  2245. /**
  2246. * Checks if a metatag configuration record is enabled.
  2247. *
  2248. * @param string $instance
  2249. * The configuration instance machine name.
  2250. *
  2251. * @return bool
  2252. * TRUE if the configuration is enabled, or FALSE otherwise.
  2253. */
  2254. function metatag_config_is_enabled($instance, $include_defaults = FALSE, $include_global = TRUE) {
  2255. if ($include_defaults) {
  2256. $instances = metatag_config_get_parent_instances($instance, $include_global);
  2257. $configs = metatag_config_load_multiple($instances);
  2258. // Check if one of the configs is enabled.
  2259. foreach ($configs as $config) {
  2260. if (empty($config->disabled)) {
  2261. return TRUE;
  2262. }
  2263. }
  2264. // No enabled configs found.
  2265. return FALSE;
  2266. }
  2267. else {
  2268. $config = metatag_config_load($instance);
  2269. return !empty($config) && empty($config->disabled);
  2270. }
  2271. }
  2272. /**
  2273. * Wrapper around entity_language().
  2274. *
  2275. * @param mixed $entity_type
  2276. * An entity type's machine name.
  2277. * @param object $entity
  2278. * The entity to review; will be typecast to an object if an array is passed.
  2279. *
  2280. * @return string
  2281. * A string indicating the language code to be used; returns LANGUAGE_NONE if
  2282. * the entity does not have a language assigned.
  2283. */
  2284. function metatag_entity_get_language($entity_type, $entity) {
  2285. // Determine the entity's language, af.
  2286. $langcode = entity_language($entity_type, (object) $entity);
  2287. // If no matching language was found, which will happen for e.g. terms and
  2288. // users, it is normally recommended to use the system default language.
  2289. // However, as the system default language can change, this could potentially
  2290. // cause data loss / confusion problems; as a result use the system "no
  2291. // language" value to avoid any potential problems.
  2292. if (empty($langcode)) {
  2293. $langcode = LANGUAGE_NONE;
  2294. }
  2295. return $langcode;
  2296. }
  2297. /**
  2298. * Implements hook_features_api().
  2299. */
  2300. function metatag_features_api() {
  2301. $components = array(
  2302. 'metatag' => array(
  2303. 'name' => t('Metatag'),
  2304. 'feature_source' => TRUE,
  2305. 'default_hook' => 'metatag_export_default',
  2306. 'default_file' => FEATURES_DEFAULTS_INCLUDED,
  2307. 'file' => drupal_get_path('module', 'metatag') . '/metatag.features.inc',
  2308. ),
  2309. );
  2310. return $components;
  2311. }
  2312. /**
  2313. * Implements hook_views_post_render().
  2314. *
  2315. * Try loading meta tags from a Views page display.
  2316. */
  2317. function metatag_views_post_render(&$view, &$output, &$cache) {
  2318. // By default do not add meta tags to admin pages. To enable meta tags on
  2319. // admin pages set the 'metatag_tag_admin_pages' variable to TRUE.
  2320. if (path_is_admin(current_path()) && !variable_get('metatag_tag_admin_pages', FALSE)) {
  2321. return;
  2322. }
  2323. // If display is not set for some reason, get out to prevent PHP notices.
  2324. if (!isset($view->display[$view->current_display])) {
  2325. return;
  2326. }
  2327. // Build a shortcut to the current display object.
  2328. $display = $view->display[$view->current_display];
  2329. // Only proceed if this view is a full page and has a valid path, don't
  2330. // process block or other Views display objects.
  2331. if ($display->display_plugin == 'page' && !empty($display->display_options['path'])) {
  2332. // Try to work out what entity type this is.
  2333. $entity_type = '';
  2334. // All paths must have a placeholder.
  2335. $placeholder_pos = strpos($display->display_options['path'], '%');
  2336. if ($placeholder_pos !== FALSE) {
  2337. // The first argument must be a numeric entity ID.
  2338. if (!empty($view->args) && is_numeric($view->args[0])) {
  2339. // The first argument should be an entity ID.
  2340. $id = $view->args[0];
  2341. // Taxonomy terms are the most commonly used item, so check that first.
  2342. if ($display->display_options['path'] == 'taxonomy/term/%' || $display->display_options['path'] == 'taxonomy/term/%/%') {
  2343. $entity_type = 'taxonomy_term';
  2344. }
  2345. // Node pages.
  2346. elseif ($display->display_options['path'] == 'node/%') {
  2347. $entity_type = 'node';
  2348. }
  2349. // User pages.
  2350. elseif ($display->display_options['path'] == 'user/%') {
  2351. $entity_type = 'user';
  2352. }
  2353. }
  2354. }
  2355. // Check for other types of entities.
  2356. if (empty($entity_type)) {
  2357. // Trigger hook_metatag_views_post_render_get_entity().
  2358. $hook = 'metatag_views_post_render_get_entity';
  2359. foreach (module_implements($hook) as $module) {
  2360. $function = $module . '_' . $hook;
  2361. if (function_exists($function)) {
  2362. $entity_type = call_user_func($function, $view);
  2363. // If an entity type was identified, stop checking.
  2364. if (!empty($entity_type)) {
  2365. break;
  2366. }
  2367. }
  2368. }
  2369. }
  2370. // If an entity type was identified, try loading the entity.
  2371. if (!empty($entity_type)) {
  2372. // Try loading the requested entity.
  2373. $entities = entity_load($entity_type, array($id));
  2374. if (!empty($entities)) {
  2375. $entity = array_pop($entities);
  2376. // Trigger our hook_entity_view().
  2377. metatag_entity_view($entity, $entity_type, 'full', NULL, TRUE);
  2378. }
  2379. }
  2380. }
  2381. }
  2382. /**
  2383. * Implements hook_ctools_render_alter().
  2384. *
  2385. * Temporary solution to load meta tags on entity pages that are driven by
  2386. * CTools display handlers.
  2387. */
  2388. function metatag_ctools_render_alter(&$info, $page, $context) {
  2389. // By default do not add meta tags to admin pages. To enable meta tags on
  2390. // admin pages set the 'metatag_tag_admin_pages' variable to TRUE.
  2391. if (path_is_admin(current_path()) && !variable_get('metatag_tag_admin_pages', FALSE)) {
  2392. return;
  2393. }
  2394. // Only proceed if this is a full page (don't process individual panes) and
  2395. // there's an 'admin path' for the current task.
  2396. if ($page && !empty($context['task']['admin path'])) {
  2397. // Loop over each context.
  2398. foreach ($context['contexts'] as $context_argument) {
  2399. if (is_array($context_argument->type) && !empty($context_argument->data)) {
  2400. if (in_array('entity', $context_argument->type)) {
  2401. $entity = $context_argument->data;
  2402. $entity_type = str_replace('entity:', '', $context_argument->plugin);
  2403. // Verify this is an appropriate entity.
  2404. $entity_info = entity_get_info($entity_type);
  2405. if (!empty($entity_info) && _metatag_entity_is_page($entity_type, $entity)) {
  2406. // Load the meta tags for this entity.
  2407. global $language;
  2408. metatag_entity_view($entity, $entity_type, 'full', $language->language, TRUE);
  2409. // Don't bother looping over any more contexts, an entity has been
  2410. // found.
  2411. break;
  2412. }
  2413. }
  2414. }
  2415. }
  2416. }
  2417. }
  2418. /**
  2419. * Checks if this entity is the default revision (published).
  2420. *
  2421. * Only needed when running Workbench Moderation v1; v3 is skipped.
  2422. *
  2423. * @param object $entity
  2424. * The entity object, e.g., $node.
  2425. *
  2426. * @return bool
  2427. * TRUE if the entity is the default revision, FALSE otherwise.
  2428. */
  2429. function _metatag_isdefaultrevision($entity) {
  2430. // D7 "Forward revisioning" is complex and causes a node_save() with the
  2431. // future node in node table. This fires hook_node_update() twice and cause
  2432. // abnormal behaviour in metatag.
  2433. //
  2434. // The steps taken by Workbench Moderation is to save the forward revision
  2435. // first and overwrite this with the live version in a shutdown function in
  2436. // a second step. This will confuse metatag. D7 has no generic property
  2437. // in the node object, if the node that is updated is the 'published' version
  2438. // or only a draft of a future version.
  2439. //
  2440. // This behaviour will change in D8 where $node->isDefaultRevision has been
  2441. // introduced. See below links for more details.
  2442. // - https://www.drupal.org/node/1879482
  2443. // - https://www.drupal.org/node/218755
  2444. // - https://www.drupal.org/node/1522154
  2445. //
  2446. // Every moderation module saving a forward revision needs to return FALSE.
  2447. // @todo: Refactor this workaround under D8.
  2448. // Workbench Moderation v1 uses the hook_node_presave() for some custom logic.
  2449. // This was replaced with hook_entity_presave() in v3, so only proceed if the
  2450. // old hook implementation is present.
  2451. if (function_exists('workbench_moderation_node_presave')) {
  2452. // If this is a node, check if the content type supports moderation.
  2453. if (function_exists('workbench_moderation_node_type_moderated') && workbench_moderation_node_type_moderated($entity->type) === TRUE) {
  2454. return !empty($entity->workbench_moderation['updating_live_revision']);
  2455. }
  2456. }
  2457. return FALSE;
  2458. }
  2459. /**
  2460. * Generate the cache ID to use with metatag_cache_get/metatag_cache_set calls.
  2461. *
  2462. * @param array $cid_parts
  2463. * A list of values to be used.
  2464. *
  2465. * @return string
  2466. * The cache ID string.
  2467. */
  2468. function metatag_cache_default_cid_parts(array $cid_parts = array()) {
  2469. // The initial parts, control the order of the parts.
  2470. $cid_part_defaults = array(
  2471. 'cache_type' => 'output',
  2472. 'instance' => '',
  2473. 'entity_type' => '',
  2474. 'entity_id' => '',
  2475. 'bundle' => '',
  2476. 'langcode' => $GLOBALS['language_content']->language,
  2477. 'revision_id' => '',
  2478. 'view_mode' => '',
  2479. 'status' => 200,
  2480. 'protocol' => $GLOBALS['is_https'] ? 'https' : 'http',
  2481. 'hostname' => $_SERVER['HTTP_HOST'],
  2482. 'base_path' => base_path(),
  2483. );
  2484. $cid_parts = array_merge($cid_part_defaults, $cid_parts);
  2485. // Add the HTTP status code.
  2486. $headers = drupal_get_http_header();
  2487. if (isset($headers['status'])) {
  2488. $cid_parts['status'] = intval($headers['status']);
  2489. }
  2490. // Allow each page in a sequence to have different values.
  2491. if (isset($_GET['page']) && is_numeric($_GET['page'])) {
  2492. $cid_parts['page'] = intval($_GET['page']);
  2493. }
  2494. // Allow other modules to customize the data using
  2495. // hook_metatag_page_cache_cid_parts_alter().
  2496. drupal_alter('metatag_page_cache_cid_parts', $cid_parts);
  2497. // Remove empty parts.
  2498. $cid_parts = array_filter($cid_parts);
  2499. // Concatenate the cache ID parts, trim the results to 255 chars.
  2500. return substr(implode(':', $cid_parts), 0, 255);
  2501. }
  2502. /**
  2503. * Wrapper for cache_set.
  2504. *
  2505. * @see cache_set()
  2506. */
  2507. function metatag_cache_set($cid, $data) {
  2508. // By default the cached data will not expire.
  2509. $expire = CACHE_PERMANENT;
  2510. // Triggers hook_metatag_cache_set_expire_alter().
  2511. drupal_alter("metatag_cache_set_expire", $expire, $cid, $data);
  2512. return cache_set($cid, $data, 'cache_metatag', $expire);
  2513. }
  2514. /**
  2515. * Wrapper for cache_get.
  2516. *
  2517. * @see cache_get()
  2518. */
  2519. function metatag_cache_get($cid) {
  2520. // Try to load the object.
  2521. return cache_get($cid, 'cache_metatag');
  2522. }
  2523. /**
  2524. * Determines if we are in an error page and return the appropriate instance.
  2525. *
  2526. * @return string
  2527. * String of error.
  2528. */
  2529. function metatag_is_error_page() {
  2530. $known_errors = array(
  2531. 'global:403' => '403 Forbidden',
  2532. 'global:404' => '404 Not Found',
  2533. );
  2534. $headers = drupal_get_http_header();
  2535. if (isset($headers['status'])) {
  2536. foreach ($known_errors as $error => $status) {
  2537. if ($status == $headers['status']) {
  2538. return $error;
  2539. }
  2540. }
  2541. }
  2542. return '';
  2543. }
  2544. /**
  2545. * Implements hook_admin_menu_cache_info().
  2546. */
  2547. function metatag_admin_menu_cache_info() {
  2548. $caches['metatag'] = array(
  2549. 'title' => t('Metatag'),
  2550. 'callback' => 'metatag_config_cache_clear',
  2551. );
  2552. return $caches;
  2553. }
  2554. /**
  2555. * Identify whether an entity type is technically capable of having meta tags.
  2556. *
  2557. * In order to be capable of having meta tags, an entity type must have view
  2558. * modes, must be fieldable, and may not be a configuration entity.
  2559. *
  2560. * @param string $entity_type
  2561. * The entity type.
  2562. * @param array $entity_info
  2563. * Entity information.
  2564. *
  2565. * @return bool
  2566. * Return TRUE if suitable.
  2567. */
  2568. function metatag_entity_type_is_suitable($entity_type, $entity_info = array()) {
  2569. $suitable = TRUE;
  2570. // If the entity info was not passed along, load it.
  2571. if (empty($entity_info)) {
  2572. $entity_info = entity_get_info($entity_type);
  2573. }
  2574. // Configuration entities may not have meta tags.
  2575. if (isset($entity_info['configuration']) && $entity_info['configuration'] == TRUE) {
  2576. $suitable = FALSE;
  2577. }
  2578. // Entities must have bundles.
  2579. elseif (empty($entity_info['bundles'])) {
  2580. $suitable = FALSE;
  2581. }
  2582. // The entity type must be fieldable.
  2583. elseif (empty($entity_info['fieldable'])) {
  2584. $suitable = FALSE;
  2585. }
  2586. else {
  2587. // Ignore some view modes that are automatically added by certain modules.
  2588. unset($entity_info['view modes']['ical']);
  2589. unset($entity_info['view modes']['diff_standard']);
  2590. unset($entity_info['view modes']['token']);
  2591. // There must be view modes.
  2592. if (empty($entity_info['view modes'])) {
  2593. $suitable = FALSE;
  2594. }
  2595. else {
  2596. // Specifically disable some entity types.
  2597. $excluded = array(
  2598. // Comment module.
  2599. 'comment',
  2600. // Field Collection module.
  2601. 'field_collection_item',
  2602. // Paragraphs module.
  2603. 'paragraphs_item',
  2604. );
  2605. if (in_array($entity_type, $excluded)) {
  2606. $suitable = FALSE;
  2607. }
  2608. }
  2609. }
  2610. // Trigger hook_metatag_entity_type_is_supported_alter() to allow other
  2611. // modules to either enable or disable certain entity types.
  2612. drupal_alter('metatag_entity_type_is_supported', $suitable, $entity_type, $entity_info);
  2613. return $suitable;
  2614. }
  2615. /**
  2616. * Implements hook_node_type_insert().
  2617. *
  2618. * When a content type is created, enable it for use with Metatag.
  2619. */
  2620. function metatag_node_type_insert($info) {
  2621. if (metatag_entity_supports_metatags('node')) {
  2622. if (metatag_entity_type_enable('node', $info->type)) {
  2623. drupal_set_message(t('Metatag support has been enabled for the @label content type.', array('@label' => $info->name)));
  2624. }
  2625. }
  2626. }
  2627. /**
  2628. * Implements hook_node_type_delete().
  2629. *
  2630. * When a content type is deleted, remove the corresponding Metatag variable.
  2631. */
  2632. function metatag_node_type_delete($info) {
  2633. variable_del('metatag_enable_node__' . $info->type);
  2634. }
  2635. /**
  2636. * Implements hook_taxonomy_vocabulary_insert().
  2637. *
  2638. * When a vocabulary is created, enable it for use with Metatag.
  2639. */
  2640. function metatag_taxonomy_vocabulary_insert($vocabulary) {
  2641. if (metatag_entity_supports_metatags('taxonomy_term')) {
  2642. if (metatag_entity_type_enable('taxonomy_term', $vocabulary->machine_name)) {
  2643. drupal_set_message(t('Metatag support has been enabled for the @label vocabulary.', array('@label' => $vocabulary->name)));
  2644. }
  2645. }
  2646. }
  2647. /**
  2648. * Implements hook_taxonomy_vocabulary_delete().
  2649. *
  2650. * When a vocabulary is deleted, remove the corresponding Metatag variable.
  2651. */
  2652. function metatag_taxonomy_vocabulary_delete($info) {
  2653. variable_del('metatag_enable_taxonomy_term__' . $info->machine_name);
  2654. }
  2655. /**
  2656. * Implements hook_workbench_moderation_transition().
  2657. *
  2658. * Clear a node's caches when its Workbench Moderation state is changed.
  2659. */
  2660. function metatag_workbench_moderation_transition($node, $previous_state, $new_state) {
  2661. metatag_metatags_cache_clear('node', array($node->nid));
  2662. }
  2663. /**
  2664. * Sort callback for sorting by metatag instance string values.
  2665. */
  2666. function _metatag_config_instance_sort($a, $b) {
  2667. $a_contexts = explode(':', $a);
  2668. $b_contexts = explode(':', $b);
  2669. // Global config always comes first.
  2670. if ($a_contexts[0] == 'global' && $b_contexts[0] != 'global') {
  2671. return -1;
  2672. }
  2673. elseif ($b_contexts[0] == 'global' && $a_contexts[0] != 'global') {
  2674. return 1;
  2675. }
  2676. for ($i = 0; $i < max(count($a_contexts), count($b_contexts)); $i++) {
  2677. $a_context = isset($a_contexts[$i]) ? $a_contexts[$i] : '';
  2678. $b_context = isset($b_contexts[$i]) ? $b_contexts[$i] : '';
  2679. if ($a_context == $b_context) {
  2680. continue;
  2681. }
  2682. else {
  2683. return strcmp($a_context, $b_context);
  2684. }
  2685. }
  2686. }
  2687. /**
  2688. * Translations & internationalization (i18n).
  2689. */
  2690. /**
  2691. * Implements hook_entity_translation_delete().
  2692. *
  2693. * Required for content translations being handled via Entity_Translation to
  2694. * remove the appropriate record when a translation is removed without the
  2695. * corresponding entity record also being removed.
  2696. */
  2697. function metatag_entity_translation_delete($entity_type, $entity, $langcode) {
  2698. // Get the entity's ID.
  2699. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  2700. $revision_id = intval($revision_id);
  2701. // Delete the translation.
  2702. metatag_metatags_delete($entity_type, $entity_id, $revision_id, $langcode);
  2703. }
  2704. /**
  2705. * Translates the metatag if i18n_string integration is enabled.
  2706. *
  2707. * @param string $string
  2708. * String in default language or array of strings to be translated.
  2709. * @param string $tag_name
  2710. * The internal name of the meta tag being translated.
  2711. * @param mixed $context
  2712. * A context string to use with i18n, or the $options array from a Metatag::
  2713. * getValue() method; if the latter it will be used to generate the full
  2714. * context.
  2715. * @param string $langcode
  2716. * The language code to submit instead of the current page's language.
  2717. * @param bool $update
  2718. * Whether or not to create/update records in {locales_source}.
  2719. *
  2720. * @return string
  2721. * The translated string if i18n_string is enabled, otherwise just returns the
  2722. * original string.
  2723. *
  2724. * @see i18n_string_translate()
  2725. */
  2726. function metatag_translate_metatag($string, $tag_name, $context, $langcode = NULL, $update = TRUE) {
  2727. if (module_exists('i18n_string') && !variable_get('metatag_i18n_disabled', FALSE)) {
  2728. // By default do not add meta tags to admin pages. To enable meta tags on
  2729. // admin pages set the 'metatag_tag_admin_pages' variable to TRUE.
  2730. static $page_is_admin;
  2731. if (is_null($page_is_admin)) {
  2732. $page_is_admin = FALSE;
  2733. if (path_is_admin(current_path()) && !variable_get('metatag_tag_admin_pages', FALSE)) {
  2734. $page_is_admin = TRUE;
  2735. }
  2736. }
  2737. if ($page_is_admin) {
  2738. return $string;
  2739. }
  2740. // If the context is an array then it is the $options from the meta tag
  2741. // generator and needs some custom tailoring. Doing it this way to avoid an
  2742. // unnecessary entity_extract_ids() call when i18n isn't being used.
  2743. if (is_array($context)) {
  2744. // Optionally disable output generation.
  2745. if (!variable_get('metatag_i18n_translate_output', FALSE)) {
  2746. return $string;
  2747. }
  2748. // Output generation was enabled, so continue as normal.
  2749. $new_context = 'output:';
  2750. if (drupal_is_front_page()) {
  2751. $new_context .= 'frontpage';
  2752. }
  2753. // If this is an entity page, use the entity as the context.
  2754. elseif (!empty($context['entity_type']) && !empty($context['entity'])) {
  2755. list($entity_id, $revision_id, $bundle) = entity_extract_ids($context['entity_type'], $context['entity']);
  2756. $new_context .= $context['entity_type'] . ':' . $entity_id;
  2757. }
  2758. // Otherwise, use the page URL.
  2759. else {
  2760. // Trim this to avoid SQL errors on the {locales_source} table.
  2761. // length = 255 - strlen('metatag:output:page:') - strlen(metatag);
  2762. $strlen = 255 - strlen('metatag:output:page:' . $tag_name);
  2763. $new_context .= 'page:' . drupal_substr(current_path(), 0, $strlen);
  2764. }
  2765. $context = $new_context;
  2766. }
  2767. $options = array(
  2768. // Automatically create/update the {locales_source} record if one wasn't
  2769. // found.
  2770. 'update' => $update,
  2771. // Translate the string.
  2772. 'translate' => TRUE,
  2773. );
  2774. // If the langcode was passed in, add it to the options passed to i18n.
  2775. if (!empty($langcode)) {
  2776. $options['langcode'] = $langcode;
  2777. }
  2778. // By default disable the watchdog logging of translation messages.
  2779. $options['watchdog'] = variable_get('metatag_i18n_enable_watchdog', FALSE);
  2780. // Triggers hook_metatag_i18n_context_alter() - allows the i18n string to
  2781. // be altered before being used.
  2782. drupal_alter('metatag_i18n_context', $context, $tag_name);
  2783. // If the context was erased just send back the original string - it's
  2784. // unlikely, but it could happen.
  2785. if (empty($context)) {
  2786. return $string;
  2787. }
  2788. // The 'name' is split up by i18n_string into two components - the textgroup
  2789. // is the first item, the others are joined together with a ':' separator
  2790. // to make the context. In order to have the contexts show with "metatag" as
  2791. // the first part of the context, it has to be added twice to the name.
  2792. $name = array(
  2793. 'metatag',
  2794. $context,
  2795. $tag_name,
  2796. );
  2797. // Notify i18n of the string, and obtain a translation if one is available.
  2798. return i18n_string($name, $string, $options);
  2799. }
  2800. // If the i18n_string module isn't enabled then just pass back the string
  2801. // as-is.
  2802. else {
  2803. return $string;
  2804. }
  2805. }
  2806. /**
  2807. * Translate a set of metatags to the current language.
  2808. *
  2809. * @param array $metatags
  2810. * List of meta tags to be translated.
  2811. * @param string $context
  2812. * An optional context to use with i18n.
  2813. * @param string $langcode
  2814. * The language code to submit instead of the current page's language.
  2815. * @param bool $update
  2816. * Whether or not to create/update records in {locales_source}.
  2817. */
  2818. function metatag_translate_metatags(&$metatags, $context = NULL, $langcode = NULL, $update = TRUE) {
  2819. if (!empty($metatags)) {
  2820. foreach ($metatags as $key => $data) {
  2821. if (!empty($data['value']) && is_string($data['value'])) {
  2822. $metatags[$key] = array(
  2823. 'value' => metatag_translate_metatag($data['value'], $key, $context, $langcode, $update),
  2824. );
  2825. }
  2826. }
  2827. }
  2828. }
  2829. /**
  2830. * Update the translated definitions of meta tags.
  2831. *
  2832. * @param array $metatags
  2833. * List of meta tags to have their translations updated.
  2834. * @param string $context
  2835. * The string that will be used to group strings in the translation UI.
  2836. */
  2837. function metatag_translations_update($metatags, $context) {
  2838. // Store the context as it was originally provided.
  2839. $original_context = $context;
  2840. // Update the i18n string.
  2841. if (module_exists('i18n_string') && !variable_get('metatag_i18n_disabled', FALSE)) {
  2842. $options = array();
  2843. // By default disable the watchdog logging of translation messages.
  2844. $options['watchdog'] = variable_get('metatag_i18n_enable_watchdog', FALSE);
  2845. foreach ($metatags as $tag_name => $data) {
  2846. // Revert the context, so that it can be changed if needed.
  2847. $context = $original_context;
  2848. if (!empty($data['value']) && is_string($data['value'])) {
  2849. // Triggers hook_metatag_i18n_context_alter() - allows the i18n string
  2850. // to be altered before being used.
  2851. drupal_alter('metatag_i18n_context', $context, $tag_name);
  2852. // Don't do anything if the context was erased - it's unlikely, but it
  2853. // could happen.
  2854. if (empty($context)) {
  2855. continue;
  2856. }
  2857. // The textgroup is the first part of the string.
  2858. i18n_string_update("metatag:{$context}:{$tag_name}", $data['value'], $options);
  2859. }
  2860. }
  2861. }
  2862. }
  2863. /**
  2864. * Remove the translated definitions of meta tags.
  2865. *
  2866. * @param array $metatags
  2867. * List of meta tags to have their translations updated.
  2868. * @param string $context
  2869. * The string that will be used to group strings in the translation UI.
  2870. */
  2871. function metatag_translations_delete($metatags, $context) {
  2872. // Store the context as it was originally provided.
  2873. $original_context = $context;
  2874. // Update the i18n string.
  2875. if (module_exists('i18n_string') && !variable_get('metatag_i18n_disabled', FALSE)) {
  2876. $options = array();
  2877. // By default disable the watchdog logging of translation messages.
  2878. $options['watchdog'] = variable_get('metatag_i18n_enable_watchdog', FALSE);
  2879. foreach ($metatags as $tag_name => $data) {
  2880. // Revert the context, so that it can be changed if needed.
  2881. $context = $original_context;
  2882. if (!empty($data['value']) && is_string($data['value'])) {
  2883. // Triggers hook_metatag_i18n_context_alter() - allows the i18n string
  2884. // to be altered before being used.
  2885. drupal_alter('metatag_i18n_context', $context, $tag_name);
  2886. // Don't do anything if the context was erased - it's unlikely, but it
  2887. // could happen.
  2888. if (empty($context)) {
  2889. continue;
  2890. }
  2891. // The textgroup is the first part of the string.
  2892. i18n_string_remove("metatag:{$context}:{$tag_name}", $data['value'], $options);
  2893. }
  2894. }
  2895. }
  2896. }
  2897. /**
  2898. * Implements hook_config_insert().
  2899. *
  2900. * Implements hook_metatag_config_insert() on behalf of i18n_string.
  2901. */
  2902. function i18n_string_metatag_config_insert($config) {
  2903. $context = 'metatag_config:' . $config->instance;
  2904. metatag_translations_update($config->config, $context);
  2905. }
  2906. /**
  2907. * Implements hook_config_update().
  2908. *
  2909. * Implements hook_metatag_config_update() on behalf of i18n_string.
  2910. */
  2911. function i18n_string_metatag_config_update($config) {
  2912. // Defer to the 'insert' function.
  2913. i18n_string_metatag_config_insert($config);
  2914. }
  2915. /**
  2916. * Implements hook_config_delete().
  2917. *
  2918. * Implements hook_metatag_config_delete() on behalf of i18n_string.
  2919. */
  2920. function i18n_string_metatag_config_delete($config) {
  2921. $context = 'metatag_config:' . $config->instance;
  2922. metatag_translations_delete($config->config, $context);
  2923. }