metatag.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <?php
  2. /**
  3. * @file
  4. * Metatag primary classes.
  5. */
  6. interface DrupalMetaTagInterface {
  7. /**
  8. * Constructor
  9. *
  10. * @param array $info
  11. * The information about the meta tag from metatag_get_info().
  12. */
  13. function __construct(array $info, array $data = array());
  14. function getForm();
  15. //function validateForm();
  16. //function processForm();
  17. function getValue();
  18. function getWeight();
  19. function getElement();
  20. function tidyValue($value);
  21. function convertUrlToAbsolute($url);
  22. }
  23. class DrupalDefaultMetaTag implements DrupalMetaTagInterface {
  24. protected $info;
  25. protected $data = array('value' => '');
  26. protected $weight = 0;
  27. function __construct(array $info, array $data = NULL) {
  28. $this->info = $info;
  29. if (isset($data)) {
  30. $this->data = $data;
  31. }
  32. }
  33. /**
  34. * Calculate the weight of this meta tag.
  35. *
  36. * @return integer
  37. */
  38. public function getWeight() {
  39. static $counter = 0;
  40. // If no weight value is found, stack this meta tag at the end.
  41. $weight = 100;
  42. if (!empty($this->info['weight'])) {
  43. $weight = $this->info['weight'];
  44. }
  45. return $weight + ($counter++ * 0.1);
  46. }
  47. /**
  48. * Build the form for this meta tag.
  49. *
  50. * @return array
  51. * A standard FormAPI array.
  52. */
  53. public function getForm(array $options = array()) {
  54. return array();
  55. }
  56. /**
  57. * Get the string value of this meta tag.
  58. *
  59. * @return string
  60. * The value of this meta tag.
  61. */
  62. public function getValue(array $options = array()) {
  63. $value = $this->tidyValue($this->data['value']);
  64. // Translate the final output string prior to output. Use the
  65. // 'output' i18n_string object type, and pass along the meta tag's
  66. // options as the context so it can be handled appropriately.
  67. $value = metatag_translate_metatag($value, $this->info['name'], $options, NULL, TRUE);
  68. return $value;
  69. }
  70. /**
  71. * Get the HTML tag for this meta tag.
  72. *
  73. * @return array
  74. * A render array for this meta tag.
  75. */
  76. public function getElement(array $options = array()) {
  77. $value = $this->getValue($options);
  78. if (strlen($value) === 0) {
  79. return array();
  80. }
  81. // The stack of elements that will be output.
  82. $elements = array();
  83. // Dynamically add each option to this setting.
  84. $base_element = isset($this->info['element']) ? $this->info['element'] : array();
  85. // Single item.
  86. if (empty($this->info['multiple'])) {
  87. $values = array($value);
  88. }
  89. // Multiple items.
  90. else {
  91. $values = array_filter(explode(',', $value));
  92. }
  93. // Loop over each item.
  94. if (!empty($values)) {
  95. foreach ($values as $ctr => $value) {
  96. $value = trim($value);
  97. // Some meta tags must be output as secure URLs.
  98. if (!empty($this->info['secure'])) {
  99. $value = str_replace('http://', 'https://', $value);
  100. }
  101. // Combine the base configuration for this meta tag with the value.
  102. $element = $base_element + array(
  103. '#theme' => 'metatag',
  104. '#tag' => 'meta',
  105. '#id' => 'metatag_' . $this->info['name'] . '_' . $ctr,
  106. '#name' => $this->info['name'],
  107. '#value' => $value,
  108. '#weight' => $this->getWeight(),
  109. );
  110. // Add header information if desired.
  111. if (!empty($this->info['header'])) {
  112. $element['#attached']['drupal_add_http_header'][] = array($this->info['header'], $value);
  113. }
  114. $elements[] = array($element, $element['#id']);
  115. }
  116. }
  117. if (!empty($elements)) {
  118. return array(
  119. '#attached' => array('drupal_add_html_head' => $elements),
  120. );
  121. }
  122. }
  123. /**
  124. * Remove unwanted formatting from a meta tag.
  125. *
  126. * @param $value string
  127. * The meta tag value to be tidied up.
  128. *
  129. * @return string
  130. * The meta tag value after it has been tidied up.
  131. */
  132. public function tidyValue($value) {
  133. // Check for Media strings from the WYSIWYG submodule.
  134. if (module_exists('media_wysiwyg') && strpos($value, '[[{') !== FALSE) {
  135. $value = media_wysiwyg_filter($value);
  136. }
  137. // Specifically replace encoded spaces, because some WYSIWYG editors are
  138. // silly. Do this before decoding the other HTML entities so that the output
  139. // doesn't end up with a bunch of a-circumflex characters.
  140. $value = str_replace('&nbsp;', ' ', $value);
  141. // Decode HTML entities.
  142. $value = decode_entities($value);
  143. // Remove any HTML code that might have been included.
  144. $value = strip_tags($value);
  145. // Strip errant whitespace.
  146. $value = str_replace(array("\r\n", "\n", "\r", "\t"), ' ', $value);
  147. $value = str_replace(' ', ' ', $value);
  148. $value = str_replace(' ', ' ', $value);
  149. $value = trim($value);
  150. return $value;
  151. }
  152. /**
  153. * Make sure a given URL is absolute.
  154. *
  155. * @param string $url
  156. * The URL to convert to an absolute URL.
  157. *
  158. * @return string
  159. * The argument converted to an absolute URL.
  160. */
  161. function convertUrlToAbsolute($url) {
  162. // Convert paths relative to the hostname, that start with a slash, to
  163. // ones that are relative to the Drupal root path.
  164. if (strpos($url, base_path()) === 0) {
  165. // Logic:
  166. // * Get the length of the base_path(),
  167. // * Get a portion of the image's path starting from the position equal
  168. // to the base_path()'s length; this will result in a path relative
  169. // to the Drupal installation's base directory.
  170. $len = strlen(base_path());
  171. $url = substr($url, $len);
  172. }
  173. // Pass everything else through file_create_url(). The alternative is to
  174. // use url() but it would insert '?q=' into the path.
  175. return file_create_url($url);
  176. }
  177. }
  178. /**
  179. * Text-based meta tag controller.
  180. */
  181. class DrupalTextMetaTag extends DrupalDefaultMetaTag {
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function getForm(array $options = array()) {
  186. $options += array(
  187. 'token types' => array(),
  188. );
  189. $form['value'] = isset($this->info['form']) ? $this->info['form'] : array();
  190. $form['value'] += array(
  191. '#type' => 'textfield',
  192. '#title' => $this->info['label'],
  193. '#description' => !empty($this->info['description']) ? $this->info['description'] : '',
  194. '#default_value' => isset($this->data['value']) ? $this->data['value'] : '',
  195. '#element_validate' => array('token_element_validate'),
  196. '#token_types' => $options['token types'],
  197. '#maxlength' => 1024,
  198. );
  199. // Optional handling for items that allow multiple values.
  200. if (!empty($this->info['multiple'])) {
  201. $form['value']['#description'] .= ' ' . t('Multiple values may be used, separated by a comma. Note: Tokens that return multiple values will be handled automatically.');
  202. }
  203. // Optional handling for images.
  204. if (!empty($this->info['image'])) {
  205. $form['value']['#description'] .= ' ' . t('This will be able to extract the URL from an image field.');
  206. }
  207. // Optional handling for languages.
  208. if (!empty($this->info['is_language'])) {
  209. $form['value']['#description'] .= ' ' . t('This will not be displayed if it is set to the "Language neutral" (i.e. "und").');
  210. }
  211. // Optional support for select_or_other.
  212. if ($form['value']['#type'] == 'select' && !empty($this->info['select_or_other']) && module_exists('select_or_other')) {
  213. $form['value']['#type'] = 'select_or_other';
  214. $form['value']['#other'] = t('Other (please type a value)');
  215. $form['value']['#multiple'] = FALSE;
  216. $form['value']['#other_unknown_defaults'] = 'other';
  217. $form['value']['#other_delimiter'] = FALSE;
  218. $form['value']['#theme'] = 'select_or_other';
  219. $form['value']['#select_type'] = 'select';
  220. $form['value']['#element_validate'] = array('select_or_other_element_validate');
  221. }
  222. // Support for dependencies, using Form API's #states system.
  223. // @see metatag.api.php.
  224. // @see https://api.drupal.org/drupal_process_states
  225. if (!empty($this->info['dependencies'])) {
  226. foreach ($this->info['dependencies'] as $specs) {
  227. $form['value']['#states']['visible'][':input[name*="[' . $specs['dependency'] . '][' . $specs['attribute'] . ']"]'] = array(
  228. $specs['condition'] => $specs['value'],
  229. );
  230. }
  231. }
  232. return $form;
  233. }
  234. /**
  235. * {@inheritdoc}
  236. */
  237. public function getValue(array $options = array()) {
  238. $options += array(
  239. 'instance' => '',
  240. 'token data' => array(),
  241. // Remove any remaining token after the string is parsed.
  242. 'clear' => TRUE,
  243. 'sanitize' => variable_get('metatag_token_sanitize', FALSE),
  244. 'raw' => FALSE,
  245. );
  246. $value = $this->data['value'];
  247. if (empty($options['raw'])) {
  248. // Give other modules the opportunity to use hook_metatag_pattern_alter()
  249. // to modify defined token patterns and values before replacement.
  250. drupal_alter('metatag_pattern', $value, $options['token data'], $this->info['name']);
  251. $value = token_replace($value, $options['token data'], $options);
  252. }
  253. // Special handling for language meta tags.
  254. if (!empty($this->info['is_language'])) {
  255. // If the meta tag value equals LANGUAGE_NONE, i.e. "und", then don't
  256. // output it.
  257. if (is_string($value) && $value == LANGUAGE_NONE) {
  258. $value = '';
  259. }
  260. }
  261. // Special handling for images and other URLs.
  262. if (!empty($this->info['image']) || !empty($this->info['url'])) {
  263. // Support multiple items, whether it's needed or not. Also remove the
  264. // empty values.
  265. $values = array_filter(explode(',', $value));
  266. // If this meta tag does *not* allow multiple items, only keep the first
  267. // one.
  268. if (empty($this->info['multiple']) && !empty($values[0])) {
  269. $values = array($values[0]);
  270. }
  271. foreach ($values as $key => &$image_value) {
  272. // Remove any unwanted whitespace around the value.
  273. $image_value = trim($image_value);
  274. // If this contains embedded image tags, extract the image URLs.
  275. if (!empty($this->info['image']) && strip_tags($image_value) != $image_value) {
  276. $matches = array();
  277. preg_match('/src="([^"]*)"/', $image_value, $matches);
  278. if (!empty($matches[1])) {
  279. $image_value = $matches[1];
  280. }
  281. }
  282. // Convert the URL to an absolute URL.
  283. $image_value = $this->convertUrlToAbsolute($image_value);
  284. // Replace spaces the URL encoded entity to avoid validation problems.
  285. $image_value = str_replace(' ', '%20', $image_value);
  286. }
  287. // Combine the multiple values into a single string.
  288. $value = implode(',', $values);
  289. }
  290. $value = $this->tidyValue($value);
  291. // Translate the final output string prior to output. Use the
  292. // 'output' i18n_string object type, and pass along the meta tag's
  293. // options as the context so it can be handled appropriately.
  294. $value = metatag_translate_metatag($value, $this->info['name'], $options, NULL, TRUE);
  295. return $value;
  296. }
  297. }
  298. /**
  299. * Link type meta tag controller.
  300. */
  301. class DrupalLinkMetaTag extends DrupalTextMetaTag {
  302. /**
  303. * {@inheritdoc}
  304. */
  305. public function getElement(array $options = array()) {
  306. $element = isset($this->info['element']) ? $this->info['element'] : array();
  307. $value = $this->getValue($options);
  308. if (strlen($value) === 0) {
  309. return array();
  310. }
  311. $element += array(
  312. '#theme' => 'metatag_link_rel',
  313. '#tag' => 'link',
  314. '#id' => 'metatag_' . $this->info['name'],
  315. '#name' => $this->info['name'],
  316. '#value' => $value,
  317. '#weight' => $this->getWeight(),
  318. );
  319. if (!isset($this->info['header']) || !empty($this->info['header'])) {
  320. // Also send the generator in the HTTP header.
  321. // @todo This does not support 'rev' or alternate link headers.
  322. $element['#attached']['drupal_add_http_header'][] = array('Link', '<' . $value . '>;' . drupal_http_header_attributes(array('rel' => $element['#name'])), TRUE);
  323. }
  324. return array(
  325. '#attached' => array('drupal_add_html_head' => array(array($element, $element['#id']))),
  326. );
  327. }
  328. }
  329. /**
  330. * Title meta tag controller.
  331. *
  332. * This extends DrupalTextMetaTag as we need to alter variables in
  333. * template_preprocess_html() rather output a normal meta tag.
  334. */
  335. class DrupalTitleMetaTag extends DrupalTextMetaTag {
  336. /**
  337. * {@inheritdoc}
  338. */
  339. public function getElement(array $options = array()) {
  340. $element = array();
  341. if ($value = $this->getValue($options)) {
  342. $element['#attached']['metatag_set_preprocess_variable'][] = array('html', 'head_title', $value);
  343. $element['#attached']['metatag_set_preprocess_variable'][] = array('html', 'head_array', array('title' => $value));
  344. }
  345. return $element;
  346. }
  347. }
  348. /**
  349. * Multiple value meta tag controller.
  350. */
  351. class DrupalListMetaTag extends DrupalDefaultMetaTag {
  352. /**
  353. * {@inheritdoc}
  354. */
  355. function __construct(array $info, array $data = NULL) {
  356. // Ensure that the $data['value] argument is an array.
  357. if (empty($data['value'])) {
  358. $data['value'] = array();
  359. }
  360. $data['value'] = (array) $data['value'];
  361. parent::__construct($info, $data);
  362. }
  363. /**
  364. * {@inheritdoc}
  365. */
  366. public function getForm(array $options = array()) {
  367. $form['value'] = isset($this->info['form']) ? $this->info['form'] : array();
  368. $form['value'] += array(
  369. '#type' => 'checkboxes',
  370. '#title' => $this->info['label'],
  371. '#description' => !empty($this->info['description']) ? $this->info['description'] : '',
  372. '#default_value' => isset($this->data['value']) ? $this->data['value'] : array(),
  373. );
  374. return $form;
  375. }
  376. /**
  377. * {@inheritdoc}
  378. */
  379. public function getValue(array $options = array()) {
  380. $values = array_keys(array_filter($this->data['value']));
  381. sort($values);
  382. $value = implode(', ', $values);
  383. $value = $this->tidyValue($value);
  384. // Translate the final output string prior to output. Use the
  385. // 'output' i18n_string object type, and pass along the meta tag's
  386. // options as the context so it can be handled appropriately.
  387. $value = metatag_translate_metatag($value, $this->info['name'], $options, NULL, TRUE);
  388. return $value;
  389. }
  390. }
  391. /**
  392. * Date interval meta tag controller.
  393. */
  394. class DrupalDateIntervalMetaTag extends DrupalDefaultMetaTag {
  395. /**
  396. * {@inheritdoc}
  397. */
  398. public function getForm(array $options = array()) {
  399. $form['value'] = array(
  400. '#type' => 'textfield',
  401. '#title' => t('!title interval', array('!title' => $this->info['label'])),
  402. '#default_value' => isset($this->data['value']) ? $this->data['value'] : '',
  403. '#element_validate' => array('element_validate_integer_positive'),
  404. '#maxlength' => 4,
  405. '#description' => isset($this->info['description']) ? $this->info['description'] : '',
  406. );
  407. $form['period'] = array(
  408. '#type' => 'select',
  409. '#title' => t('!title interval type', array('!title' => $this->info['label'])),
  410. '#default_value' => isset($this->data['period']) ? $this->data['period'] : '',
  411. '#options' => array(
  412. '' => t('- none -'),
  413. 'day' => t('Day(s)'),
  414. 'week' => t('Week(s)'),
  415. 'month' => t('Month(s)'),
  416. 'year' => t('Year(s)'),
  417. ),
  418. );
  419. return $form;
  420. }
  421. /**
  422. * {@inheritdoc}
  423. */
  424. public function getValue(array $options = array()) {
  425. $value = '';
  426. if (!empty($this->data['value'])) {
  427. $interval = intval($this->data['value']);
  428. if (!empty($interval) && !empty($this->data['period'])) {
  429. $period = $this->data['period'];
  430. $value = format_plural($interval, '@count ' . $period, '@count ' . $period . 's');
  431. }
  432. }
  433. // Translate the final output string prior to output. Use the
  434. // 'output' i18n_string object type, and pass along the meta tag's
  435. // options as the context so it can be handled appropriately.
  436. $value = metatag_translate_metatag($value, $this->info['name'], $options, NULL, TRUE);
  437. return $value;
  438. }
  439. }