metatag.module 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337
  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. // Wrap this in a try-catch block to work around occasions when the schema
  599. // hasn't been updated yet.
  600. try {
  601. if (metatag_entity_supports_metatags($entity_type)) {
  602. // Get the revision_ids.
  603. $revision_ids = array();
  604. foreach ($entities as $key => $entity) {
  605. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  606. $revision_id = intval($revision_id);
  607. if (!empty($revision_id)) {
  608. $revision_ids[] = $revision_id;
  609. }
  610. }
  611. // Load all meta tags for these entities.
  612. $metatags = metatag_metatags_load_multiple($entity_type, array_keys($entities), $revision_ids);
  613. // Assign the metatag records for the correct revision ID.
  614. foreach ($entities as $entity_id => $entity) {
  615. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  616. $revision_id = intval($revision_id);
  617. $entities[$entity_id]->metatags = isset($metatags[$entity_id][$revision_id]) ? $metatags[$entity_id][$revision_id] : array();
  618. }
  619. }
  620. }
  621. catch (Exception $e) {
  622. 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);
  623. // Don't display the same message twice for Drush.
  624. if (drupal_is_cli()) {
  625. drupal_set_message(t('Run your updates, like drush updb.'));
  626. }
  627. // Only message people who can see it in watchdog and can likely fix it.
  628. elseif (user_access('access site reports')) {
  629. 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');
  630. }
  631. }
  632. }
  633. /**
  634. * Implements hook_entity_insert().
  635. */
  636. function metatag_entity_insert($entity, $entity_type) {
  637. if (isset($entity->metatags)) {
  638. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  639. $revision_id = intval($revision_id);
  640. // Determine the entity's language.
  641. $langcode = entity_language($entity_type, $entity);
  642. // Unfortunately due to how core works, the normal entity_language()
  643. // function returns 'und' instead of the node's language during node
  644. // creation.
  645. if ((empty($langcode) || $langcode == LANGUAGE_NONE) && !empty($entity->language)) {
  646. $langcode = $entity->language;
  647. }
  648. // If no language was still found, use the 'no language' value.
  649. if (empty($langcode)) {
  650. $langcode = LANGUAGE_NONE;
  651. }
  652. // Work-around for initial entity creation where a language was selection
  653. // but where it's different to the form's value.
  654. if (!isset($entity->metatags[$langcode]) && isset($entity->metatags[LANGUAGE_NONE])) {
  655. $entity->metatags[$langcode] = $entity->metatags[LANGUAGE_NONE];
  656. unset($entity->metatags[LANGUAGE_NONE]);
  657. }
  658. // Support for Workbench Moderation v1.
  659. if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
  660. return;
  661. }
  662. metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $langcode);
  663. }
  664. }
  665. /**
  666. * Implements hook_entity_update().
  667. */
  668. function metatag_entity_update($entity, $entity_type) {
  669. if (!metatag_entity_supports_metatags($entity_type)) {
  670. return;
  671. }
  672. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  673. $revision_id = intval($revision_id);
  674. if (isset($entity->metatags)) {
  675. // Determine the entity's new language. This will always be accurate as the
  676. // language value will already have been updated by the time this function
  677. // executes, and it will be loaded for the correct edit process.
  678. $new_language = metatag_entity_get_language($entity_type, $entity);
  679. // If applicable, determine the entity's original language. This cannot be
  680. // obtained via the normal API as that data will already have been updated,
  681. // instead check to see if the entity has an old-fasioned 'language' value.
  682. if (isset($entity->original) && isset($entity->language) && isset($entity->original->language)) {
  683. $old_language = $entity->original->language;
  684. // If the language has changed then additional checking needs to be done.
  685. // Need to compare against the entity's raw language value as they will
  686. // be different when updating a translated entity, versus an untranslated
  687. // entity or a source entity for translation, and give a false positive.
  688. if ($new_language == $entity->language && $new_language != $old_language) {
  689. // If this entity is not translated, or if it is translated but the
  690. // translation was previously created, then some language cleanup needs
  691. // to be done.
  692. if (!isset($entity->translation) || (isset($entity->translation) && !empty($entity->translation['created']))) {
  693. // Delete the old language record. This will not affect old revisions.
  694. db_delete('metatag')
  695. ->condition('entity_type', $entity_type)
  696. ->condition('entity_id', $entity_id)
  697. ->condition('revision_id', $revision_id)
  698. ->condition('language', $old_language)
  699. ->execute();
  700. // Swap out the metatag values for the two languages.
  701. if (isset($entity->metatags[$old_language])) {
  702. $entity->metatags[$new_language] = $entity->metatags[$old_language];
  703. unset($entity->metatags[$old_language]);
  704. }
  705. }
  706. }
  707. }
  708. // Support for Workbench Moderation v1.
  709. if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
  710. return;
  711. }
  712. // Save the record.
  713. $old_vid = isset($entity->old_vid) ? $entity->old_vid : NULL;
  714. metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $new_language, $old_vid);
  715. }
  716. else {
  717. // Still ensure the meta tag output is cached.
  718. metatag_metatags_cache_clear($entity_type, $entity_id);
  719. }
  720. }
  721. /**
  722. * Implements hook_entity_delete().
  723. */
  724. function metatag_entity_delete($entity, $entity_type) {
  725. list($entity_id) = entity_extract_ids($entity_type, $entity);
  726. metatag_metatags_delete($entity_type, $entity_id);
  727. }
  728. /**
  729. * Implements hook_field_attach_delete_revision().
  730. */
  731. function metatag_field_attach_delete_revision($entity_type, $entity) {
  732. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  733. $revision_id = intval($revision_id);
  734. metatag_metatags_delete($entity_type, $entity_id, $revision_id);
  735. }
  736. /**
  737. * Implements hook_entity_view().
  738. *
  739. * Provides additional argument to allow the display to be forced, to work
  740. * around problems elsewhere in the APIs.
  741. */
  742. function metatag_entity_view($entity, $entity_type, $view_mode, $langcode, $force = FALSE) {
  743. // Only run this function once per page load.
  744. static $i_will_say_this_only_once = FALSE;
  745. // Only proceed if this entity object is the page being viewed.
  746. if (_metatag_entity_is_page($entity_type, $entity)) {
  747. // Some API calls need to force the data loading.
  748. if (!$force) {
  749. // Only run this function once per page load.
  750. if ($i_will_say_this_only_once) {
  751. return;
  752. }
  753. $i_will_say_this_only_once = TRUE;
  754. }
  755. // CTools uses 'page_manager' view mode to indicate the full entity display
  756. // page rather than 'full', so streamline the internal processes.
  757. if ($view_mode == 'page_manager') {
  758. $view_mode = 'full';
  759. }
  760. // Generate metatags output.
  761. if ($output = metatag_generate_entity_metatags($entity, $entity_type, $langcode, $view_mode)) {
  762. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  763. $instance = "{$entity_type}:{$bundle}";
  764. // We need to register the term's metatags, so we can later fetch them.
  765. // @see metatag_page_build().
  766. metatag_page_set_metatags($instance, $output);
  767. }
  768. }
  769. }
  770. /**
  771. * Generate the metatags for a given entity.
  772. *
  773. * @param object $entity
  774. * The entity object to generate the metatags for.
  775. * @param string $entity_type
  776. * The entity type of the entity.
  777. * @param string $langcode
  778. * The language code used for rendering the entity.
  779. * @param string $view_mode
  780. * The view mode the entity is rendered in.
  781. * @param bool $cached
  782. * TRUE if metatags can be loaded from and saved to the cache. FALSE if the
  783. * cache should be bypassed.
  784. *
  785. * @return array
  786. * A renderable array of metatags for the given entity.
  787. */
  788. function metatag_generate_entity_metatags($entity, $entity_type, $langcode = NULL, $view_mode = 'full', $cached = TRUE) {
  789. // If this entity object isn't allowed meta tags, don't continue.
  790. if (!metatag_entity_has_metatags($entity_type, $entity)) {
  791. return array();
  792. }
  793. // Obtain some details of the entity that are needed elsewhere.
  794. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  795. $revision_id = intval($revision_id);
  796. // Check if a specific metatag config exists, otherwise just use the global
  797. // one, stripping out the bundle.
  798. $instance = "{$entity_type}:{$bundle}";
  799. if (!metatag_config_load_with_defaults($instance, FALSE)) {
  800. $instance = "{$entity_type}";
  801. }
  802. // Determine the language this entity actually uses.
  803. $entity_language = metatag_entity_get_language($entity_type, $entity);
  804. // If no language was requested, try the language defined for this page
  805. // request.
  806. if (empty($langcode)) {
  807. $langcode = $GLOBALS['language_content']->language;
  808. }
  809. // This entity doesn't have any languages defined, i.e. it uses 'und'. This
  810. // can't conflict with loading the wrong language as entities either have no
  811. // language or they have specific one(s), they can't have both.
  812. if ($entity_language == LANGUAGE_NONE) {
  813. $langcode = LANGUAGE_NONE;
  814. }
  815. // If there are no meta tags for the currently identified language, and there
  816. // *are* meta tags defined for the entity's default language, use the entity's
  817. // default language's values, unless the "Don't load entity's default
  818. // language values if no languages match" option is enabled on the advanced
  819. // settings page.
  820. elseif (empty($entity->metatags[$langcode]) && !empty($entity->metatags[$entity_language]) && !variable_get('metatag_entity_no_lang_default', FALSE)) {
  821. $langcode = $entity_language;
  822. }
  823. // Other scenarios.
  824. else {
  825. // There's no need to do anything else - either there are meta tag values
  826. // created for the requested language or there aren't.
  827. }
  828. $cid = FALSE;
  829. if ($cached) {
  830. // All applicable pieces for this current page.
  831. $cid_parts = array(
  832. 'entity_type' => $entity_type,
  833. 'bundle' => $bundle,
  834. 'entity_id' => $entity_id,
  835. 'revision_id' => $revision_id,
  836. // Cache separately based on the language of the passed-in entity and the
  837. // overall active language of the page.
  838. 'langcode' => $langcode,
  839. 'language_content' => $GLOBALS['language_content']->language,
  840. 'view_mode' => $view_mode,
  841. );
  842. $cid = metatag_cache_default_cid_parts($cid_parts);
  843. }
  844. if ($cid && $cache = metatag_cache_get($cid)) {
  845. $output = $cache->data;
  846. }
  847. else {
  848. // Separate the meta tags.
  849. $metatags = isset($entity->metatags) ? $entity->metatags : array();
  850. // Build options for meta tag rendering.
  851. $options = array(
  852. 'entity' => $entity,
  853. 'entity_type' => $entity_type,
  854. 'view_mode' => $view_mode,
  855. );
  856. // Ensure we actually pass a language object rather than language code.
  857. $languages = language_list();
  858. if (isset($languages[$langcode])) {
  859. $options['language'] = $languages[$langcode];
  860. }
  861. // Reload the entity object from cache as it may have been altered.
  862. if (!empty($entity_id)) {
  863. $token_type = token_get_entity_mapping('entity', $entity_type);
  864. $entities = entity_load($entity_type, array($entity_id));
  865. $options['token data'][$token_type] = $entities[$entity_id];
  866. $options['entity'] = $entities[$entity_id];
  867. }
  868. // Render the metatags and save to the cache.
  869. $output = metatag_metatags_view($instance, $metatags, $options);
  870. if ($cid) {
  871. metatag_cache_set($cid, $output);
  872. }
  873. }
  874. return $output;
  875. }
  876. /**
  877. * Generate the metatags for a given entity.
  878. *
  879. * @param object $entity_id
  880. * The entity id of the entity to generate the metatags for.
  881. * @param string $entity_type
  882. * The entity type of the entity to generate the metatags for.
  883. * @param string $langcode
  884. * The language code used for rendering the entity.
  885. *
  886. * @return array
  887. * A renderable array of metatags for the given entity.
  888. */
  889. function metatags_get_entity_metatags($entity_id, $entity_type, $langcode = NULL) {
  890. $entities = entity_load($entity_type, array($entity_id));
  891. $entity = reset($entities);
  892. return !empty($entity) ? metatag_generate_entity_metatags($entity, $entity_type, $langcode) : array();
  893. }
  894. /**
  895. * Build a renderable array of meta tag output.
  896. *
  897. * @param string $instance
  898. * The configuration instance key of the meta tags to use, e.g.
  899. * "node:article".
  900. * @param array $metatags
  901. * An array of meta tag data.
  902. * @param array $options
  903. * (optional) An array of options including the following keys and values:
  904. * - language: A language object.
  905. * - token data: An array of data to pass into token_replace() during
  906. * meta tag value generation.
  907. */
  908. function metatag_metatags_view($instance, array $metatags = array(), array $options = array()) {
  909. $output = array();
  910. // Convert language codes to a language object.
  911. if (isset($options['language']) && is_string($options['language'])) {
  912. $languages = language_list();
  913. $options['language'] = isset($languages[$options['language']]) ? $languages[$options['language']] : NULL;
  914. }
  915. // If there are any tags, determine the translation to display.
  916. if (!empty($metatags)) {
  917. // Get the display language; default to the entity's language.
  918. if (isset($options['language']) && isset($options['language']->language) && isset($metatags[$options['language']->language])) {
  919. $metatags = $metatags[$options['language']->language];
  920. }
  921. // If no language requested, use the no-language value.
  922. elseif (!empty($metatags[LANGUAGE_NONE])) {
  923. $metatags = $metatags[LANGUAGE_NONE];
  924. }
  925. else {
  926. $metatags = array();
  927. }
  928. }
  929. // Add any default tags to the mix.
  930. $metatags += metatag_config_load_with_defaults($instance);
  931. $options['instance'] = $instance;
  932. foreach ($metatags as $metatag => $data) {
  933. if ((!empty($data['value']) || (isset($data['value']) && is_numeric($data['value'])))
  934. && $metatag_instance = metatag_get_instance($metatag, $data)) {
  935. $output[$metatag] = $metatag_instance->getElement($options);
  936. }
  937. }
  938. // Allow the output meta tags to be modified using
  939. // hook_metatag_metatags_view_alter().
  940. drupal_alter('metatag_metatags_view', $output, $instance, $options);
  941. return $output;
  942. }
  943. function metatag_metatags_values($instance, array $metatags = array(), array $options = array()) {
  944. $values = array();
  945. // Apply defaults to the data for each language.
  946. foreach ($metatags as $language => $metatag) {
  947. $metatags[$language] += metatag_config_load_with_defaults($instance);
  948. }
  949. // Generate output only if we have a valid language.
  950. if (isset($options['language']) && is_string($options['language']) && isset($metatags[$options['language']])) {
  951. $language = $options['language'];
  952. // Convert language codes to a language object.
  953. $languages = language_list();
  954. $options['language'] = isset($languages[$language]) ? $languages[$language] : NULL;
  955. $options['instance'] = $instance;
  956. // Get output elements.
  957. foreach ($metatags[$language] as $metatag => $data) {
  958. if ($metatag_instance = metatag_get_instance($metatag, $data)) {
  959. $values[$metatag] = $metatag_instance->getValue($options);
  960. }
  961. }
  962. }
  963. return array_filter($values, 'drupal_strlen');
  964. }
  965. /**
  966. * Build a FAPI array for editing meta tags.
  967. *
  968. * @param array $form
  969. * The current FAPI array.
  970. * @param string $instance
  971. * The configuration instance key of the metatags to use, e.g. "node:article".
  972. * @param array $metatags
  973. * An array of metatag data.
  974. * @param array $options
  975. * (optional) An array of options including the following keys and values:
  976. * - token types: An array of token types to be passed to theme_token_tree().
  977. */
  978. function metatag_metatags_form(array &$form, $instance, array $metatags = array(), array $options = array()) {
  979. $info = metatag_get_info();
  980. if (empty($info['tags'])) {
  981. return;
  982. }
  983. // Work out the language code to use, default to NONE.
  984. $langcode = LANGUAGE_NONE;
  985. if (!empty($form['#entity_type'])) {
  986. if (!empty($form['#entity'])) {
  987. $langcode = metatag_entity_get_language($form['#entity_type'], $form['#entity']);
  988. }
  989. else {
  990. $entity_info = entity_get_info($form['#entity_type']);
  991. if (!empty($entity_info['token type'])) {
  992. $entity_key = '#' . $entity_info['token type'];
  993. if (!empty($form[$entity_key])) {
  994. $langcode = metatag_entity_get_language($form['#entity_type'], $form[$entity_key]);
  995. }
  996. }
  997. }
  998. }
  999. // Merge in the default options.
  1000. $options += array(
  1001. 'token types' => array(),
  1002. 'defaults' => metatag_config_load_with_defaults($instance),
  1003. 'instance' => $instance,
  1004. );
  1005. $form['metatags'] = array(
  1006. '#type' => 'fieldset',
  1007. '#title' => t('Meta tags'),
  1008. '#collapsible' => TRUE,
  1009. '#collapsed' => TRUE,
  1010. '#multilingual' => TRUE,
  1011. '#tree' => TRUE,
  1012. '#access' => user_access('edit meta tags') || user_access('administer meta tags'),
  1013. '#weight' => 40,
  1014. '#language' => $langcode,
  1015. '#attributes' => array(
  1016. 'class' => array('metatags-form'),
  1017. ),
  1018. );
  1019. $form['metatags'][$langcode] = array(
  1020. '#metatag_defaults' => $options['defaults'],
  1021. '#type' => 'container',
  1022. '#multilingual' => TRUE,
  1023. '#tree' => TRUE,
  1024. );
  1025. // Show a different intro message for entity pages vs config pages.
  1026. if (isset($form['#entity'])) {
  1027. $form['metatags'][$langcode]['intro_text'] = array(
  1028. '#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>',
  1029. '#weight' => -10,
  1030. );
  1031. }
  1032. else {
  1033. $form['metatags'][$langcode]['intro_text'] = array(
  1034. '#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>',
  1035. '#weight' => -10,
  1036. );
  1037. }
  1038. // Only support vertical tabs if there is a vertical tab element.
  1039. foreach (element_children($form) as $key) {
  1040. if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'vertical_tabs') {
  1041. $form['metatags']['#group'] = $key;
  1042. $form['metatags']['#attached']['js']['vertical-tabs'] = drupal_get_path('module', 'metatag') . '/metatag.vertical-tabs.js';
  1043. break;
  1044. }
  1045. }
  1046. // Merge in the default meta tag configurations.
  1047. $metatags += $options['defaults'];
  1048. // This will be used later.
  1049. $group_metatag_access = array();
  1050. // Build the form for each metatag.
  1051. foreach ($info['tags'] as $metatag => $metatag_info) {
  1052. // @todo Replace context matching with hook_metatag_access().
  1053. if (isset($options['context']) && isset($metatag_info['context'])) {
  1054. if (!in_array($options['context'], $metatag_info['context'])) {
  1055. continue;
  1056. }
  1057. }
  1058. $metatag_instance = metatag_get_instance($metatag, isset($metatags[$metatag]) ? $metatags[$metatag] : array());
  1059. if (empty($metatag_instance)) {
  1060. continue;
  1061. }
  1062. // Get the form element from the meta tag class.
  1063. $metatag_form = $metatag_instance->getForm($options);
  1064. // Add a default value form element.
  1065. if (isset($options['defaults'][$metatag]['value'])) {
  1066. $metatag_form['default'] = array(
  1067. '#type' => 'hidden',
  1068. '#value' => $options['defaults'][$metatag]['value'],
  1069. );
  1070. }
  1071. // Optional extended edit permissions.
  1072. if (variable_get('metatag_extended_permissions', FALSE)) {
  1073. $metatag_form['#access'] = user_access('edit meta tag: ' . $metatag) || user_access('administer meta tags');
  1074. }
  1075. else {
  1076. $metatag_form['#access'] = $form['metatags']['#access'];
  1077. }
  1078. if (!empty($metatag_info['group'])) {
  1079. $group_key = $metatag_info['group'];
  1080. if (isset($info['groups'][$group_key]['label']) && !isset($form['metatags'][$langcode][$group_key])) {
  1081. $group = $info['groups'][$group_key] + array('form' => array(), 'description' => NULL);
  1082. $form['metatags'][$langcode][$group_key] = $group['form'] + array(
  1083. '#type' => 'fieldset',
  1084. '#title' => check_plain($group['label']),
  1085. '#description' => filter_xss($group['description']),
  1086. '#collapsible' => TRUE,
  1087. '#collapsed' => TRUE,
  1088. );
  1089. }
  1090. $form['metatags'][$langcode][$group_key][$metatag] = $metatag_form + array('#parents' => array('metatags', $langcode, $metatag));
  1091. // Hide the fieldset itself if there is not at least one of the meta tag
  1092. // fields visible.
  1093. if (variable_get('metatag_extended_permissions', FALSE)) {
  1094. $form['metatags'][$langcode][$group_key]['#access'] = count(element_get_visible_children($form['metatags'][$langcode][$group_key])) > 0;
  1095. }
  1096. else {
  1097. $form['metatags'][$langcode][$group_key]['#access'] = $form['metatags']['#access'];
  1098. }
  1099. // Structure the access parameter into this array, and make use of it
  1100. // later when we move on. Besides, this foreach is getting heavy.
  1101. $group_metatag_access[$group_key] = $form['metatags'][$langcode][$group_key]['#access'];
  1102. }
  1103. else {
  1104. $form['metatags'][$langcode][$metatag] = $metatag_form;
  1105. }
  1106. }
  1107. // Hide the fieldset itself if there is not at least one of the meta tag
  1108. // fields visible; only bother checking this if the user had edit access in
  1109. // the first place.
  1110. if ($form['metatags']['#access'] && variable_get('metatag_extended_permissions', FALSE)) {
  1111. $form['metatags']['#access'] = count(element_get_visible_children($form['metatags'][$langcode])) > 0;
  1112. }
  1113. // Check the #access of each group. If it passed, we display options for
  1114. // tokens. By this we update the #description of each group.
  1115. if ($form['metatags']['#access']) {
  1116. // Built the token list.
  1117. $token_listing_link = theme('token_tree', array('token_types' => $options['token types'], 'dialog' => TRUE));
  1118. // Add the token list to the top of the fieldset.
  1119. $form['metatags'][$langcode]['#description'] = $token_listing_link;
  1120. // Check if each meta tag group is being displayed.
  1121. if (!empty($group_metatag_access)) {
  1122. foreach ($group_metatag_access as $group_key => $token_access) {
  1123. if ($token_access) {
  1124. // Update the description.
  1125. if (isset($form['metatags'][$langcode][$group_key]['#description'])) {
  1126. $form['metatags'][$langcode][$group_key]['#description'] .= '<br />';
  1127. }
  1128. else {
  1129. $form['metatags'][$langcode][$group_key]['#description'] = '';
  1130. }
  1131. $form['metatags'][$langcode][$group_key]['#description'] .= $token_listing_link;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. // Add a submit handler to compare the submitted values against the deafult
  1137. // values.
  1138. $form += array('#submit' => array());
  1139. array_unshift($form['#submit'], 'metatag_metatags_form_submit');
  1140. }
  1141. /**
  1142. * Form API submission callback.
  1143. *
  1144. * Unset meta tag values that equal their default values, and load any
  1145. * additional meta tag values for other languages so that they can be properly
  1146. * saved later on.
  1147. *
  1148. * @see metatag_metatags_save()
  1149. */
  1150. function metatag_metatags_form_submit($form, &$form_state) {
  1151. if (!empty($form_state['values']['metatags'])) {
  1152. // Unset meta tag values that equal their default values.
  1153. foreach ($form_state['values']['metatags'] as $langcode => $values) {
  1154. if (!empty($form['metatags'][$langcode]['#metatag_defaults'])) {
  1155. metatag_filter_values_from_defaults($form_state['values']['metatags'][$langcode], $form['metatags'][$langcode]['#metatag_defaults']);
  1156. }
  1157. }
  1158. // Need to load the entity's values for other languages, otherwise they will
  1159. // be incorrectly deleted later on.
  1160. if (isset($form['#entity']) && !empty($form['#entity']->metatags)) {
  1161. foreach ($form['#entity']->metatags as $langcode => $values) {
  1162. if (!isset($form_state['values']['metatags'][$langcode])) {
  1163. $form_state['values']['metatags'][$langcode] = $values;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. /**
  1170. * Implements hook_field_extra_fields().
  1171. */
  1172. function metatag_field_extra_fields() {
  1173. $extra = array();
  1174. foreach (entity_get_info() as $entity_type => $entity_info) {
  1175. foreach (array_keys($entity_info['bundles']) as $bundle) {
  1176. if (metatag_entity_supports_metatags($entity_type, $bundle)) {
  1177. $extra[$entity_type][$bundle]['form']['metatags'] = array(
  1178. 'label' => t('Meta tags'),
  1179. 'description' => t('Meta tag module form elements.'),
  1180. 'weight' => 40,
  1181. );
  1182. }
  1183. }
  1184. }
  1185. return $extra;
  1186. }
  1187. /**
  1188. * Check if an individual entity has meta tags defined, or has defaults.
  1189. *
  1190. * @param string $entity_type
  1191. * An entity type.
  1192. * @param object $entity
  1193. * An entity object.
  1194. *
  1195. * @return boolean
  1196. * TRUE or FALSE if the entity should have a form for or process meta tags.
  1197. */
  1198. function metatag_entity_has_metatags($entity_type, $entity) {
  1199. // If an entity has custom meta tags assigned, then we should return TRUE.
  1200. if (!empty($entity->metatags)) {
  1201. return TRUE;
  1202. }
  1203. // Otherwise, check to see if there exists any enabed configuration for
  1204. // either the entity type, or bundle (even if the configuration is empty).
  1205. // If no configuration exists, then we should not be displaying the meta tag
  1206. // forms or processing meta tags on entity view.
  1207. $config_exists = &drupal_static(__FUNCTION__, array());
  1208. list( , , $bundle) = entity_extract_ids($entity_type, $entity);
  1209. // Do not pretend to have metatags when the bundle does not support them.
  1210. if (!metatag_entity_supports_metatags($entity_type, $bundle)) {
  1211. return FALSE;
  1212. }
  1213. $instance = "{$entity_type}:{$bundle}";
  1214. if (!isset($config_exists[$instance])) {
  1215. // Check if the intstance or its parents (excluding global) are enabled.
  1216. $config_exists[$instance] = metatag_config_is_enabled($instance, TRUE, FALSE);
  1217. }
  1218. return !empty($config_exists[$instance]);
  1219. }
  1220. /**
  1221. * Check whether the requested entity type (and bundle) support metatag.
  1222. *
  1223. * By default this will be FALSE, support has to be specifically enabled by
  1224. * assigning 'metatag' => TRUE within the hook_entity_info() definition for the
  1225. * entity.
  1226. */
  1227. function metatag_entity_supports_metatags($entity_type = NULL, $bundle = NULL) {
  1228. $entity_types = &drupal_static(__FUNCTION__);
  1229. if (!isset($entity_types)) {
  1230. $entity_types = array();
  1231. }
  1232. // Everything else depends upon a specific entity type being checked.
  1233. if (isset($entity_type)) {
  1234. if (!isset($entity_types[$entity_type])) {
  1235. $entity_info = entity_get_info($entity_type);
  1236. if (empty($entity_info['metatags'])) {
  1237. $entity_types[$entity_type] = FALSE;
  1238. }
  1239. else {
  1240. $entity_types[$entity_type] = array();
  1241. foreach ($entity_info['bundles'] as $bundle_key => $bundle_info) {
  1242. $entity_types[$entity_type][$bundle_key] = !isset($bundle_info['metatags']) || !empty($bundle_info['metatags']);
  1243. }
  1244. }
  1245. }
  1246. // If a specific entity bundle is being compared, check it first.
  1247. if (isset($bundle)) {
  1248. // Allow entities to be disabled by assigning a variable
  1249. // 'metatag_enable_{$entity_type}__{$bundle}' the value FALSE, e.g.:
  1250. //
  1251. // // Disable metatags for carousel nodes.
  1252. // $conf['metatag_enable_node__carousel'] = FALSE;
  1253. //
  1254. // @see Advanced settings page.
  1255. if (variable_get('metatag_enable_' . $entity_type . '__' . $bundle, 'monkey') == FALSE) {
  1256. return FALSE;
  1257. }
  1258. return isset($entity_types[$entity_type][$bundle]) ? $entity_types[$entity_type][$bundle] : FALSE;
  1259. }
  1260. // Otherwise check the entity type itself.
  1261. else {
  1262. // Allow entities to be disabled by assigning a variable
  1263. // 'metatag_enable_{$entity_type}' the value FALSE, e.g.:
  1264. //
  1265. // // Disable metatags for file_entity.
  1266. // $conf['metatag_enable_file'] = FALSE;
  1267. //
  1268. // @see Advanced settings page.
  1269. if (variable_get('metatag_enable_' . $entity_type, 'monkey') == FALSE) {
  1270. return FALSE;
  1271. }
  1272. return isset($entity_types[$entity_type]) ? ($entity_types[$entity_type] !== FALSE) : FALSE;
  1273. }
  1274. }
  1275. return $entity_types;
  1276. }
  1277. /**
  1278. * Implements hook_entity_info_alter().
  1279. *
  1280. * Enables Metatag support for the core entities.
  1281. */
  1282. function metatag_entity_info_alter(&$info) {
  1283. $defaults['node'] = array(
  1284. 'path' => 'node/%node',
  1285. 'metatags' => TRUE,
  1286. );
  1287. $defaults['user'] = array(
  1288. 'path' => 'user/%user',
  1289. 'metatags' => TRUE,
  1290. );
  1291. $defaults['taxonomy_term'] = array(
  1292. 'path' => 'taxonomy/term/%taxonomy_term',
  1293. 'metatags' => TRUE,
  1294. );
  1295. // Just running taxonomy_vocabulary_load() here would cause problems for
  1296. // EntityCache in certain circumstances, so instead the query is executed
  1297. // directly instead.
  1298. if (module_exists('forum') && ($vocab_id = variable_get('forum_nav_vocabulary', 0))) {
  1299. $vocab_name = db_query("SELECT machine_name FROM {taxonomy_vocabulary} WHERE vid = :vid", array(':vid' => $vocab_id))->fetchField();
  1300. if (!empty($vocab_name)) {
  1301. $defaults['taxonomy_term']['bundles'][$vocab_name]['path'] = 'forum/%taxonomy_term';
  1302. }
  1303. }
  1304. foreach ($defaults as $key => $entity_defaults) {
  1305. if (isset($info[$key])) {
  1306. $info[$key] = drupal_array_merge_deep($entity_defaults, $info[$key]);
  1307. }
  1308. }
  1309. }
  1310. /**
  1311. * Given a path determine if it is an entity default path.
  1312. *
  1313. * @param $path
  1314. * The internal path. The id of the entity should be in the string as '[id]'.
  1315. * @return
  1316. * An array with the entity type and the loaded entity object.
  1317. */
  1318. function metatag_load_entity_from_path($path) {
  1319. $entity_paths = &drupal_static(__FUNCTION__);
  1320. $result = FALSE;
  1321. if (!isset($entity_paths)) {
  1322. $entity_paths = array();
  1323. foreach (entity_get_info() as $entity_type => $entity_info) {
  1324. if (isset($entity_info['default path'])) {
  1325. $default_path = $entity_info['default path'];
  1326. $default_path = preg_quote($default_path, '/');
  1327. $default_path = str_replace('\[id\]', '(\d+)', $default_path);
  1328. $entity_paths[$entity_type] = $default_path;
  1329. }
  1330. }
  1331. }
  1332. foreach ($entity_paths as $entity_type => $default_path) {
  1333. if (preg_match("/^{$default_path}$/", $path, $matches)) {
  1334. if ($entity = entity_load($entity_type, array($matches[1]))) {
  1335. $result = array('entity_type' => $entity_type, 'entity' => reset($entity));
  1336. }
  1337. break;
  1338. }
  1339. }
  1340. // Allow other modules to customize the data using
  1341. // hook_metatag_load_entity_from_path_alter().
  1342. drupal_alter('metatag_load_entity_from_path', $path, $result);
  1343. return $result;
  1344. }
  1345. /**
  1346. * Add meta tags to be added later with metatag_page_build().
  1347. *
  1348. * @param string $instance
  1349. * The configuration instance key of the meta tags, e.g. "node:article".
  1350. * @param array $metatags
  1351. * An array of meta tags from metatag_metatags_view().
  1352. */
  1353. function metatag_page_set_metatags($instance, $metatags) {
  1354. $page_metatags = &drupal_static(__FUNCTION__, array());
  1355. $page_metatags[$instance] = $metatags;
  1356. }
  1357. /**
  1358. * Retrieve the array of meta tags to be added with metatag_page_build().
  1359. */
  1360. function metatag_page_get_metatags() {
  1361. // @todo Add alter to this result?
  1362. return drupal_static('metatag_page_set_metatags', array());
  1363. }
  1364. /**
  1365. * Implements hook_page_build().
  1366. */
  1367. function metatag_page_build(&$page) {
  1368. // By default do not add meta tags to admin pages. To enable meta tags on
  1369. // admin pages set the 'metatag_tag_admin_pages' variable to TRUE.
  1370. if (path_is_admin(current_path()) && !variable_get('metatag_tag_admin_pages', FALSE)) {
  1371. return;
  1372. }
  1373. // The page region can be changed.
  1374. $region = variable_get('metatag_page_region', 'content');
  1375. // Ensure these arrays exist, otherwise several use cases will fail.
  1376. if (!isset($page[$region]) || !is_array($page[$region])) {
  1377. $page[$region] = array();
  1378. }
  1379. if (!isset($page[$region]['metatags']) || !is_array($page[$region]['metatags'])) {
  1380. $page[$region]['metatags'] = array();
  1381. }
  1382. // The front page has special consideration. Also, check if this is an error
  1383. // (403/404) page, those also require separate handling.
  1384. $instance = 'global:frontpage';
  1385. if ((drupal_is_front_page() && metatag_config_is_enabled($instance))
  1386. || ($instance = metatag_is_error_page())) {
  1387. // Generate the cache ID.
  1388. $cid_parts = array(
  1389. 'instance' => $instance,
  1390. );
  1391. $cid = metatag_cache_default_cid_parts($cid_parts);
  1392. if ($cache = metatag_cache_get($cid)) {
  1393. $metatags = $cache->data;
  1394. }
  1395. else {
  1396. $metatags = metatag_metatags_view($instance, array());
  1397. metatag_cache_set($cid, $metatags);
  1398. }
  1399. $page[$region]['metatags'][$instance] = $metatags;
  1400. }
  1401. // Load any meta tags assigned via metatag_page_set_metatags(). Note: this
  1402. // must include the necessary defaults.
  1403. else {
  1404. $page[$region]['metatags'] += metatag_page_get_metatags();
  1405. }
  1406. // If no meta tags were loaded at least load the global defaults. This may be
  1407. // disabled, see README.txt for details.
  1408. if (empty($page[$region]['metatags']) && variable_get('metatag_load_all_pages', TRUE)) {
  1409. $instance = 'global';
  1410. // Generate the cache ID.
  1411. $cid_parts = array(
  1412. 'instance' => $instance,
  1413. 'path' => request_path(),
  1414. );
  1415. $cid = metatag_cache_default_cid_parts($cid_parts);
  1416. if ($cache = metatag_cache_get($cid)) {
  1417. $metatags = $cache->data;
  1418. }
  1419. else {
  1420. $metatags = metatag_metatags_view($instance, array());
  1421. metatag_cache_set($cid, $metatags);
  1422. }
  1423. $page[$region]['metatags'][$instance] = $metatags;
  1424. }
  1425. }
  1426. /**
  1427. * Returns whether the current page is the page of the passed in entity.
  1428. *
  1429. * @param $entity_type
  1430. * The entity type; e.g. 'node' or 'user'.
  1431. * @param $entity
  1432. * The entity object.
  1433. *
  1434. * @return
  1435. * TRUE if the current page is the page of the specified entity, or FALSE
  1436. * otherwise.
  1437. */
  1438. function _metatag_entity_is_page($entity_type, $entity) {
  1439. // Exclude comment entities as this conflicts with comment_fragment.module.
  1440. if ($entity_type == 'comment') {
  1441. return;
  1442. }
  1443. $uri = entity_uri($entity_type, $entity);
  1444. $current_path = current_path();
  1445. // Support for Workbench Moderation v1 - if this is a node, check if the
  1446. // content type supports moderation.
  1447. if ($entity_type == 'node' && function_exists('workbench_moderation_node_type_moderated') && workbench_moderation_node_type_moderated($entity->type) === TRUE) {
  1448. return !empty($uri['path']) && ($current_path == $uri['path'] || $current_path == $uri['path'] . '/draft');
  1449. }
  1450. // Support for core node revisions.
  1451. elseif (!empty($uri['path']) && strpos($current_path, $uri['path']) === 0 && strpos($current_path, '/revisions/') && strpos($current_path, '/view')) {
  1452. return TRUE;
  1453. }
  1454. // Any other page.
  1455. else {
  1456. return !empty($uri['path']) && $current_path == $uri['path'];
  1457. }
  1458. }
  1459. /**
  1460. * Implements hook_field_attach_rename_bundle().
  1461. */
  1462. function metatag_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  1463. $instance_old = $entity_type . ':' . $bundle_old;
  1464. $instance_new = $entity_type . ':' . $bundle_new;
  1465. if ($config = metatag_config_load($instance_old)) {
  1466. $config->instance = $instance_new;
  1467. metatag_config_save($config);
  1468. metatag_config_delete($instance_old);
  1469. }
  1470. }
  1471. /**
  1472. * Implements hook_field_attach_delete_bundle().
  1473. */
  1474. function metatag_field_attach_delete_bundle($entity_type, $bundle) {
  1475. $instance = $entity_type . ':' . $bundle;
  1476. metatag_config_delete($instance);
  1477. }
  1478. /**
  1479. * Implements hook_field_attach_form().
  1480. */
  1481. function metatag_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  1482. if (!metatag_entity_has_metatags($entity_type, $entity)) {
  1483. return;
  1484. }
  1485. // Entity_Translation will trigger this hook again, skip it.
  1486. if (!empty($form_state['entity_translation']['is_translation'])) {
  1487. return;
  1488. }
  1489. list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  1490. $instance = "{$entity_type}:{$bundle}";
  1491. // Grab the meta tags for display in the form if there are any.
  1492. if (!empty($entity->metatags)) {
  1493. // Identify the language to use with this entity.
  1494. $entity_language = metatag_entity_get_language($entity_type, $entity);
  1495. // If this is a new translation using Entity Translation, load the meta
  1496. // tags from the entity's original language.
  1497. 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()])) {
  1498. $metatags = $entity->metatags[$handler->getSourceLanguage()];
  1499. }
  1500. // Determine from where we should get the tags.
  1501. elseif (isset($entity->metatags[$langcode])) {
  1502. // Set the tags to the translation set matching that of the form.
  1503. $metatags = $entity->metatags[$langcode];
  1504. }
  1505. // There is no translation for this entity's tags in the current
  1506. // language. Instead, display tags in the language of the entity, the
  1507. // source language of translations. The will provide translators with the
  1508. // original text to translate.
  1509. elseif (isset($entity->metatags[$entity_language])) {
  1510. $metatags = $entity->metatags[$entity_language];
  1511. }
  1512. // This is a preview so set the tags to the raw submission data. No
  1513. // language has been set.
  1514. else {
  1515. $metatags = $entity->metatags;
  1516. }
  1517. }
  1518. else {
  1519. $metatags = array();
  1520. }
  1521. $options['token types'] = array(token_get_entity_mapping('entity', $entity_type));
  1522. $options['context'] = $entity_type;
  1523. // Allow hook_metatag_token_types_alter() to modify the defined tokens.
  1524. drupal_alter('metatag_token_types', $options);
  1525. // @todo Remove metatag_form_alter() when https://www.drupal.org/node/1284642 is fixed in core.
  1526. //metatag_metatags_form($form, $instance, $metatags, $options);
  1527. $form['#metatags'] = array(
  1528. 'instance' => $instance,
  1529. 'metatags' => $metatags,
  1530. 'options' => $options,
  1531. );
  1532. }
  1533. /**
  1534. * Implements hook_form_alter().
  1535. *
  1536. * @todo Remove this when https://www.drupal.org/node/1284642 is fixed in core.
  1537. */
  1538. function metatag_form_alter(&$form, $form_state, $form_id) {
  1539. if (!empty($form['#metatags']) && !isset($form['metatags'])) {
  1540. extract($form['#metatags']);
  1541. metatag_metatags_form($form, $instance, $metatags, $options);
  1542. unset($form['#metatags']);
  1543. }
  1544. }
  1545. /**
  1546. * Get the meta tag information array of a meta tag.
  1547. *
  1548. * @param $metatag
  1549. * The meta tag name, e.g. description, for which the info shall be returned,
  1550. * or NULL to return an array with info about all meta tags.
  1551. */
  1552. function metatag_get_info($type = NULL, $name = NULL) {
  1553. // Use the advanced drupal_static() pattern, since this is called very often.
  1554. static $drupal_static_fast;
  1555. if (!isset($drupal_static_fast)) {
  1556. $drupal_static_fast['metatag_info'] = &drupal_static(__FUNCTION__);
  1557. }
  1558. $info = &$drupal_static_fast['metatag_info'];
  1559. global $language;
  1560. if (!isset($info)) {
  1561. // hook_metatag_info() includes translated strings, so each language is cached
  1562. // separately.
  1563. $cid = 'info:' . $language->language;
  1564. if ($cache = metatag_cache_get($cid)) {
  1565. $info = $cache->data;
  1566. }
  1567. else {
  1568. // Obtain all metatag specs defined in other modules using
  1569. // hook_metatag_info().
  1570. $info = module_invoke_all('metatag_info');
  1571. $info += array('tags' => array(), 'groups' => array());
  1572. // Merge in default values.
  1573. foreach ($info['tags'] as $key => $data) {
  1574. $info['tags'][$key] += array(
  1575. // Merge in default values.
  1576. 'name' => $key,
  1577. 'class' => 'DrupalTextMetaTag',
  1578. );
  1579. }
  1580. // Let other modules alter the entity info using
  1581. // hook_metatag_info_alter().
  1582. drupal_alter('metatag_info', $info);
  1583. metatag_cache_set($cid, $info);
  1584. }
  1585. }
  1586. if (isset($type) && isset($name)) {
  1587. return isset($info[$type][$name]) ? $info[$type][$name] : FALSE;
  1588. }
  1589. elseif (isset($type)) {
  1590. return isset($info[$type]) ? $info[$type] : array();
  1591. }
  1592. else {
  1593. return $info;
  1594. }
  1595. }
  1596. function metatag_get_instance($metatag, array $data = array()) {
  1597. $info = metatag_get_info('tags', $metatag);
  1598. if (!empty($info['class']) && class_exists($info['class'])) {
  1599. $class = $info['class'];
  1600. return new $class($info, $data);
  1601. }
  1602. }
  1603. /**
  1604. * Return the string value of a meta tag.
  1605. *
  1606. * @param $metatag
  1607. * The meta tag string.
  1608. * @param $data
  1609. * The array of data for the meta tag class instance.
  1610. * @param $options
  1611. * An optional array of additional options to pass to the getValue() method
  1612. * of the meta tag class instance.
  1613. * - raw: A boolean if TRUE will not perform token replacement.
  1614. *
  1615. * @return
  1616. * A string value.
  1617. */
  1618. function metatag_get_value($metatag, array $data, array $options = array()) {
  1619. $value = '';
  1620. if ($metatag_instance = metatag_get_instance($metatag, $data)) {
  1621. $options["instance"] = $metatag;
  1622. $value = $metatag_instance->getValue($options);
  1623. }
  1624. return $value;
  1625. }
  1626. /**
  1627. * Set a variable to be altered in metatag_preprocess_html().
  1628. *
  1629. * @see metatag_get_preprocess_variables()
  1630. * @see metatag_preprocess_html()
  1631. * @see metatag_preprocess_maintenance_page()
  1632. */
  1633. function metatag_set_preprocess_variable($hook, $variable, $value) {
  1634. $variables = &drupal_static(__FUNCTION__, array());
  1635. $variables[$hook][$variable] = $value;
  1636. }
  1637. /**
  1638. * Return an array of variables to be altered in preprocess functions.
  1639. *
  1640. * @see metatag_set_preprocess_variable()
  1641. * @see metatag_preprocess_html()
  1642. * @see metatag_preprocess_maintenance_page()
  1643. */
  1644. function metatag_get_preprocess_variables($hook) {
  1645. $variables = drupal_static('metatag_set_preprocess_variable', array());
  1646. return isset($variables[$hook]) ? $variables[$hook] : array();
  1647. }
  1648. /**
  1649. * Implements hook_preprocess_html().
  1650. */
  1651. function metatag_preprocess_html(&$variables) {
  1652. foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
  1653. $variables[$variable] = $value;
  1654. }
  1655. }
  1656. /**
  1657. * Implements hook_preprocess_maintenance_page().
  1658. */
  1659. function metatag_preprocess_maintenance_page(&$variables) {
  1660. foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
  1661. $variables[$variable] = $value;
  1662. }
  1663. }
  1664. /**
  1665. * Implements hook_html_head_alter().
  1666. */
  1667. function metatag_html_head_alter(&$elements) {
  1668. // Remove duplicate link tags if found.
  1669. $metatags = metatag_get_info('tags');
  1670. foreach (array_keys($metatags) as $name) {
  1671. if (!isset($elements['metatag_' . $name]) || $elements['metatag_' . $name]['#tag'] != 'link') {
  1672. // Only check for link tags added by the metatags module.
  1673. continue;
  1674. }
  1675. foreach (array_keys($elements) as $key) {
  1676. if (strpos($key, 'drupal_add_html_head_link:' . $name . ':') === 0) {
  1677. unset($elements[$key]);
  1678. }
  1679. }
  1680. }
  1681. // Remove the default generator meta tag.
  1682. unset($elements['system_meta_generator']);
  1683. }
  1684. function metatag_metatag_get_form($metatag, array $data = array(), array $options = array()) {
  1685. $instance = metatag_get_instance($metatag, $data);
  1686. return $instance->getForm($options);
  1687. }
  1688. function metatag_config_instance_info($instance = NULL) {
  1689. global $language;
  1690. $info = &drupal_static(__FUNCTION__);
  1691. // hook_metatag_info() includes translated strings, so each language is cached
  1692. // separately.
  1693. $cid = 'metatag:config:instance:info:' . $language->language;
  1694. if (!isset($info)) {
  1695. if ($cache = metatag_cache_get($cid)) {
  1696. $info = $cache->data;
  1697. }
  1698. else {
  1699. // Allow modules to act upon the record insertion using
  1700. // hook_metatag_config_instance_info().
  1701. $info = module_invoke_all('metatag_config_instance_info');
  1702. // Allow other modules to customize the data using
  1703. // hook_metatag_config_instance_info_alter().
  1704. drupal_alter('metatag_config_instance_info', $info);
  1705. metatag_cache_set($cid, $info);
  1706. }
  1707. }
  1708. if (isset($instance)) {
  1709. return isset($info[$instance]) ? $info[$instance] : FALSE;
  1710. }
  1711. else {
  1712. return $info;
  1713. }
  1714. }
  1715. /**
  1716. * Filter out meta tag values that equal the default values.
  1717. *
  1718. * @todo Use information in $values[$metatag]['default'] rather than a $defaults parameter.
  1719. */
  1720. function metatag_filter_values_from_defaults(array &$values, array $defaults = array()) {
  1721. foreach ($values as $metatag => $data) {
  1722. $default = isset($data['default']) ? $data['default'] : (isset($defaults[$metatag]['value']) ? $defaults[$metatag]['value'] : NULL);
  1723. if (isset($default) && isset($data['value']) && $default === $data['value']) {
  1724. // Meta tag has a default, and it matches user-submitted value.
  1725. unset($values[$metatag]);
  1726. }
  1727. elseif (!isset($default) && (is_string($data['value']) && !drupal_strlen($data['value']) || (is_array($data['value']) && !array_filter($data['value'])))) {
  1728. // Metatag does not have a default, and user did not submit a value.
  1729. unset($values[$metatag]);
  1730. }
  1731. if (isset($values[$metatag]['default'])) {
  1732. // Unset the default hidden value.
  1733. unset($values[$metatag]['default']);
  1734. }
  1735. }
  1736. }
  1737. /**
  1738. * Return all the parents of a given configuration instance.
  1739. *
  1740. * @param $instance
  1741. * A meta tag configuration instance.
  1742. *
  1743. * @return
  1744. * An array of instances starting with the $instance parameter, with the end
  1745. * of the array being the global instance.
  1746. */
  1747. function metatag_config_get_parent_instances($instance, $include_global = TRUE) {
  1748. $parents = array();
  1749. $segments = explode(':', $instance);
  1750. while (count($segments) > 0) {
  1751. $parents[] = implode(':', $segments);
  1752. array_pop($segments);
  1753. }
  1754. if ($include_global && end($parents) !== 'global') {
  1755. $parents[] = 'global';
  1756. }
  1757. reset($parents);
  1758. return $parents;
  1759. }
  1760. /**
  1761. * Get the proper label of a configuration instance.
  1762. *
  1763. * @param $instance
  1764. * A meta tag configuration instance.
  1765. */
  1766. function metatag_config_instance_label($instance) {
  1767. $labels = &drupal_static(__FUNCTION__, array());
  1768. if (!isset($labels[$instance])) {
  1769. $instance_parts = explode(':', $instance);
  1770. $instance_part = array_pop($instance_parts);
  1771. if ($context = metatag_config_instance_info($instance)) {
  1772. $labels[$instance] = $context['label'];
  1773. }
  1774. else {
  1775. $labels[$instance] = t('Unknown (@instance)', array('@instance' => $instance_part));
  1776. }
  1777. // Normally the following would use metatag_config_get_parent_instances()
  1778. // but since we already sliced the instance by separator and removed the
  1779. // last segment, putting the array back together gives us this instance's
  1780. // parent.
  1781. if (!empty($instance_parts)) {
  1782. $labels[$instance] = metatag_config_instance_label(implode(':', $instance_parts)) . ': ' . $labels[$instance];
  1783. }
  1784. }
  1785. return $labels[$instance];
  1786. }
  1787. /**
  1788. * Title callback for meta tag configuration instances.
  1789. */
  1790. function metatag_config_title($config) {
  1791. return metatag_config_instance_label($config->instance);
  1792. }
  1793. /**
  1794. * Access callback for meta tag configuration instances.
  1795. */
  1796. function metatag_config_access($op, $config = NULL) {
  1797. if (!user_access('administer meta tags')) {
  1798. return FALSE;
  1799. }
  1800. if ($op == 'enable') {
  1801. return !empty($config->disabled);
  1802. }
  1803. elseif ($op == 'disable') {
  1804. return empty($config->disabled);
  1805. }
  1806. elseif ($op == 'delete') {
  1807. return ($config->export_type & EXPORT_IN_DATABASE) && !($config->export_type & EXPORT_IN_CODE);
  1808. }
  1809. elseif ($op == 'revert') {
  1810. return ($config->export_type & EXPORT_IN_DATABASE) && ($config->export_type & EXPORT_IN_CODE);
  1811. }
  1812. return FALSE;
  1813. }
  1814. /**
  1815. * Checks if a metatag configuration record is enabled.
  1816. *
  1817. * @param string $instance
  1818. * The configuration instance machine name.
  1819. *
  1820. * @return bool
  1821. * TRUE if the configuration is enabled, or FALSE otherwise.
  1822. */
  1823. function metatag_config_is_enabled($instance, $include_defaults = FALSE, $include_global = TRUE) {
  1824. if ($include_defaults) {
  1825. $instances = metatag_config_get_parent_instances($instance, $include_global);
  1826. $configs = metatag_config_load_multiple($instances);
  1827. // Check if one of the configs is enabled.
  1828. foreach ($configs as $config) {
  1829. if (empty($config->disabled)) {
  1830. return TRUE;
  1831. }
  1832. }
  1833. // No enabled configs found.
  1834. return FALSE;
  1835. }
  1836. else {
  1837. $config = metatag_config_load($instance);
  1838. return !empty($config) && empty($config->disabled);
  1839. }
  1840. }
  1841. /**
  1842. * Wrapper around entity_language() to use LANGUAGE_NONE if the entity does not
  1843. * have a language assigned.
  1844. *
  1845. * @param $entity_type
  1846. * An entity type's machine name.
  1847. * @param $entity
  1848. * The entity to review;
  1849. *
  1850. * @return
  1851. * A string indicating the language code to be used.
  1852. */
  1853. function metatag_entity_get_language($entity_type, $entity) {
  1854. // Determine the entity's language.
  1855. $langcode = entity_language($entity_type, $entity);
  1856. // If no matching language was found, which will happen for e.g. terms and
  1857. // users, it is normally recommended to use the system default language.
  1858. // However, as the system default language can change, this could potentially
  1859. // cause data loss / confusion problems; as a result use the system "no
  1860. // language" value to avoid any potential problems.
  1861. if (empty($langcode)) {
  1862. $langcode = LANGUAGE_NONE;
  1863. }
  1864. return $langcode;
  1865. }
  1866. /**
  1867. * Implements hook_features_api().
  1868. */
  1869. function metatag_features_api() {
  1870. $components = array(
  1871. 'metatag' => array(
  1872. 'name' => t('Metatag'),
  1873. 'feature_source' => TRUE,
  1874. 'default_hook' => 'metatag_export_default',
  1875. 'default_file' => FEATURES_DEFAULTS_INCLUDED,
  1876. 'file' => drupal_get_path('module', 'metatag') . '/metatag.features.inc',
  1877. ),
  1878. );
  1879. return $components;
  1880. }
  1881. /**
  1882. * Implements hook_views_post_render().
  1883. */
  1884. function metatag_views_post_render(&$view, &$output, &$cache) {
  1885. // Build a shortcut to the current display object.
  1886. $display = $view->display[$view->current_display];
  1887. // Only proceed if this view is a full page, don't process block or other
  1888. // Views display objects.
  1889. if ($display->display_plugin == 'page' && isset($display->display_options['path'])) {
  1890. // Check if this is an entity display page, if so trigger
  1891. // hook_entity_view().
  1892. foreach (entity_get_info() as $entity_type => $entity_info) {
  1893. // Entity paths will include an auto-loader that matches the entity's
  1894. // name, thus the path will be 'some/path/%entity_name'.
  1895. if (isset($entity_info['path']) && ($display->display_options['path'] . $entity_type) == $entity_info['path']) {
  1896. // Only proceed if this entity type supports meta tags.
  1897. if (metatag_entity_supports_metatags($entity_type)) {
  1898. // There must be at least one argument and the first argument must be
  1899. // numerical.
  1900. if (!empty($view->args) && is_numeric($view->args[0])) {
  1901. // Only the first argument is used.
  1902. $entities = entity_load($entity_type, array($view->args[0]));
  1903. // Only if the entity actually exists.
  1904. if (!empty($entities)) {
  1905. $entity = array_pop($entities);
  1906. metatag_entity_view($entity, $entity_type, 'full', NULL, TRUE);
  1907. }
  1908. }
  1909. }
  1910. }
  1911. }
  1912. }
  1913. }
  1914. /**
  1915. * Implements hook_ctools_render_alter().
  1916. *
  1917. * Temporary solution to load meta tags on entity pages that are driven by
  1918. * CTools display handlers.
  1919. */
  1920. function metatag_ctools_render_alter(&$info, $page, $context) {
  1921. // Only proceed if this is a full page (don't process individual panes) and
  1922. // there's an 'admin path' for the current task.
  1923. if ($page && !empty($context['task']['admin path'])) {
  1924. // Check if this is an entity display page, if so trigger
  1925. // hook_entity_view().
  1926. foreach (entity_get_info() as $entity_type => $entity_info) {
  1927. // Entity paths will include an auto-loader that matches the entity's
  1928. // name, thus the path will be 'some/path/%entity_name'.
  1929. if (isset($entity_info['path']) && $context['task']['admin path'] == $entity_info['path']) {
  1930. // Only proceed if this entity type supports meta tags.
  1931. if (metatag_entity_supports_metatags($entity_type)) {
  1932. // There must be at least one argument and the first argument must be
  1933. // numerical.
  1934. if (!empty($context['args']) && is_numeric($context['args'][0])) {
  1935. // We need to pop entity from contexts array.
  1936. $first_context = array_pop($context['contexts']);
  1937. // Only if the context actually exists, which would be an entity.
  1938. if (!empty($first_context->data) && is_object($first_context->data)) {
  1939. $langcode = $GLOBALS['language_content']->language;
  1940. metatag_entity_view($first_context->data, $entity_type, 'full', $langcode, TRUE);
  1941. }
  1942. }
  1943. }
  1944. }
  1945. }
  1946. }
  1947. }
  1948. /**
  1949. * Implements hook_entity_translation_delete().
  1950. *
  1951. * Required for content translations being handled via Entity_Translation to
  1952. * remove the appropriate record when a translation is removed without the
  1953. * corresponding entity record also being removed.
  1954. */
  1955. function metatag_entity_translation_delete($entity_type, $entity, $langcode) {
  1956. // Get the entity's ID.
  1957. list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
  1958. $revision_id = intval($revision_id);
  1959. // Delete the translation.
  1960. metatag_metatags_delete($entity_type, $entity_id, $revision_id, $langcode);
  1961. }
  1962. /**
  1963. * Translates the metatag if i18n_string is enabled.
  1964. * @param $name
  1965. * Array or string concatenated with ':' that contains textgroup and string context
  1966. * @param string $string
  1967. * String in default language or array of strings to be translated
  1968. * @param $options
  1969. * An associative array of additional options. @see i18n_string_translate()
  1970. */
  1971. function metatag_translate($name, $string, $langcode = NULL, $update = FALSE) {
  1972. if (function_exists('i18n_string_translate')) {
  1973. $options = array(
  1974. 'langcode' => $langcode,
  1975. 'update' => $update,
  1976. );
  1977. return i18n_string_translate($name, $string, $options);
  1978. }
  1979. else {
  1980. return $string;
  1981. }
  1982. }
  1983. /**
  1984. * Checks if this entity is the default revision (published).
  1985. *
  1986. * @param object $entity
  1987. * The entity object, e.g., $node.
  1988. *
  1989. * @return bool
  1990. * TRUE if the entity is the default revision, FALSE otherwise.
  1991. */
  1992. function _metatag_isdefaultrevision($entity) {
  1993. // D7 "Forward revisioning" is complex and causes a node_save() with the
  1994. // future node in node table. This fires hook_node_update() twice and cause
  1995. // abnormal behaviour in metatag.
  1996. //
  1997. // The steps taken by Workbench Moderation is to save the forward revision
  1998. // first and overwrite this with the live version in a shutdown function in
  1999. // a second step. This will confuse metatag. D7 has no generic property
  2000. // in the node object, if the node that is updated is the 'published' version
  2001. // or only a draft of a future version.
  2002. //
  2003. // This behaviour will change in D8 where $node->isDefaultRevision has been
  2004. // introduced. See below links for more details.
  2005. // - https://www.drupal.org/node/1879482
  2006. // - https://www.drupal.org/node/218755
  2007. // - https://www.drupal.org/node/1522154
  2008. //
  2009. // Every moderation module saving a forward revision needs to return FALSE.
  2010. // @todo: Refactor this workaround under D8.
  2011. // Support for Workbench Moderation v1 - if this is a node, check if the
  2012. // content type supports moderation.
  2013. if (function_exists('workbench_moderation_node_type_moderated') && workbench_moderation_node_type_moderated($entity->type) === TRUE) {
  2014. return !empty($entity->workbench_moderation['updating_live_revision']);
  2015. }
  2016. return FALSE;
  2017. }
  2018. /**
  2019. * Generate the cache ID to use with metatag_cache_get/metatag_cache_set calls.
  2020. *
  2021. * @param array $cid_parts
  2022. * A list of values to be used.
  2023. *
  2024. * @return string
  2025. * The cache ID string.
  2026. */
  2027. function metatag_cache_default_cid_parts(array $cid_parts = array()) {
  2028. // The initial parts, control the order of the parts.
  2029. $cid_part_defaults = array(
  2030. 'cache_type' => 'output',
  2031. 'instance' => '',
  2032. 'entity_type' => '',
  2033. 'entity_id' => '',
  2034. 'bundle' => '',
  2035. 'langcode' => $GLOBALS['language_content']->language,
  2036. 'revision_id' => '',
  2037. 'view_mode' => '',
  2038. 'status' => 200,
  2039. 'protocol' => $GLOBALS['is_https'] ? 'https' : 'http',
  2040. 'hostname' => $_SERVER['HTTP_HOST'],
  2041. 'base_path' => base_path(),
  2042. );
  2043. $cid_parts = array_merge($cid_part_defaults, $cid_parts);
  2044. // Add the HTTP status code.
  2045. $headers = drupal_get_http_header();
  2046. if (isset($headers['status'])) {
  2047. $cid_parts['status'] = intval($headers['status']);
  2048. }
  2049. // Allow each page in a sequence to have different values.
  2050. if (isset($_GET['page'])) {
  2051. $cid_parts['page'] = $_GET['page'];
  2052. }
  2053. // Allow other modules to customize the data using
  2054. // hook_metatag_page_cache_cid_parts_alter().
  2055. drupal_alter('metatag_page_cache_cid_parts', $cid_parts);
  2056. // Remove empty parts.
  2057. $cid_parts = array_filter($cid_parts);
  2058. // Concatenate the cache ID parts, trim the results to 128 chars.
  2059. return substr(implode(':', $cid_parts), 0, 128);
  2060. }
  2061. /**
  2062. * Wrapper for cache_set.
  2063. *
  2064. * @see cache_set().
  2065. */
  2066. function metatag_cache_set($cid, $data) {
  2067. // Cache the data for later.
  2068. return cache_set($cid, $data, 'cache_metatag');
  2069. }
  2070. /**
  2071. * Wrapper for cache_get.
  2072. *
  2073. * @see cache_get().
  2074. */
  2075. function metatag_cache_get($cid) {
  2076. // Try to load the object.
  2077. return cache_get($cid, 'cache_metatag');
  2078. }
  2079. /**
  2080. * Determines if we are in an error page and return the appropriate instance.
  2081. *
  2082. * @return string
  2083. */
  2084. function metatag_is_error_page() {
  2085. $known_errors = array(
  2086. 'global:403' => '403 Forbidden',
  2087. 'global:404' => '404 Not Found',
  2088. );
  2089. $headers = drupal_get_http_header();
  2090. if (isset($headers['status'])) {
  2091. foreach ($known_errors as $error => $status) {
  2092. if ($status == $headers['status']) {
  2093. return $error;
  2094. }
  2095. }
  2096. }
  2097. return '';
  2098. }