metatag.module 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300
  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_hook_info().
  56. */
  57. function metatag_hook_info() {
  58. $hooks = array(
  59. 'metatag_config_default',
  60. 'metatag_config_default_alter',
  61. 'metatag_config_delete',
  62. 'metatag_config_insert',
  63. 'metatag_config_instance_info',
  64. 'metatag_config_instance_info_alter',
  65. 'metatag_config_load',
  66. 'metatag_config_load_presave',
  67. 'metatag_config_update',
  68. 'metatag_info',
  69. 'metatag_info_alter',
  70. );
  71. return array_fill_keys($hooks, array('group' => 'metatag'));
  72. }
  73. /**
  74. * Implements hook_permission().
  75. */
  76. function metatag_permission() {
  77. $permissions['administer meta tags'] = array(
  78. 'title' => t('Administer meta tags'),
  79. 'restrict access' => TRUE,
  80. 'description' => t('Control the main settings pages and modify per-object meta tags.'),
  81. );
  82. $permissions['edit meta tags'] = array(
  83. 'title' => t('Edit meta tags'),
  84. 'description' => t('Modify meta tags on individual entity records (nodes, terms, users, etc).'),
  85. );
  86. // Optional extended edit permissions.
  87. if (variable_get('metatag_extended_permissions', FALSE)) {
  88. $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')));
  89. $metatags = metatag_get_info();
  90. foreach ($metatags['tags'] as $metatag_name => $metatag) {
  91. $permissions['edit meta tag: ' . $metatag_name] = array(
  92. 'title' => t('Extended permission: Edit :tag meta tag', array(':tag' => $metatag['label'])),
  93. 'description' => t('Customize the :tag meta tag on individual forms.', array(':tag' => $metatag['label'])),
  94. );
  95. }
  96. }
  97. return $permissions;
  98. }
  99. /**
  100. * Implements hook_menu().
  101. */
  102. function metatag_menu() {
  103. $items['admin/config/search/metatags'] = array(
  104. 'title' => 'Metatag',
  105. 'description' => 'Configure Metatag defaults.',
  106. 'page callback' => 'metatag_config_overview',
  107. 'access arguments' => array('administer meta tags'),
  108. 'file' => 'metatag.admin.inc',
  109. );
  110. $items['admin/config/search/metatags/config'] = array(
  111. 'title' => 'Defaults',
  112. 'type' => MENU_DEFAULT_LOCAL_TASK,
  113. 'weight' => -10,
  114. );
  115. $items['admin/config/search/metatags/config/add'] = array(
  116. 'title' => 'Add a Metatag default',
  117. 'page callback' => 'drupal_get_form',
  118. 'page arguments' => array('metatag_config_add_form'),
  119. 'access arguments' => array('administer meta tags'),
  120. 'file' => 'metatag.admin.inc',
  121. 'type' => MENU_LOCAL_ACTION,
  122. );
  123. $items['admin/config/search/metatags/config/%metatag_config'] = array(
  124. 'title callback' => 'metatag_config_title',
  125. 'title arguments' => array(5),
  126. 'page callback' => 'drupal_get_form',
  127. 'page arguments' => array('metatag_config_edit_form', 5),
  128. 'access arguments' => array('administer meta tags'),
  129. 'file' => 'metatag.admin.inc',
  130. );
  131. $items['admin/config/search/metatags/config/%metatag_config/edit'] = array(
  132. 'title' => 'Edit',
  133. 'type' => MENU_DEFAULT_LOCAL_TASK,
  134. 'weight' => -10,
  135. );
  136. $items['admin/config/search/metatags/config/%metatag_config/enable'] = array(
  137. 'title' => 'Enable',
  138. 'page callback' => 'metatag_config_enable',
  139. 'page arguments' => array(5),
  140. 'access callback' => 'metatag_config_access',
  141. 'access arguments' => array('enable', 5),
  142. 'file' => 'metatag.admin.inc',
  143. );
  144. $items['admin/config/search/metatags/config/%metatag_config/disable'] = array(
  145. 'title' => 'Disable',
  146. 'page callback' => 'metatag_config_disable',
  147. 'page arguments' => array(5),
  148. 'access callback' => 'metatag_config_access',
  149. 'access arguments' => array('disable', 5),
  150. 'file' => 'metatag.admin.inc',
  151. );
  152. $items['admin/config/search/metatags/config/%metatag_config/revert'] = array(
  153. 'title' => 'Revert',
  154. 'page callback' => 'drupal_get_form',
  155. 'page arguments' => array('metatag_config_delete_form', 5),
  156. 'access callback' => 'metatag_config_access',
  157. 'access arguments' => array('revert', 5),
  158. 'file' => 'metatag.admin.inc',
  159. 'type' => MENU_LOCAL_TASK,
  160. );
  161. $items['admin/config/search/metatags/config/%metatag_config/delete'] = array(
  162. 'title' => 'Delete',
  163. 'page callback' => 'drupal_get_form',
  164. 'page arguments' => array('metatag_config_delete_form', 5),
  165. 'access callback' => 'metatag_config_access',
  166. 'access arguments' => array('delete', 5),
  167. 'file' => 'metatag.admin.inc',
  168. );
  169. $items['admin/config/search/metatags/config/%metatag_config/export'] = array(
  170. 'title' => 'Export',
  171. 'page callback' => 'metatag_config_export_form',
  172. 'page arguments' => array(5),
  173. 'access arguments' => array('administer meta tags'),
  174. 'file' => 'metatag.admin.inc',
  175. 'type' => MENU_LOCAL_TASK,
  176. 'weight' => 10,
  177. );
  178. $items['admin/config/search/metatags/settings'] = array(
  179. 'title' => 'Advanced settings',
  180. 'page callback' => 'drupal_get_form',
  181. 'page arguments' => array('metatag_admin_settings_form'),
  182. 'access arguments' => array('administer meta tags'),
  183. 'type' => MENU_LOCAL_TASK,
  184. 'weight' => 30,
  185. 'file' => 'metatag.admin.inc',
  186. );
  187. $items['admin/config/search/metatags/bulk-revert'] = array(
  188. 'title' => 'Bulk revert',
  189. 'page callback' => 'drupal_get_form',
  190. 'page arguments' => array('metatag_bulk_revert_form'),
  191. 'access arguments' => array('administer meta tags'),
  192. 'type' => MENU_LOCAL_TASK,
  193. 'weight' => 40,
  194. 'file' => 'metatag.admin.inc',
  195. );
  196. return $items;
  197. }
  198. /**
  199. * Implements hook_flush_caches().
  200. */
  201. function metatag_flush_caches() {
  202. return array('cache_metatag');
  203. }
  204. /**
  205. * Load a metatag configuration record with all the defaults merged in.
  206. *
  207. * For example, given the configuration instance 'node:article', this function
  208. * will load the configuration records for 'node:article', then 'node', and
  209. * then finally 'global', with each attempt using an array merge.
  210. *
  211. * The levels of defaults is arranged by splitting the $instance variable by
  212. * the colon character, and always using a 'global' instance at the end.
  213. */
  214. function metatag_config_load_with_defaults($instance, $include_global = TRUE) {
  215. $defaults = &drupal_static(__FUNCTION__, array());
  216. // Statically cache defaults since they can include multiple levels.
  217. $cid = "config:{$instance}" . ($include_global ? ':withglobal' : ':withoutglobal');
  218. if (!isset($defaults[$cid])) {
  219. if ($cache = metatag_cache_get($cid)) {
  220. $defaults[$cid] = $cache->data;
  221. }
  222. else {
  223. $defaults[$cid] = array();
  224. $instances = metatag_config_get_parent_instances($instance, $include_global);
  225. $configs = metatag_config_load_multiple($instances);
  226. foreach ($instances as $key) {
  227. // Ignore disabled configurations.
  228. if (!isset($configs[$key]) || !empty($configs[$key]->disabled)) {
  229. continue;
  230. }
  231. // Add config to the defaults array.
  232. if (!empty($configs[$key]->config)) {
  233. $defaults[$cid] += $configs[$key]->config;
  234. }
  235. }
  236. metatag_cache_set($cid, $defaults[$cid]);
  237. }
  238. }
  239. return $defaults[$cid];
  240. }
  241. /**
  242. * Load a metatag configuration record.
  243. */
  244. function metatag_config_load($instance) {
  245. $results = metatag_config_load_multiple(array($instance));
  246. return !empty($results[$instance]) ? $results[$instance] : FALSE;
  247. }
  248. /**
  249. * Load multiple metatag configuration records.
  250. */
  251. function metatag_config_load_multiple(array $instances) {
  252. // Load the data.
  253. ctools_include('export');
  254. $configs = ctools_export_load_object('metatag_config', 'names', $instances);
  255. // "Fix" any records that might be using old values. Ideally these will be
  256. // permanently fixed by being re-saved or re-exported.
  257. foreach (metatag_config_get_replacements() as $old_tag => $new_tag) {
  258. foreach ($configs as $config_name => $config) {
  259. if (isset($config->config[$old_tag])) {
  260. $config->config[$new_tag] = $config->config[$old_tag];
  261. unset($config->config[$old_tag]);
  262. }
  263. }
  264. }
  265. return $configs;
  266. }
  267. /**
  268. * Identify the meta tags that have been deprecated and replaced by others.
  269. */
  270. function metatag_config_get_replacements() {
  271. $replacements = &drupal_static(__FUNCTION__);
  272. if (!isset($replacements)) {
  273. $replacements = array();
  274. foreach (metatag_get_info('tags') as $tag_name => $tag_info) {
  275. if (!empty($tag_info['replaces'])) {
  276. if (!is_array($tag_info['replaces'])) {
  277. $tag_info['replaces'] = array($tag_info['replaces']);
  278. }
  279. foreach ($tag_info['replaces'] as $replaces) {
  280. $replacements[$replaces] = $tag_name;
  281. }
  282. }
  283. }
  284. }
  285. return $replacements;
  286. }
  287. /**
  288. * Save a metatag configuration record to the database.
  289. */
  290. function metatag_config_save($config) {
  291. $config->is_new = empty($config->cid);
  292. // Allow modules to alter the configuration before it is saved using
  293. // hook_metatag_config_presave().
  294. module_invoke_all('metatag_config_presave', $config);
  295. // Update the i18n string
  296. if (function_exists('i18n_string_update')) {
  297. $instance = $config->instance;
  298. foreach ($config->config as $field => $item) {
  299. $name = "metatag:" . $instance . ":" . $field;
  300. i18n_string_update($name, $item['value']);
  301. }
  302. }
  303. if ($config->is_new) {
  304. drupal_write_record('metatag_config', $config);
  305. // Allow modules to act upon the record insertion using
  306. // hook_metatag_config_insert().
  307. module_invoke_all('metatag_config_insert', $config);
  308. }
  309. else {
  310. drupal_write_record('metatag_config', $config, array('cid'));
  311. // Allow modules to act upon the record update using
  312. // hook_metatag_config_insert().
  313. module_invoke_all('metatag_config_update', $config);
  314. }
  315. unset($config->is_new);
  316. // Clear any caches.
  317. metatag_config_cache_clear();
  318. }
  319. /**
  320. * Delete a metatag configuration record.
  321. */
  322. function metatag_config_delete($instance) {
  323. db_delete('metatag_config')
  324. ->condition('instance', $instance)
  325. ->execute();
  326. // Clear any caches.
  327. metatag_config_cache_clear();
  328. }
  329. /**
  330. * Clear the metatag configuration cache.
  331. */
  332. function metatag_config_cache_clear() {
  333. cache_clear_all('*', 'cache_metatag', TRUE);
  334. drupal_static_reset('metatag_config_load_with_defaults');
  335. drupal_static_reset('metatag_entity_has_metatags');
  336. drupal_static_reset('metatag_entity_supports_metatags');
  337. ctools_include('export');
  338. ctools_export_load_object_reset('metatag_config');
  339. }
  340. /**
  341. * Load an entity's tags.
  342. *
  343. * @param $entity_type
  344. * The entity type to load.
  345. * @param $entity_id
  346. * The ID of the entity to load.
  347. *
  348. * @return
  349. * An array of tag data keyed by revision ID and language.
  350. */
  351. function metatag_metatags_load($entity_type, $entity_id) {
  352. $metatags = metatag_metatags_load_multiple($entity_type, array($entity_id));
  353. return !empty($metatags) ? reset($metatags) : array();
  354. }
  355. /**
  356. * Load tags for multiple entities.
  357. *
  358. * @param $entity_type
  359. * The entity type to load.
  360. * @param $entity_ids
  361. * The list of entity IDs.
  362. *
  363. * @return
  364. * An array of tag data, keyed by entity ID, revision ID and language.
  365. */
  366. function metatag_metatags_load_multiple($entity_type, array $entity_ids, array $revision_ids = array()) {
  367. // Double check entity IDs are numeric thanks to Entity API module.
  368. $entity_ids = array_filter($entity_ids, 'is_numeric');
  369. if (empty($entity_ids)) {
  370. return array();
  371. }
  372. // Also need to check if the metatag table exists since this condition could
  373. // fire before the table has been installed yet.
  374. if (!variable_get('metatag_schema_installed', FALSE)) {
  375. if (db_table_exists('metatag')) {
  376. variable_set('metatag_schema_installed', TRUE);
  377. }
  378. else {
  379. watchdog('metatag', 'The system tried to load metatag data before the schema was fully loaded.', array(), WATCHDOG_WARNING);
  380. return array();
  381. }
  382. }
  383. // Verify that the metatag.revision_id field has been added to the {metatag}
  384. // table schema.
  385. if (!variable_get('metatag_has_revision_id', FALSE)) {
  386. if (db_field_exists('metatag', 'revision_id')) {
  387. variable_set('metatag_has_revision_id', TRUE);
  388. }
  389. else {
  390. watchdog('metatag', 'The database updates need to be ran.', array(), WATCHDOG_WARNING);
  391. return array();
  392. }
  393. }
  394. // Get all translations of tag data for this entity.
  395. $query = db_select('metatag', 'm')
  396. ->fields('m', array('entity_id', 'revision_id', 'language', 'data'))
  397. ->condition('m.entity_type', $entity_type)
  398. ->orderBy('entity_id')
  399. ->orderBy('revision_id');
  400. // Filter by revision_ids if they are available. If not, filter by entity_ids.
  401. if (!empty($revision_ids)) {
  402. $query->condition('m.revision_id', $revision_ids, 'IN');
  403. }
  404. else {
  405. $query->condition('m.entity_id', $entity_ids, 'IN');
  406. }
  407. $result = $query->execute();
  408. // Marshal it into an array keyed by entity ID. Each value is an array of
  409. // translations keyed by language code.
  410. $metatags = array();
  411. while ($record = $result->fetchObject()) {
  412. $data = unserialize($record->data);
  413. // "Fix" any records that might be using old values. Ideally these will be
  414. // permanently fixed by being re-saved or re-exported.
  415. foreach (metatag_config_get_replacements() as $old_tag => $new_tag) {
  416. if (isset($data[$old_tag])) {
  417. $data[$new_tag] = $data[$old_tag];
  418. unset($data[$old_tag]);
  419. }
  420. }
  421. $metatags[$record->entity_id][$record->revision_id][$record->language] = $data;
  422. }
  423. return $metatags;
  424. }
  425. /**
  426. * Save an entity's tags.
  427. *
  428. * @param $entity_type
  429. * The entity type to load
  430. * @param $entity_id
  431. * The entity's ID
  432. * @param $revision_id
  433. * The entity's VID.
  434. * @param $metatags
  435. * All of the tag information
  436. * @param $language
  437. * The language of the translation set
  438. */
  439. function metatag_metatags_save($entity_type, $entity_id, $revision_id, $metatags, $langcode, $old_vid = NULL) {
  440. // If no language assigned, or the language doesn't exist, use the
  441. // has-no-language language.
  442. $languages = language_list();
  443. if (empty($langcode) || !isset($languages[$langcode])) {
  444. $langcode = LANGUAGE_NONE;
  445. }
  446. // Check that $entity_id is numeric because of Entity API and string IDs.
  447. if (!is_numeric($entity_id)) {
  448. return;
  449. }
  450. // The revision_id must be a numeric value; some entities use NULL for the
  451. // revision so change that to a zero.
  452. if (is_null($revision_id)) {
  453. $revision_id = 0;
  454. }
  455. // Handle scenarios where the metatags are completely empty.
  456. if (empty($metatags)) {
  457. $metatags = array();
  458. // Add an empty array record for each language.
  459. $languages = db_query("SELECT language, ''
  460. FROM {metatag}
  461. WHERE (entity_type = :type)
  462. AND (entity_id = :id)
  463. AND (revision_id = :revision)",
  464. array(
  465. ':type' => $entity_type,
  466. ':id' => $entity_id,
  467. ':revision' => $revision_id,
  468. ))->fetchAllKeyed();
  469. foreach ($languages as $oldlang => $empty) {
  470. $metatags[$oldlang] = array();
  471. }
  472. }
  473. // Update each of the per-language metatag configurations in turn.
  474. foreach ($metatags as $langcode => $new_metatags) {
  475. // Allow other modules to alter the meta tags prior to saving using
  476. // hook_metatag_presave().
  477. foreach (module_implements('metatag_presave') as $module) {
  478. $function = "{$module}_metatag_presave";
  479. $function($new_metatags, $entity_type, $entity_id, $revision_id, $langcode);
  480. }
  481. // If the data array is empty, there is no data to actually save, so just
  482. // delete the record from the database.
  483. if (empty($new_metatags)) {
  484. db_delete('metatag')
  485. ->condition('entity_type', $entity_type)
  486. ->condition('entity_id', $entity_id)
  487. ->condition('revision_id', $revision_id)
  488. ->condition('language', $langcode)
  489. ->execute();
  490. }
  491. // Otherwise save the data for this entity.
  492. else {
  493. db_merge('metatag')
  494. ->key(array(
  495. 'entity_type' => $entity_type,
  496. 'entity_id' => $entity_id,
  497. 'language' => $langcode,
  498. 'revision_id' => $revision_id,
  499. ))
  500. ->fields(array(
  501. 'data' => serialize($new_metatags),
  502. ))
  503. ->execute();
  504. }
  505. }
  506. // Clear cached data.
  507. metatag_metatags_cache_clear($entity_type, $entity_id);
  508. }
  509. /**
  510. * Delete an entity's tags.
  511. *
  512. * @param $entity_type
  513. * The entity type
  514. * @param $entity_id
  515. * The entity's ID
  516. * @param $revision_id
  517. * The entity's VID.
  518. * @param $langcode
  519. * The language ID of the entry to delete. If left blank, all language
  520. * entries for this entity will be deleted.
  521. */
  522. function metatag_metatags_delete($entity_type, $entity_id, $revision_id = NULL, $langcode = NULL) {
  523. $revision_ids = array();
  524. if (!empty($revision_id)) {
  525. $revision_ids[] = $revision_id;
  526. }
  527. return metatag_metatags_delete_multiple($entity_type, array($entity_id), $revision_ids, $langcode);
  528. }
  529. /**
  530. * Delete multiple entities' tags.
  531. *
  532. * @param $entity_type
  533. * The entity type
  534. * @param $entity_ids
  535. * The list of IDs
  536. * @param $revision_id
  537. * An optional list of VIDs, if omitted all revisions will be deleted.
  538. * @param $langcode
  539. * The language ID of the entities to delete. If left blank, all language
  540. * entries for the enities will be deleted.
  541. */
  542. function metatag_metatags_delete_multiple($entity_type, array $entity_ids, array $revision_ids = array(), $langcode = NULL) {
  543. // Double check entity IDs are numeric thanks to Entity API module.
  544. $entity_ids = array_filter($entity_ids, 'is_numeric');
  545. if ($metatags = metatag_metatags_load_multiple($entity_type, $entity_ids, $revision_ids)) {
  546. $transaction = db_transaction();
  547. try {
  548. // Let other modules know about the records being deleted using
  549. // hook_metatag_metatags_delete().
  550. module_invoke_all('metatag_metatags_delete', $entity_type, $entity_ids, $revision_ids, $langcode);
  551. // Set the entity to delete.
  552. $query = db_delete('metatag')
  553. ->condition('entity_type', $entity_type)
  554. ->condition('entity_id', $entity_ids, 'IN');
  555. // Optionally delete a specific revision.
  556. if (!empty($revision_ids)) {
  557. $query->condition('revision_id', $revision_ids, 'IN');
  558. }
  559. // Specify a language if there is one.
  560. if (!empty($langcode)) {
  561. $query->condition('language', $langcode);
  562. }
  563. // Perform the deletion(s).
  564. $query->execute();
  565. // Clear cached data.
  566. metatag_metatags_cache_clear($entity_type, $entity_ids);
  567. }
  568. catch (Exception $e) {
  569. $transaction->rollback();
  570. watchdog_exception('metatag', $e);
  571. throw $e;
  572. }
  573. }
  574. }
  575. /**
  576. * Clear the cached records for a given entity type or entity ID.
  577. *
  578. * @param string $entity_type
  579. * The entity type to clear.
  580. */
  581. function metatag_metatags_cache_clear($entity_type, $entity_ids = NULL) {
  582. if (empty($entity_ids)) {
  583. cache_clear_all("output:$entity_type", 'cache_metatag', TRUE);
  584. }
  585. else {
  586. if (!is_array($entity_ids)) {
  587. $entity_ids = array($entity_ids);
  588. }
  589. foreach ($entity_ids as $entity_id) {
  590. cache_clear_all("output:$entity_type:$entity_id", 'cache_metatag', TRUE);
  591. }
  592. }
  593. }
  594. /**
  595. * Implements hook_entity_load().
  596. */
  597. function metatag_entity_load($entities, $entity_type) {
  598. // Get the revision_ids.
  599. $revision_ids = array();
  600. foreach ($entities as $key => $entity) {
  601. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  602. $revision_id = intval($revision_id);
  603. if (!empty($revision_id)) {
  604. $revision_ids[] = $revision_id;
  605. }
  606. }
  607. // Wrap this in a try-catch block to work around occasions when the schema
  608. // hasn't been updated yet.
  609. try {
  610. if (metatag_entity_supports_metatags($entity_type)) {
  611. $metatags = metatag_metatags_load_multiple($entity_type, array_keys($entities), $revision_ids);
  612. // Assign the metatag records for the correct revision ID.
  613. foreach ($entities as $entity_id => $entity) {
  614. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  615. $revision_id = intval($revision_id);
  616. $entities[$entity_id]->metatags = isset($metatags[$entity_id][$revision_id]) ? $metatags[$entity_id][$revision_id] : array();
  617. }
  618. }
  619. }
  620. catch (Exception $e) {
  621. 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', array('@update' => base_path() . 'update.php', '%ids' => implode(', ', array_keys($entities)), '%type' => $entity_type, '%error' => $e->getMessage()), WATCHDOG_WARNING);
  622. // Don't display the same message twice for Drush.
  623. if (drupal_is_cli()) {
  624. drupal_set_message(t('Run your updates, like drush updb.'));
  625. }
  626. // Only message people who can see it in watchdog and can likely fix it.
  627. elseif (user_access('access site reports')) {
  628. 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');
  629. }
  630. }
  631. }
  632. /**
  633. * Implements hook_entity_insert().
  634. */
  635. function metatag_entity_insert($entity, $entity_type) {
  636. if (isset($entity->metatags)) {
  637. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  638. $revision_id = intval($revision_id);
  639. // Determine the entity's language.
  640. $langcode = entity_language($entity_type, $entity);
  641. // Unfortunately due to how core works, the normal entity_language()
  642. // function returns 'und' instead of the node's language during node
  643. // creation.
  644. if ((empty($langcode) || $langcode == LANGUAGE_NONE) && !empty($entity->language)) {
  645. $langcode = $entity->language;
  646. }
  647. // If no language was still found, use the 'no language' value.
  648. if (empty($langcode)) {
  649. $langcode = LANGUAGE_NONE;
  650. }
  651. // Work-around for initial entity creation where a language was selection
  652. // but where it's different to the form's value.
  653. if (!isset($entity->metatags[$langcode]) && isset($entity->metatags[LANGUAGE_NONE])) {
  654. $entity->metatags[$langcode] = $entity->metatags[LANGUAGE_NONE];
  655. unset($entity->metatags[LANGUAGE_NONE]);
  656. }
  657. // Support for Workbench Moderation v1.
  658. if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
  659. return;
  660. }
  661. metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $langcode);
  662. }
  663. }
  664. /**
  665. * Implements hook_entity_update().
  666. */
  667. function metatag_entity_update($entity, $entity_type) {
  668. if (!metatag_entity_supports_metatags($entity_type)) {
  669. return;
  670. }
  671. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  672. $revision_id = intval($revision_id);
  673. if (isset($entity->metatags)) {
  674. // Determine the entity's new language. This will always be accurate as the
  675. // language value will already have been updated by the time this function
  676. // executes, and it will be loaded for the correct edit process.
  677. $new_language = metatag_entity_get_language($entity_type, $entity);
  678. // If applicable, determine the entity's original language. This cannot be
  679. // obtained via the normal API as that data will already have been updated,
  680. // instead check to see if the entity has an old-fasioned 'language' value.
  681. if (isset($entity->original) && isset($entity->language) && isset($entity->original->language)) {
  682. $old_language = $entity->original->language;
  683. // If the language has changed then additional checking needs to be done.
  684. // Need to compare against the entity's raw language value as they will
  685. // be different when updating a translated entity, versus an untranslated
  686. // entity or a source entity for translation, and give a false positive.
  687. if ($new_language == $entity->language && $new_language != $old_language) {
  688. // If this entity is not translated, or if it is translated but the
  689. // translation was previously created, then some language cleanup needs
  690. // to be done.
  691. if (!isset($entity->translation) || (isset($entity->translation) && !empty($entity->translation['created']))) {
  692. // Delete the old language record. This will not affect old revisions.
  693. db_delete('metatag')
  694. ->condition('entity_type', $entity_type)
  695. ->condition('entity_id', $entity_id)
  696. ->condition('revision_id', $revision_id)
  697. ->condition('language', $old_language)
  698. ->execute();
  699. // Swap out the metatag values for the two languages.
  700. if (isset($entity->metatags[$old_language])) {
  701. $entity->metatags[$new_language] = $entity->metatags[$old_language];
  702. unset($entity->metatags[$old_language]);
  703. }
  704. }
  705. }
  706. }
  707. // Support for Workbench Moderation v1.
  708. if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
  709. return;
  710. }
  711. // Save the record.
  712. $old_vid = isset($entity->old_vid) ? $entity->old_vid : NULL;
  713. metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $new_language, $old_vid);
  714. }
  715. else {
  716. // Still ensure the meta tag output is cached.
  717. metatag_metatags_cache_clear($entity_type, $entity_id);
  718. }
  719. }
  720. /**
  721. * Implements hook_entity_delete().
  722. */
  723. function metatag_entity_delete($entity, $entity_type) {
  724. list($entity_id) = entity_extract_ids($entity_type, $entity);
  725. metatag_metatags_delete($entity_type, $entity_id);
  726. }
  727. /**
  728. * Implements hook_field_attach_delete_revision().
  729. */
  730. function metatag_field_attach_delete_revision($entity_type, $entity) {
  731. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  732. $revision_id = intval($revision_id);
  733. metatag_metatags_delete($entity_type, $entity_id, $revision_id);
  734. }
  735. /**
  736. * Implements hook_entity_view().
  737. *
  738. * Provides additional argument to allow the display to be forced, to work
  739. * around problems elsewhere in the APIs.
  740. */
  741. function metatag_entity_view($entity, $entity_type, $view_mode, $langcode, $force = FALSE) {
  742. // Only run this function once per page load.
  743. static $i_will_say_this_only_once = FALSE;
  744. // Only proceed if this entity object is the page being viewed.
  745. if (_metatag_entity_is_page($entity_type, $entity)) {
  746. // Some API calls need to force the data loading.
  747. if (!$force) {
  748. // Only run this function once per page load.
  749. if ($i_will_say_this_only_once) {
  750. return;
  751. }
  752. $i_will_say_this_only_once = TRUE;
  753. }
  754. // CTools uses 'page_manager' view mode to indicate the full entity display
  755. // page rather than 'full', so streamline the internal processes.
  756. if ($view_mode == 'page_manager') {
  757. $view_mode = 'full';
  758. }
  759. // Generate metatags output.
  760. if ($output = metatag_generate_entity_metatags($entity, $entity_type, $langcode, $view_mode)) {
  761. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  762. $instance = "{$entity_type}:{$bundle}";
  763. // We need to register the term's metatags, so we can later fetch them.
  764. // @see metatag_page_build().
  765. metatag_page_set_metatags($instance, $output);
  766. }
  767. }
  768. }
  769. /**
  770. * Generate the metatags for a given entity.
  771. *
  772. * @param object $entity
  773. * The entity object to generate the metatags for.
  774. * @param string $entity_type
  775. * The entity type of the entity.
  776. * @param string $langcode
  777. * The language code used for rendering the entity.
  778. * @param string $view_mode
  779. * The view mode the entity is rendered in.
  780. * @param bool $cached
  781. * TRUE if metatags can be loaded from and saved to the cache. FALSE if the
  782. * cache should be bypassed.
  783. *
  784. * @return array
  785. * A renderable array of metatags for the given entity.
  786. */
  787. function metatag_generate_entity_metatags($entity, $entity_type, $langcode = NULL, $view_mode = 'full', $cached = TRUE) {
  788. // If this entity object isn't allowed meta tags, don't continue.
  789. if (!metatag_entity_has_metatags($entity_type, $entity)) {
  790. return array();
  791. }
  792. // Obtain some details of the entity that are needed elsewhere.
  793. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  794. $revision_id = intval($revision_id);
  795. // Check if a specific metatag config exists, otherwise just use the global
  796. // one, stripping out the bundle.
  797. $instance = "{$entity_type}:{$bundle}";
  798. if (!metatag_config_load_with_defaults($instance, FALSE)) {
  799. $instance = "{$entity_type}";
  800. }
  801. // Determine the language this entity actually uses.
  802. $entity_language = metatag_entity_get_language($entity_type, $entity);
  803. // If no language was requested, try the language defined for this page
  804. // request.
  805. if (empty($langcode)) {
  806. $langcode = $GLOBALS['language_content']->language;
  807. }
  808. // This entity doesn't have any languages defined, i.e. it uses 'und'. This
  809. // can't conflict with loading the wrong language as entities either have no
  810. // language or they have specific one(s), they can't have both.
  811. if ($entity_language == LANGUAGE_NONE) {
  812. $langcode = LANGUAGE_NONE;
  813. }
  814. // If there are no meta tags for the currently identified language, and there
  815. // *are* meta tags defined for the entity's default language, use the entity's
  816. // default language's values, unless the "Don't load entity's default
  817. // language values if no languages match" option is enabled on the advanced
  818. // settings page.
  819. elseif (empty($entity->metatags[$langcode]) && !empty($entity->metatags[$entity_language]) && !variable_get('metatag_entity_no_lang_default', FALSE)) {
  820. $langcode = $entity_language;
  821. }
  822. // Other scenarios.
  823. else {
  824. // There's no need to do anything else - either there are meta tag values
  825. // created for the requested language or there aren't.
  826. }
  827. $cid = FALSE;
  828. if ($cached) {
  829. // All applicable pieces for this current page.
  830. $cid_parts = array(
  831. 'entity_type' => $entity_type,
  832. 'bundle' => $bundle,
  833. 'entity_id' => $entity_id,
  834. 'revision_id' => $revision_id,
  835. // Cache separately based on the language of the passed-in entity and the
  836. // overall active language of the page.
  837. 'langcode' => $langcode,
  838. 'language_content' => $GLOBALS['language_content']->language,
  839. 'view_mode' => $view_mode,
  840. );
  841. $cid = metatag_cache_default_cid_parts($cid_parts);
  842. }
  843. if ($cid && $cache = metatag_cache_get($cid)) {
  844. $output = $cache->data;
  845. }
  846. else {
  847. // Separate the meta tags.
  848. $metatags = isset($entity->metatags) ? $entity->metatags : array();
  849. // Build options for meta tag rendering.
  850. $options = array(
  851. 'entity' => $entity,
  852. 'entity_type' => $entity_type,
  853. 'view_mode' => $view_mode,
  854. );
  855. // Ensure we actually pass a language object rather than language code.
  856. $languages = language_list();
  857. if (isset($languages[$langcode])) {
  858. $options['language'] = $languages[$langcode];
  859. }
  860. // Reload the entity object from cache as it may have been altered.
  861. $token_type = token_get_entity_mapping('entity', $entity_type);
  862. $entities = entity_load($entity_type, array($entity_id));
  863. $options['token data'][$token_type] = $entities[$entity_id];
  864. $options['entity'] = $entities[$entity_id];
  865. // Render the metatags and save to the cache.
  866. $output = metatag_metatags_view($instance, $metatags, $options);
  867. if ($cid) {
  868. metatag_cache_set($cid, $output);
  869. }
  870. }
  871. return $output;
  872. }
  873. /**
  874. * Generate the metatags for a given entity.
  875. *
  876. * @param object $entity_id
  877. * The entity id of the entity to generate the metatags for.
  878. * @param string $entity_type
  879. * The entity type of the entity to generate the metatags for.
  880. * @param string $langcode
  881. * The language code used for rendering the entity.
  882. *
  883. * @return array
  884. * A renderable array of metatags for the given entity.
  885. */
  886. function metatags_get_entity_metatags($entity_id, $entity_type, $langcode = NULL) {
  887. $entities = entity_load($entity_type, array($entity_id));
  888. $entity = reset($entities);
  889. return !empty($entity) ? metatag_generate_entity_metatags($entity, $entity_type, $langcode) : array();
  890. }
  891. /**
  892. * Build a renderable array of meta tag output.
  893. *
  894. * @param string $instance
  895. * The configuration instance key of the meta tags to use, e.g.
  896. * "node:article".
  897. * @param array $metatags
  898. * An array of meta tag data.
  899. * @param array $options
  900. * (optional) An array of options including the following keys and values:
  901. * - language: A language object.
  902. * - token data: An array of data to pass into token_replace() during
  903. * meta tag value generation.
  904. */
  905. function metatag_metatags_view($instance, array $metatags = array(), array $options = array()) {
  906. $output = array();
  907. // Convert language codes to a language object.
  908. if (isset($options['language']) && is_string($options['language'])) {
  909. $languages = language_list();
  910. $options['language'] = isset($languages[$options['language']]) ? $languages[$options['language']] : NULL;
  911. }
  912. // If there are any tags, determine the translation to display.
  913. if (!empty($metatags)) {
  914. // Get the display language; default to the entity's language.
  915. if (isset($options['language']) && isset($options['language']->language) && isset($metatags[$options['language']->language])) {
  916. $metatags = $metatags[$options['language']->language];
  917. }
  918. // If no language requested, use the no-language value.
  919. elseif (!empty($metatags[LANGUAGE_NONE])) {
  920. $metatags = $metatags[LANGUAGE_NONE];
  921. }
  922. else {
  923. $metatags = array();
  924. }
  925. }
  926. // Add any default tags to the mix.
  927. $metatags += metatag_config_load_with_defaults($instance);
  928. $options['instance'] = $instance;
  929. foreach ($metatags as $metatag => $data) {
  930. if ((!empty($data['value']) || (isset($data['value']) && is_numeric($data['value'])))
  931. && $metatag_instance = metatag_get_instance($metatag, $data)) {
  932. $output[$metatag] = $metatag_instance->getElement($options);
  933. }
  934. }
  935. // Allow the output meta tags to be modified using
  936. // hook_metatag_metatags_view_alter().
  937. drupal_alter('metatag_metatags_view', $output, $instance, $options);
  938. return $output;
  939. }
  940. function metatag_metatags_values($instance, array $metatags = array(), array $options = array()) {
  941. $values = array();
  942. // Apply defaults to the data for each language.
  943. foreach ($metatags as $language => $metatag) {
  944. $metatags[$language] += metatag_config_load_with_defaults($instance);
  945. }
  946. // Generate output only if we have a valid language.
  947. if (isset($options['language']) && is_string($options['language']) && isset($metatags[$options['language']])) {
  948. $language = $options['language'];
  949. // Convert language codes to a language object.
  950. $languages = language_list();
  951. $options['language'] = isset($languages[$language]) ? $languages[$language] : NULL;
  952. $options['instance'] = $instance;
  953. // Get output elements.
  954. foreach ($metatags[$language] as $metatag => $data) {
  955. if ($metatag_instance = metatag_get_instance($metatag, $data)) {
  956. $values[$metatag] = $metatag_instance->getValue($options);
  957. }
  958. }
  959. }
  960. return array_filter($values, 'drupal_strlen');
  961. }
  962. /**
  963. * Build a FAPI array for editing meta tags.
  964. *
  965. * @param array $form
  966. * The current FAPI array.
  967. * @param string $instance
  968. * The configuration instance key of the metatags to use, e.g. "node:article".
  969. * @param array $metatags
  970. * An array of metatag data.
  971. * @param array $options
  972. * (optional) An array of options including the following keys and values:
  973. * - token types: An array of token types to be passed to theme_token_tree().
  974. */
  975. function metatag_metatags_form(array &$form, $instance, array $metatags = array(), array $options = array()) {
  976. $info = metatag_get_info();
  977. if (empty($info['tags'])) {
  978. return;
  979. }
  980. // Work out the language code to use, default to NONE.
  981. $langcode = LANGUAGE_NONE;
  982. if (isset($form['#entity_type']) && isset($form['#entity'])) {
  983. $langcode = metatag_entity_get_language($form['#entity_type'], $form['#entity']);
  984. }
  985. // Merge in the default options.
  986. $options += array(
  987. 'token types' => array(),
  988. 'defaults' => metatag_config_load_with_defaults($instance),
  989. 'instance' => $instance,
  990. );
  991. $form['metatags'] = array(
  992. '#type' => 'fieldset',
  993. '#title' => t('Meta tags'),
  994. '#collapsible' => TRUE,
  995. '#collapsed' => TRUE,
  996. '#multilingual' => TRUE,
  997. '#tree' => TRUE,
  998. '#access' => user_access('edit meta tags') || user_access('administer meta tags'),
  999. '#weight' => 40,
  1000. '#language' => $langcode,
  1001. '#attributes' => array(
  1002. 'class' => array('metatags-form'),
  1003. ),
  1004. );
  1005. $form['metatags'][$langcode] = array(
  1006. '#metatag_defaults' => $options['defaults'],
  1007. '#type' => 'container',
  1008. '#multilingual' => TRUE,
  1009. '#tree' => TRUE,
  1010. );
  1011. // Show a different intro message for entity pages vs config pages.
  1012. if (isset($form['#entity'])) {
  1013. $form['metatags'][$langcode]['intro_text'] = array(
  1014. '#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>',
  1015. '#weight' => -10,
  1016. );
  1017. }
  1018. else {
  1019. $form['metatags'][$langcode]['intro_text'] = array(
  1020. '#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>',
  1021. '#weight' => -10,
  1022. );
  1023. }
  1024. // Only support vertical tabs if there is a vertical tab element.
  1025. foreach (element_children($form) as $key) {
  1026. if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'vertical_tabs') {
  1027. $form['metatags']['#group'] = $key;
  1028. $form['metatags']['#attached']['js']['vertical-tabs'] = drupal_get_path('module', 'metatag') . '/metatag.vertical-tabs.js';
  1029. break;
  1030. }
  1031. }
  1032. // Merge in the default meta tag configurations.
  1033. $metatags += $options['defaults'];
  1034. // This will be used later.
  1035. $group_metatag_access = array();
  1036. // Build the form for each metatag.
  1037. foreach ($info['tags'] as $metatag => $metatag_info) {
  1038. // @todo Replace context matching with hook_metatag_access().
  1039. if (isset($options['context']) && isset($metatag_info['context'])) {
  1040. if (!in_array($options['context'], $metatag_info['context'])) {
  1041. continue;
  1042. }
  1043. }
  1044. $metatag_instance = metatag_get_instance($metatag, isset($metatags[$metatag]) ? $metatags[$metatag] : array());
  1045. if (empty($metatag_instance)) {
  1046. continue;
  1047. }
  1048. // Get the form element from the meta tag class.
  1049. $metatag_form = $metatag_instance->getForm($options);
  1050. // Add a default value form element.
  1051. if (isset($options['defaults'][$metatag]['value'])) {
  1052. $metatag_form['default'] = array(
  1053. '#type' => 'hidden',
  1054. '#value' => $options['defaults'][$metatag]['value'],
  1055. );
  1056. }
  1057. // Optional extended edit permissions.
  1058. if (variable_get('metatag_extended_permissions', FALSE)) {
  1059. $metatag_form['#access'] = user_access('edit meta tag: ' . $metatag) || user_access('administer meta tags');
  1060. }
  1061. else {
  1062. $metatag_form['#access'] = $form['metatags']['#access'];
  1063. }
  1064. if (!empty($metatag_info['group'])) {
  1065. $group_key = $metatag_info['group'];
  1066. if (isset($info['groups'][$group_key]['label']) && !isset($form['metatags'][$langcode][$group_key])) {
  1067. $group = $info['groups'][$group_key] + array('form' => array(), 'description' => NULL);
  1068. $form['metatags'][$langcode][$group_key] = $group['form'] + array(
  1069. '#type' => 'fieldset',
  1070. '#title' => check_plain($group['label']),
  1071. '#description' => filter_xss($group['description']),
  1072. '#collapsible' => TRUE,
  1073. '#collapsed' => TRUE,
  1074. );
  1075. }
  1076. $form['metatags'][$langcode][$group_key][$metatag] = $metatag_form + array('#parents' => array('metatags', $langcode, $metatag));
  1077. // Hide the fieldset itself if there is not at least one of the meta tag
  1078. // fields visible.
  1079. if (variable_get('metatag_extended_permissions', FALSE)) {
  1080. $form['metatags'][$langcode][$group_key]['#access'] = count(element_get_visible_children($form['metatags'][$langcode][$group_key])) > 0;
  1081. }
  1082. else {
  1083. $form['metatags'][$langcode][$group_key]['#access'] = $form['metatags']['#access'];
  1084. }
  1085. // Structure the access parameter into this array, and make use of it
  1086. // later when we move on. Besides, this foreach is getting heavy.
  1087. $group_metatag_access[$group_key] = $form['metatags'][$langcode][$group_key]['#access'];
  1088. }
  1089. else {
  1090. $form['metatags'][$langcode][$metatag] = $metatag_form;
  1091. }
  1092. }
  1093. // Hide the fieldset itself if there is not at least one of the meta tag
  1094. // fields visible; only bother checking this if the user had edit access in
  1095. // the first place.
  1096. if ($form['metatags']['#access'] && variable_get('metatag_extended_permissions', FALSE)) {
  1097. $form['metatags']['#access'] = count(element_get_visible_children($form['metatags'][$langcode])) > 0;
  1098. }
  1099. // Check the #access of each group. If it passed, we display options for
  1100. // tokens. By this we update the #description of each group.
  1101. if ($form['metatags']['#access']) {
  1102. // Built the token list.
  1103. $token_listing_link = theme('token_tree', array('token_types' => $options['token types'], 'dialog' => TRUE));
  1104. // Add the token list to the top of the fieldset.
  1105. $form['metatags'][$langcode]['#description'] = $token_listing_link;
  1106. // Check if each meta tag group is being displayed.
  1107. if (!empty($group_metatag_access)) {
  1108. foreach ($group_metatag_access as $group_key => $token_access) {
  1109. if ($token_access) {
  1110. // Update the description.
  1111. if (isset($form['metatags'][$langcode][$group_key]['#description'])) {
  1112. $form['metatags'][$langcode][$group_key]['#description'] .= '<br />';
  1113. }
  1114. else {
  1115. $form['metatags'][$langcode][$group_key]['#description'] = '';
  1116. }
  1117. $form['metatags'][$langcode][$group_key]['#description'] .= $token_listing_link;
  1118. }
  1119. }
  1120. }
  1121. }
  1122. // Add a submit handler to compare the submitted values against the deafult
  1123. // values.
  1124. $form += array('#submit' => array());
  1125. array_unshift($form['#submit'], 'metatag_metatags_form_submit');
  1126. }
  1127. /**
  1128. * Form API submission callback.
  1129. *
  1130. * Unset meta tag values that equal their default values, and load any
  1131. * additional meta tag values for other languages so that they can be properly
  1132. * saved later on.
  1133. *
  1134. * @see metatag_metatags_save()
  1135. */
  1136. function metatag_metatags_form_submit($form, &$form_state) {
  1137. if (!empty($form_state['values']['metatags'])) {
  1138. // Unset meta tag values that equal their default values.
  1139. foreach ($form_state['values']['metatags'] as $langcode => $values) {
  1140. if (!empty($form['metatags'][$langcode]['#metatag_defaults'])) {
  1141. metatag_filter_values_from_defaults($form_state['values']['metatags'][$langcode], $form['metatags'][$langcode]['#metatag_defaults']);
  1142. }
  1143. }
  1144. // Need to load the entity's values for other languages, otherwise they will
  1145. // be incorrectly deleted later on.
  1146. if (isset($form['#entity']) && !empty($form['#entity']->metatags)) {
  1147. foreach ($form['#entity']->metatags as $langcode => $values) {
  1148. if (!isset($form_state['values']['metatags'][$langcode])) {
  1149. $form_state['values']['metatags'][$langcode] = $values;
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. /**
  1156. * Implements hook_field_extra_fields().
  1157. */
  1158. function metatag_field_extra_fields() {
  1159. $extra = array();
  1160. foreach (entity_get_info() as $entity_type => $entity_info) {
  1161. foreach (array_keys($entity_info['bundles']) as $bundle) {
  1162. if (metatag_entity_supports_metatags($entity_type, $bundle)) {
  1163. $extra[$entity_type][$bundle]['form']['metatags'] = array(
  1164. 'label' => t('Meta tags'),
  1165. 'description' => t('Meta tag module form elements.'),
  1166. 'weight' => 40,
  1167. );
  1168. }
  1169. }
  1170. }
  1171. return $extra;
  1172. }
  1173. /**
  1174. * Check if an individual entity has meta tags defined, or has defaults.
  1175. *
  1176. * @param string $entity_type
  1177. * An entity type.
  1178. * @param object $entity
  1179. * An entity object.
  1180. *
  1181. * @return boolean
  1182. * TRUE or FALSE if the entity should have a form for or process meta tags.
  1183. */
  1184. function metatag_entity_has_metatags($entity_type, $entity) {
  1185. // If an entity has custom meta tags assigned, then we should return TRUE.
  1186. if (!empty($entity->metatags)) {
  1187. return TRUE;
  1188. }
  1189. // Otherwise, check to see if there exists any enabed configuration for
  1190. // either the entity type, or bundle (even if the configuration is empty).
  1191. // If no configuration exists, then we should not be displaying the meta tag
  1192. // forms or processing meta tags on entity view.
  1193. $config_exists = &drupal_static(__FUNCTION__, array());
  1194. list( , , $bundle) = entity_extract_ids($entity_type, $entity);
  1195. // Do not pretend to have metatags when the bundle does not support them.
  1196. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  1197. return FALSE;
  1198. }
  1199. $instance = "{$entity_type}:{$bundle}";
  1200. if (!isset($config_exists[$instance])) {
  1201. // Check if the intstance or its parents (excluding global) are enabled.
  1202. $config_exists[$instance] = metatag_config_is_enabled($instance, TRUE, FALSE);
  1203. }
  1204. return !empty($config_exists[$instance]);
  1205. }
  1206. /**
  1207. * Check whether the requested entity type (and bundle) support metatag.
  1208. *
  1209. * By default this will be FALSE, support has to be specifically enabled by
  1210. * assigning 'metatag' => TRUE within the hook_entity_info() definition for the
  1211. * entity.
  1212. */
  1213. function metatag_entity_supports_metatags($entity_type = NULL, $bundle = NULL) {
  1214. $entity_types = &drupal_static(__FUNCTION__);
  1215. if (!isset($entity_types)) {
  1216. $entity_types = array();
  1217. foreach (entity_get_info() as $entity_type_key => $entity_info) {
  1218. if (empty($entity_info['metatags'])) {
  1219. $entity_types[$entity_type_key] = FALSE;
  1220. continue;
  1221. }
  1222. $entity_types[$entity_type_key] = array();
  1223. foreach ($entity_info['bundles'] as $bundle_key => $bundle_info) {
  1224. $entity_types[$entity_type_key][$bundle_key] = !isset($bundle_info['metatags']) || !empty($bundle_info['metatags']);
  1225. }
  1226. }
  1227. }
  1228. if (isset($entity_type) && isset($bundle)) {
  1229. // Allow entities to be disabled by assigning a variable
  1230. // 'metatag_enable_{$entity_type}__{$bundle}' the value FALSE, e.g.:
  1231. //
  1232. // // Disable metatags for carousel nodes.
  1233. // $conf['metatag_enable_node__carousel'] = FALSE;
  1234. //
  1235. // @see Advanced settings page.
  1236. if (variable_get('metatag_enable_' . $entity_type . '__' . $bundle, 'monkey') == FALSE) {
  1237. return FALSE;
  1238. }
  1239. return isset($entity_types[$entity_type][$bundle]) ? $entity_types[$entity_type][$bundle] : FALSE;
  1240. }
  1241. elseif (isset($entity_type)) {
  1242. // Allow entities to be disabled by assigning a variable
  1243. // 'metatag_enable_{$entity_type}' the value FALSE, e.g.:
  1244. //
  1245. // // Disable metatags for file_entity.
  1246. // $conf['metatag_enable_file'] = FALSE;
  1247. //
  1248. // @see Advanced settings page.
  1249. if (variable_get('metatag_enable_' . $entity_type, 'monkey') == FALSE) {
  1250. return FALSE;
  1251. }
  1252. return isset($entity_types[$entity_type]) ? ($entity_types[$entity_type] !== FALSE) : FALSE;
  1253. }
  1254. return $entity_types;
  1255. }
  1256. /**
  1257. * Implements hook_entity_info_alter().
  1258. *
  1259. * Enables Metatag support for the core entities.
  1260. */
  1261. function metatag_entity_info_alter(&$info) {
  1262. $defaults['node'] = array(
  1263. 'path' => 'node/%node',
  1264. 'metatags' => TRUE,
  1265. );
  1266. $defaults['user'] = array(
  1267. 'path' => 'user/%user',
  1268. 'metatags' => TRUE,
  1269. );
  1270. $defaults['taxonomy_term'] = array(
  1271. 'path' => 'taxonomy/term/%taxonomy_term',
  1272. 'metatags' => TRUE,
  1273. );
  1274. // Just running taxonomy_vocabulary_load() here would cause problems for
  1275. // EntityCache in certain circumstances, so instead the query is executed
  1276. // directly instead.
  1277. if (module_exists('forum') && ($vocab_id = variable_get('forum_nav_vocabulary', 0))) {
  1278. $vocab_name = db_query("SELECT machine_name FROM {taxonomy_vocabulary} WHERE vid = :vid", array(':vid' => $vocab_id))->fetchField();
  1279. if (!empty($vocab_name)) {
  1280. $defaults['taxonomy_term']['bundles'][$vocab_name]['path'] = 'forum/%taxonomy_term';
  1281. }
  1282. }
  1283. foreach ($defaults as $key => $entity_defaults) {
  1284. if (isset($info[$key])) {
  1285. $info[$key] = drupal_array_merge_deep($entity_defaults, $info[$key]);
  1286. }
  1287. }
  1288. }
  1289. /**
  1290. * Given a path determine if it is an entity default path.
  1291. *
  1292. * @param $path
  1293. * The internal path. The id of the entity should be in the string as '[id]'.
  1294. * @return
  1295. * An array with the entity type and the loaded entity object.
  1296. */
  1297. function metatag_load_entity_from_path($path) {
  1298. $entity_paths = &drupal_static(__FUNCTION__);
  1299. $result = FALSE;
  1300. if (!isset($entity_paths)) {
  1301. $entity_paths = array();
  1302. foreach (entity_get_info() as $entity_type => $entity_info) {
  1303. if (isset($entity_info['default path'])) {
  1304. $default_path = $entity_info['default path'];
  1305. $default_path = preg_quote($default_path, '/');
  1306. $default_path = str_replace('\[id\]', '(\d+)', $default_path);
  1307. $entity_paths[$entity_type] = $default_path;
  1308. }
  1309. }
  1310. }
  1311. foreach ($entity_paths as $entity_type => $default_path) {
  1312. if (preg_match("/^{$default_path}$/", $path, $matches)) {
  1313. if ($entity = entity_load($entity_type, array($matches[1]))) {
  1314. $result = array('entity_type' => $entity_type, 'entity' => reset($entity));
  1315. }
  1316. break;
  1317. }
  1318. }
  1319. // Allow other modules to customize the data using
  1320. // hook_metatag_load_entity_from_path_alter().
  1321. drupal_alter('metatag_load_entity_from_path', $path, $result);
  1322. return $result;
  1323. }
  1324. /**
  1325. * Add meta tags to be added later with metatag_page_build().
  1326. *
  1327. * @param string $instance
  1328. * The configuration instance key of the meta tags, e.g. "node:article".
  1329. * @param array $metatags
  1330. * An array of meta tags from metatag_metatags_view().
  1331. */
  1332. function metatag_page_set_metatags($instance, $metatags) {
  1333. $page_metatags = &drupal_static(__FUNCTION__, array());
  1334. $page_metatags[$instance] = $metatags;
  1335. }
  1336. /**
  1337. * Retrieve the array of meta tags to be added with metatag_page_build().
  1338. */
  1339. function metatag_page_get_metatags() {
  1340. // @todo Add alter to this result?
  1341. return drupal_static('metatag_page_set_metatags', array());
  1342. }
  1343. /**
  1344. * Implements hook_page_build().
  1345. */
  1346. function metatag_page_build(&$page) {
  1347. // By default do not add meta tags to admin pages. To enable meta tags on
  1348. // admin pages set the 'metatag_tag_admin_pages' variable to TRUE.
  1349. if (path_is_admin(current_path()) && !variable_get('metatag_tag_admin_pages', FALSE)) {
  1350. return;
  1351. }
  1352. // Ensure these arrays exist, otherwise several use cases will fail.
  1353. if (!isset($page['content']) || !is_array($page['content'])) {
  1354. $page['content'] = array();
  1355. }
  1356. if (!isset($page['content']['metatags']) || !is_array($page['content']['metatags'])) {
  1357. $page['content']['metatags'] = array();
  1358. }
  1359. // The front page has special consideration. Also, check if this is an error
  1360. // (403/404) page, those also require separate handling.
  1361. $instance = 'global:frontpage';
  1362. if ((drupal_is_front_page() && metatag_config_is_enabled($instance))
  1363. || ($instance = metatag_is_error_page())) {
  1364. // Generate the cache ID.
  1365. $cid_parts = array(
  1366. 'instance' => $instance,
  1367. );
  1368. $cid = metatag_cache_default_cid_parts($cid_parts);
  1369. if ($cache = metatag_cache_get($cid)) {
  1370. $metatags = $cache->data;
  1371. }
  1372. else {
  1373. $metatags = metatag_metatags_view($instance, array());
  1374. metatag_cache_set($cid, $metatags);
  1375. }
  1376. $page['content']['metatags'][$instance] = $metatags;
  1377. }
  1378. // Load any meta tags assigned via metatag_page_set_metatags(). Note: this
  1379. // must include the necessary defaults.
  1380. else {
  1381. $page['content']['metatags'] += metatag_page_get_metatags();
  1382. }
  1383. // If no meta tags were loaded at least load the global defaults. This may be
  1384. // disabled, see README.txt for details.
  1385. if (empty($page['content']['metatags']) && variable_get('metatag_load_all_pages', TRUE)) {
  1386. $instance = 'global';
  1387. // Generate the cache ID.
  1388. $cid_parts = array(
  1389. 'instance' => $instance,
  1390. 'path' => request_path(),
  1391. );
  1392. $cid = metatag_cache_default_cid_parts($cid_parts);
  1393. if ($cache = metatag_cache_get($cid)) {
  1394. $metatags = $cache->data;
  1395. }
  1396. else {
  1397. $metatags = metatag_metatags_view($instance, array());
  1398. metatag_cache_set($cid, $metatags);
  1399. }
  1400. $page['content']['metatags'][$instance] = $metatags;
  1401. }
  1402. }
  1403. /**
  1404. * Returns whether the current page is the page of the passed in entity.
  1405. *
  1406. * @param $entity_type
  1407. * The entity type; e.g. 'node' or 'user'.
  1408. * @param $entity
  1409. * The entity object.
  1410. *
  1411. * @return
  1412. * TRUE if the current page is the page of the specified entity, or FALSE
  1413. * otherwise.
  1414. */
  1415. function _metatag_entity_is_page($entity_type, $entity) {
  1416. // Exclude comment entities as this conflicts with comment_fragment.module.
  1417. if ($entity_type == 'comment') {
  1418. return;
  1419. }
  1420. $uri = entity_uri($entity_type, $entity);
  1421. $current_path = current_path();
  1422. // Support for Workbench Moderation v1 - if this is a node, check if the
  1423. // content type supports moderation.
  1424. if ($entity_type == 'node' && function_exists('workbench_moderation_node_type_moderated') && workbench_moderation_node_type_moderated($entity->type) === TRUE) {
  1425. return !empty($uri['path']) && ($current_path == $uri['path'] || $current_path == $uri['path'] . '/draft');
  1426. }
  1427. // Support for core node revisions.
  1428. elseif (!empty($uri['path']) && strpos($current_path, $uri['path']) === 0 && strpos($current_path, '/revisions/') && strpos($current_path, '/view')) {
  1429. return TRUE;
  1430. }
  1431. // Any other page.
  1432. else {
  1433. return !empty($uri['path']) && $current_path == $uri['path'];
  1434. }
  1435. }
  1436. /**
  1437. * Implements hook_field_attach_rename_bundle().
  1438. */
  1439. function metatag_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  1440. $instance_old = $entity_type . ':' . $bundle_old;
  1441. $instance_new = $entity_type . ':' . $bundle_new;
  1442. if ($config = metatag_config_load($instance_old)) {
  1443. $config->instance = $instance_new;
  1444. metatag_config_save($config);
  1445. metatag_config_delete($instance_old);
  1446. }
  1447. }
  1448. /**
  1449. * Implements hook_field_attach_delete_bundle().
  1450. */
  1451. function metatag_field_attach_delete_bundle($entity_type, $bundle) {
  1452. $instance = $entity_type . ':' . $bundle;
  1453. metatag_config_delete($instance);
  1454. }
  1455. /**
  1456. * Implements hook_field_attach_form().
  1457. */
  1458. function metatag_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  1459. if (!metatag_entity_has_metatags($entity_type, $entity)) {
  1460. return;
  1461. }
  1462. // Entity_Translation will trigger this hook again, skip it.
  1463. if (!empty($form_state['entity_translation']['is_translation'])) {
  1464. return;
  1465. }
  1466. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  1467. $instance = "{$entity_type}:{$bundle}";
  1468. // Grab the meta tags for display in the form if there are any.
  1469. if (!empty($entity->metatags)) {
  1470. // Identify the language to use with this entity.
  1471. $entity_language = metatag_entity_get_language($entity_type, $entity);
  1472. // If this is a new translation using Entity Translation, load the meta
  1473. // tags from the entity's original language.
  1474. 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()])) {
  1475. $metatags = $entity->metatags[$handler->getSourceLanguage()];
  1476. }
  1477. // Determine from where we should get the tags.
  1478. elseif (isset($entity->metatags[$langcode])) {
  1479. // Set the tags to the translation set matching that of the form.
  1480. $metatags = $entity->metatags[$langcode];
  1481. }
  1482. // There is no translation for this entity's tags in the current
  1483. // language. Instead, display tags in the language of the entity, the
  1484. // source language of translations. The will provide translators with the
  1485. // original text to translate.
  1486. elseif (isset($entity->metatags[$entity_language])) {
  1487. $metatags = $entity->metatags[$entity_language];
  1488. }
  1489. // This is a preview so set the tags to the raw submission data. No
  1490. // language has been set.
  1491. else {
  1492. $metatags = $entity->metatags;
  1493. }
  1494. }
  1495. else {
  1496. $metatags = array();
  1497. }
  1498. $options['token types'] = array(token_get_entity_mapping('entity', $entity_type));
  1499. $options['context'] = $entity_type;
  1500. // Allow hook_metatag_token_types_alter() to modify the defined tokens.
  1501. drupal_alter('metatag_token_types', $options);
  1502. // @todo Remove metatag_form_alter() when http://drupal.org/node/1284642 is fixed in core.
  1503. //metatag_metatags_form($form, $instance, $metatags, $options);
  1504. $form['#metatags'] = array(
  1505. 'instance' => $instance,
  1506. 'metatags' => $metatags,
  1507. 'options' => $options,
  1508. );
  1509. }
  1510. /**
  1511. * Implements hook_form_alter().
  1512. *
  1513. * @todo Remove this when http://drupal.org/node/1284642 is fixed in core.
  1514. */
  1515. function metatag_form_alter(&$form, $form_state, $form_id) {
  1516. if (!empty($form['#metatags']) && !isset($form['metatags'])) {
  1517. extract($form['#metatags']);
  1518. metatag_metatags_form($form, $instance, $metatags, $options);
  1519. unset($form['#metatags']);
  1520. }
  1521. }
  1522. /**
  1523. * Get the meta tag information array of a meta tag.
  1524. *
  1525. * @param $metatag
  1526. * The meta tag name, e.g. description, for which the info shall be returned,
  1527. * or NULL to return an array with info about all meta tags.
  1528. */
  1529. function metatag_get_info($type = NULL, $name = NULL) {
  1530. // Use the advanced drupal_static() pattern, since this is called very often.
  1531. static $drupal_static_fast;
  1532. if (!isset($drupal_static_fast)) {
  1533. $drupal_static_fast['metatag_info'] = &drupal_static(__FUNCTION__);
  1534. }
  1535. $info = &$drupal_static_fast['metatag_info'];
  1536. global $language;
  1537. if (!isset($info)) {
  1538. // hook_metatag_info() includes translated strings, so each language is cached
  1539. // separately.
  1540. $cid = 'info:' . $language->language;
  1541. if ($cache = metatag_cache_get($cid)) {
  1542. $info = $cache->data;
  1543. }
  1544. else {
  1545. // Obtain all metatag specs defined in other modules using
  1546. // hook_metatag_info().
  1547. $info = module_invoke_all('metatag_info');
  1548. $info += array('tags' => array(), 'groups' => array());
  1549. // Merge in default values.
  1550. foreach ($info['tags'] as $key => $data) {
  1551. $info['tags'][$key] += array(
  1552. // Merge in default values.
  1553. 'name' => $key,
  1554. 'class' => 'DrupalTextMetaTag',
  1555. );
  1556. }
  1557. // Let other modules alter the entity info using
  1558. // hook_metatag_info_alter().
  1559. drupal_alter('metatag_info', $info);
  1560. metatag_cache_set($cid, $info);
  1561. }
  1562. }
  1563. if (isset($type) && isset($name)) {
  1564. return isset($info[$type][$name]) ? $info[$type][$name] : FALSE;
  1565. }
  1566. elseif (isset($type)) {
  1567. return isset($info[$type]) ? $info[$type] : array();
  1568. }
  1569. else {
  1570. return $info;
  1571. }
  1572. }
  1573. function metatag_get_instance($metatag, array $data = array()) {
  1574. $info = metatag_get_info('tags', $metatag);
  1575. if (!empty($info['class']) && class_exists($info['class'])) {
  1576. $class = $info['class'];
  1577. return new $class($info, $data);
  1578. }
  1579. }
  1580. /**
  1581. * Return the string value of a meta tag.
  1582. *
  1583. * @param $metatag
  1584. * The meta tag string.
  1585. * @param $data
  1586. * The array of data for the meta tag class instance.
  1587. * @param $options
  1588. * An optional array of additional options to pass to the getValue() method
  1589. * of the meta tag class instance.
  1590. * - raw: A boolean if TRUE will not perform token replacement.
  1591. *
  1592. * @return
  1593. * A string value.
  1594. */
  1595. function metatag_get_value($metatag, array $data, array $options = array()) {
  1596. $value = '';
  1597. if ($metatag_instance = metatag_get_instance($metatag, $data)) {
  1598. $options["instance"] = $metatag;
  1599. $value = $metatag_instance->getValue($options);
  1600. }
  1601. return $value;
  1602. }
  1603. /**
  1604. * Set a variable to be altered in metatag_preprocess_html().
  1605. *
  1606. * @see metatag_get_preprocess_variables()
  1607. * @see metatag_preprocess_html()
  1608. * @see metatag_preprocess_maintenance_page()
  1609. */
  1610. function metatag_set_preprocess_variable($hook, $variable, $value) {
  1611. $variables = &drupal_static(__FUNCTION__, array());
  1612. $variables[$hook][$variable] = $value;
  1613. }
  1614. /**
  1615. * Return an array of variables to be altered in preprocess functions.
  1616. *
  1617. * @see metatag_set_preprocess_variable()
  1618. * @see metatag_preprocess_html()
  1619. * @see metatag_preprocess_maintenance_page()
  1620. */
  1621. function metatag_get_preprocess_variables($hook) {
  1622. $variables = drupal_static('metatag_set_preprocess_variable', array());
  1623. return isset($variables[$hook]) ? $variables[$hook] : array();
  1624. }
  1625. /**
  1626. * Implements hook_preprocess_html().
  1627. */
  1628. function metatag_preprocess_html(&$variables) {
  1629. foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
  1630. $variables[$variable] = $value;
  1631. }
  1632. }
  1633. /**
  1634. * Implements hook_preprocess_maintenance_page().
  1635. */
  1636. function metatag_preprocess_maintenance_page(&$variables) {
  1637. foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
  1638. $variables[$variable] = $value;
  1639. }
  1640. }
  1641. /**
  1642. * Implements hook_html_head_alter().
  1643. */
  1644. function metatag_html_head_alter(&$elements) {
  1645. // Remove duplicate link tags if found.
  1646. $metatags = metatag_get_info('tags');
  1647. foreach (array_keys($metatags) as $name) {
  1648. if (!isset($elements['metatag_' . $name]) || $elements['metatag_' . $name]['#tag'] != 'link') {
  1649. // Only check for link tags added by the metatags module.
  1650. continue;
  1651. }
  1652. foreach (array_keys($elements) as $key) {
  1653. if (strpos($key, 'drupal_add_html_head_link:' . $name . ':') === 0) {
  1654. unset($elements[$key]);
  1655. }
  1656. }
  1657. }
  1658. // Remove the default generator meta tag.
  1659. unset($elements['system_meta_generator']);
  1660. }
  1661. function metatag_metatag_get_form($metatag, array $data = array(), array $options = array()) {
  1662. $instance = metatag_get_instance($metatag, $data);
  1663. return $instance->getForm($options);
  1664. }
  1665. function metatag_config_instance_info($instance = NULL) {
  1666. global $language;
  1667. $info = &drupal_static(__FUNCTION__);
  1668. // hook_metatag_info() includes translated strings, so each language is cached
  1669. // separately.
  1670. $cid = 'metatag:config:instance:info:' . $language->language;
  1671. if (!isset($info)) {
  1672. if ($cache = metatag_cache_get($cid)) {
  1673. $info = $cache->data;
  1674. }
  1675. else {
  1676. // Allow modules to act upon the record insertion using
  1677. // hook_metatag_config_instance_info().
  1678. $info = module_invoke_all('metatag_config_instance_info');
  1679. // Allow other modules to customize the data using
  1680. // hook_metatag_config_instance_info_alter().
  1681. drupal_alter('metatag_config_instance_info', $info);
  1682. metatag_cache_set($cid, $info);
  1683. }
  1684. }
  1685. if (isset($instance)) {
  1686. return isset($info[$instance]) ? $info[$instance] : FALSE;
  1687. }
  1688. else {
  1689. return $info;
  1690. }
  1691. }
  1692. /**
  1693. * Filter out meta tag values that equal the default values.
  1694. *
  1695. * @todo Use information in $values[$metatag]['default'] rather than a $defaults parameter.
  1696. */
  1697. function metatag_filter_values_from_defaults(array &$values, array $defaults = array()) {
  1698. foreach ($values as $metatag => $data) {
  1699. $default = isset($data['default']) ? $data['default'] : (isset($defaults[$metatag]['value']) ? $defaults[$metatag]['value'] : NULL);
  1700. if (isset($default) && isset($data['value']) && $default === $data['value']) {
  1701. // Meta tag has a default, and it matches user-submitted value.
  1702. unset($values[$metatag]);
  1703. }
  1704. elseif (!isset($default) && (is_string($data['value']) && !drupal_strlen($data['value']) || (is_array($data['value']) && !array_filter($data['value'])))) {
  1705. // Metatag does not have a default, and user did not submit a value.
  1706. unset($values[$metatag]);
  1707. }
  1708. if (isset($values[$metatag]['default'])) {
  1709. // Unset the default hidden value.
  1710. unset($values[$metatag]['default']);
  1711. }
  1712. }
  1713. }
  1714. /**
  1715. * Return all the parents of a given configuration instance.
  1716. *
  1717. * @param $instance
  1718. * A meta tag configuration instance.
  1719. *
  1720. * @return
  1721. * An array of instances starting with the $instance parameter, with the end
  1722. * of the array being the global instance.
  1723. */
  1724. function metatag_config_get_parent_instances($instance, $include_global = TRUE) {
  1725. $parents = array();
  1726. $segments = explode(':', $instance);
  1727. while (count($segments) > 0) {
  1728. $parents[] = implode(':', $segments);
  1729. array_pop($segments);
  1730. }
  1731. if ($include_global && end($parents) !== 'global') {
  1732. $parents[] = 'global';
  1733. }
  1734. reset($parents);
  1735. return $parents;
  1736. }
  1737. /**
  1738. * Get the proper label of a configuration instance.
  1739. *
  1740. * @param $instance
  1741. * A meta tag configuration instance.
  1742. */
  1743. function metatag_config_instance_label($instance) {
  1744. $labels = &drupal_static(__FUNCTION__, array());
  1745. if (!isset($labels[$instance])) {
  1746. $instance_parts = explode(':', $instance);
  1747. $instance_part = array_pop($instance_parts);
  1748. if ($context = metatag_config_instance_info($instance)) {
  1749. $labels[$instance] = $context['label'];
  1750. }
  1751. else {
  1752. $labels[$instance] = t('Unknown (@instance)', array('@instance' => $instance_part));
  1753. }
  1754. // Normally the following would use metatag_config_get_parent_instances()
  1755. // but since we already sliced the instance by separator and removed the
  1756. // last segment, putting the array back together gives us this instance's
  1757. // parent.
  1758. if (!empty($instance_parts)) {
  1759. $labels[$instance] = metatag_config_instance_label(implode(':', $instance_parts)) . ': ' . $labels[$instance];
  1760. }
  1761. }
  1762. return $labels[$instance];
  1763. }
  1764. /**
  1765. * Title callback for meta tag configuration instances.
  1766. */
  1767. function metatag_config_title($config) {
  1768. return metatag_config_instance_label($config->instance);
  1769. }
  1770. /**
  1771. * Access callback for meta tag configuration instances.
  1772. */
  1773. function metatag_config_access($op, $config = NULL) {
  1774. if (!user_access('administer meta tags')) {
  1775. return FALSE;
  1776. }
  1777. if ($op == 'enable') {
  1778. return !empty($config->disabled);
  1779. }
  1780. elseif ($op == 'disable') {
  1781. return empty($config->disabled);
  1782. }
  1783. elseif ($op == 'delete') {
  1784. return ($config->export_type & EXPORT_IN_DATABASE) && !($config->export_type & EXPORT_IN_CODE);
  1785. }
  1786. elseif ($op == 'revert') {
  1787. return ($config->export_type & EXPORT_IN_DATABASE) && ($config->export_type & EXPORT_IN_CODE);
  1788. }
  1789. return FALSE;
  1790. }
  1791. /**
  1792. * Checks if a metatag configuration record is enabled.
  1793. *
  1794. * @param string $instance
  1795. * The configuration instance machine name.
  1796. *
  1797. * @return bool
  1798. * TRUE if the configuration is enabled, or FALSE otherwise.
  1799. */
  1800. function metatag_config_is_enabled($instance, $include_defaults = FALSE, $include_global = TRUE) {
  1801. if ($include_defaults) {
  1802. return (bool) metatag_config_load_with_defaults($instance, $include_global);
  1803. }
  1804. else {
  1805. $config = metatag_config_load($instance);
  1806. return !empty($config) && empty($config->disabled);
  1807. }
  1808. }
  1809. /**
  1810. * Wrapper around entity_language() to use LANGUAGE_NONE if the entity does not
  1811. * have a language assigned.
  1812. *
  1813. * @param $entity_type
  1814. * An entity type's machine name.
  1815. * @param $entity
  1816. * The entity to review;
  1817. *
  1818. * @return
  1819. * A string indicating the language code to be used.
  1820. */
  1821. function metatag_entity_get_language($entity_type, $entity) {
  1822. // Determine the entity's language.
  1823. $langcode = entity_language($entity_type, $entity);
  1824. // If no matching language was found, which will happen for e.g. terms and
  1825. // users, it is normally recommended to use the system default language.
  1826. // However, as the system default language can change, this could potentially
  1827. // cause data loss / confusion problems; as a result use the system "no
  1828. // language" value to avoid any potential problems.
  1829. if (empty($langcode)) {
  1830. $langcode = LANGUAGE_NONE;
  1831. }
  1832. return $langcode;
  1833. }
  1834. /**
  1835. * Implements hook_features_api().
  1836. */
  1837. function metatag_features_api() {
  1838. $components = array(
  1839. 'metatag' => array(
  1840. 'name' => t('Metatag'),
  1841. 'feature_source' => TRUE,
  1842. 'default_hook' => 'metatag_export_default',
  1843. 'default_file' => FEATURES_DEFAULTS_INCLUDED,
  1844. 'file' => drupal_get_path('module', 'metatag') . '/metatag.features.inc',
  1845. ),
  1846. );
  1847. return $components;
  1848. }
  1849. /**
  1850. * Implements hook_views_post_render().
  1851. */
  1852. function metatag_views_post_render(&$view, &$output, &$cache) {
  1853. // Build a shortcut to the current display object.
  1854. $display = $view->display[$view->current_display];
  1855. // Only proceed if this view is a full page, don't process block or other
  1856. // Views display objects.
  1857. if ($display->display_plugin == 'page' && isset($display->display_options['path'])) {
  1858. // Check if this is an entity display page, if so trigger
  1859. // hook_entity_view().
  1860. foreach (entity_get_info() as $entity_type => $entity_info) {
  1861. // Entity paths will include an auto-loader that matches the entity's
  1862. // name, thus the path will be 'some/path/%entity_name'.
  1863. if (isset($entity_info['path']) && ($display->display_options['path'] . $entity_type) == $entity_info['path']) {
  1864. // Only proceed if this entity type supports meta tags.
  1865. if (metatag_entity_supports_metatags($entity_type)) {
  1866. // There must be at least one argument and the first argument must be
  1867. // numerical.
  1868. if (!empty($view->args) && is_numeric($view->args[0])) {
  1869. // Only the first argument is used.
  1870. $entities = entity_load($entity_type, array($view->args[0]));
  1871. // Only if the entity actually exists.
  1872. if (!empty($entities)) {
  1873. $entity = array_pop($entities);
  1874. metatag_entity_view($entity, $entity_type, 'full', NULL, TRUE);
  1875. }
  1876. }
  1877. }
  1878. }
  1879. }
  1880. }
  1881. }
  1882. /**
  1883. * Implements hook_ctools_render_alter().
  1884. *
  1885. * Temporary solution to load meta tags on entity pages that are driven by
  1886. * CTools display handlers.
  1887. */
  1888. function metatag_ctools_render_alter(&$info, $page, $context) {
  1889. // Only proceed if this is a full page (don't process individual panes) and
  1890. // there's an 'admin path' for the current task.
  1891. if ($page && !empty($context['task']['admin path'])) {
  1892. // Check if this is an entity display page, if so trigger
  1893. // hook_entity_view().
  1894. foreach (entity_get_info() as $entity_type => $entity_info) {
  1895. // Entity paths will include an auto-loader that matches the entity's
  1896. // name, thus the path will be 'some/path/%entity_name'.
  1897. if (isset($entity_info['path']) && $context['task']['admin path'] == $entity_info['path']) {
  1898. // Only proceed if this entity type supports meta tags.
  1899. if (metatag_entity_supports_metatags($entity_type)) {
  1900. // There must be at least one argument and the first argument must be
  1901. // numerical.
  1902. if (!empty($context['args']) && is_numeric($context['args'][0])) {
  1903. // We need to pop entity from contexts array.
  1904. $first_context = array_pop($context['contexts']);
  1905. // Only if the context actually exists, which would be an entity.
  1906. if (!empty($first_context->data)) {
  1907. $langcode = $GLOBALS['language_content']->language;
  1908. metatag_entity_view($first_context->data, $entity_type, 'full', $langcode, TRUE);
  1909. }
  1910. }
  1911. }
  1912. }
  1913. }
  1914. }
  1915. }
  1916. /**
  1917. * Implements hook_entity_translation_delete().
  1918. *
  1919. * Required for content translations being handled via Entity_Translation to
  1920. * remove the appropriate record when a translation is removed without the
  1921. * corresponding entity record also being removed.
  1922. */
  1923. function metatag_entity_translation_delete($entity_type, $entity, $langcode) {
  1924. // Get the entity's ID.
  1925. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  1926. $revision_id = intval($revision_id);
  1927. // Delete the translation.
  1928. metatag_metatags_delete($entity_type, $entity_id, $revision_id, $langcode);
  1929. }
  1930. /**
  1931. * Translates the metatag if i18n_string is enabled.
  1932. * @param $name
  1933. * Array or string concatenated with ':' that contains textgroup and string context
  1934. * @param string $string
  1935. * String in default language or array of strings to be translated
  1936. * @param $options
  1937. * An associative array of additional options. @see i18n_string_translate()
  1938. */
  1939. function metatag_translate($name, $string, $langcode = NULL, $update = FALSE) {
  1940. if (function_exists('i18n_string_translate')) {
  1941. $options = array(
  1942. 'langcode' => $langcode,
  1943. 'update' => $update,
  1944. );
  1945. return i18n_string_translate($name, $string, $options);
  1946. }
  1947. else {
  1948. return $string;
  1949. }
  1950. }
  1951. /**
  1952. * Checks if this entity is the default revision (published).
  1953. *
  1954. * @param object $entity
  1955. * The entity object, e.g., $node.
  1956. *
  1957. * @return bool
  1958. * TRUE if the entity is the default revision, FALSE otherwise.
  1959. */
  1960. function _metatag_isdefaultrevision($entity) {
  1961. // D7 "Forward revisioning" is complex and causes a node_save() with the
  1962. // future node in node table. This fires hook_node_update() twice and cause
  1963. // abnormal behaviour in metatag.
  1964. //
  1965. // The steps taken by Workbench Moderation is to save the forward revision
  1966. // first and overwrite this with the live version in a shutdown function in
  1967. // a second step. This will confuse metatag. D7 has no generic property
  1968. // in the node object, if the node that is updated is the 'published' version
  1969. // or only a draft of a future version.
  1970. //
  1971. // This behaviour will change in D8 where $node->isDefaultRevision has been
  1972. // introduced. See below links for more details.
  1973. // - http://drupal.org/node/1879482
  1974. // - http://drupal.org/node/218755
  1975. // - http://drupal.org/node/1522154
  1976. //
  1977. // Every moderation module saving a forward revision needs to return FALSE.
  1978. // @todo: Refactor this workaround under D8.
  1979. // Support for Workbench Moderation v1 - if this is a node, check if the
  1980. // content type supports moderation.
  1981. if (function_exists('workbench_moderation_node_type_moderated') && workbench_moderation_node_type_moderated($entity->type) === TRUE) {
  1982. return !empty($entity->workbench_moderation['updating_live_revision']);
  1983. }
  1984. return FALSE;
  1985. }
  1986. /**
  1987. * Generate the cache ID to use with metatag_cache_get/metatag_cache_set calls.
  1988. *
  1989. * @param array $cid_parts
  1990. * A list of values to be used.
  1991. *
  1992. * @return string
  1993. * The cache ID string.
  1994. */
  1995. function metatag_cache_default_cid_parts(array $cid_parts = array()) {
  1996. // The initial parts, control the order of the parts.
  1997. $cid_part_defaults = array(
  1998. 'cache_type' => 'output',
  1999. 'instance' => '',
  2000. 'entity_type' => '',
  2001. 'entity_id' => '',
  2002. 'bundle' => '',
  2003. 'langcode' => $GLOBALS['language_content']->language,
  2004. 'revision_id' => '',
  2005. 'view_mode' => '',
  2006. 'status' => 200,
  2007. 'protocol' => $GLOBALS['is_https'] ? 'https' : 'http',
  2008. 'hostname' => $_SERVER['HTTP_HOST'],
  2009. 'base_path' => base_path(),
  2010. );
  2011. $cid_parts = array_merge($cid_part_defaults, $cid_parts);
  2012. // Add the HTTP status code.
  2013. $headers = drupal_get_http_header();
  2014. if (isset($headers['status'])) {
  2015. $cid_parts['status'] = intval($headers['status']);
  2016. }
  2017. // Allow each page in a sequence to have different values.
  2018. if (isset($_GET['page'])) {
  2019. $cid_parts['page'] = $_GET['page'];
  2020. }
  2021. // Allow other modules to customize the data using
  2022. // hook_metatag_page_cache_cid_parts_alter().
  2023. drupal_alter('metatag_page_cache_cid_parts', $cid_parts);
  2024. // Remove empty parts.
  2025. $cid_parts = array_filter($cid_parts);
  2026. // Concatenate the cache ID parts, trim the results to 128 chars.
  2027. return substr(implode(':', $cid_parts), 0, 128);
  2028. }
  2029. /**
  2030. * Wrapper for cache_set.
  2031. *
  2032. * @see cache_set().
  2033. */
  2034. function metatag_cache_set($cid, $data) {
  2035. // Cache the data for later.
  2036. return cache_set($cid, $data, 'cache_metatag');
  2037. }
  2038. /**
  2039. * Wrapper for cache_get.
  2040. *
  2041. * @see cache_get().
  2042. */
  2043. function metatag_cache_get($cid) {
  2044. // Try to load the object.
  2045. return cache_get($cid, 'cache_metatag');
  2046. }
  2047. /**
  2048. * Determines if we are in an error page and return the appropriate instance.
  2049. *
  2050. * @return string
  2051. */
  2052. function metatag_is_error_page() {
  2053. $known_errors = array(
  2054. 'global:403' => '403 Forbidden',
  2055. 'global:404' => '404 Not Found',
  2056. );
  2057. $headers = drupal_get_http_header();
  2058. if (isset($headers['status'])) {
  2059. foreach ($known_errors as $error => $status) {
  2060. if ($status == $headers['status']) {
  2061. return $error;
  2062. }
  2063. }
  2064. }
  2065. return '';
  2066. }