xref: /plugin/autotooltip/helper.php (revision e296955091db38ffe3d3b5165a7924246dcb0bf9)
1<?php
2if(!defined('DOKU_INC')) die();
3
4/**
5 * Auto-Tooltip DokuWiki plugin
6 *
7 * @license    MIT
8 * @author     Eli Fenton
9 */
10class helper_plugin_autotooltip extends DokuWiki_Plugin {
11	private $localRenderer;
12	private static $metaCache = [];
13
14	public function __construct() {
15		$this->localRenderer = new Doku_Renderer_xhtml;
16	}
17
18
19	/**
20	 * Return methods of this helper
21	 *
22	 * @return array with methods description
23	 */
24	public function getMethods() {
25		$result = array();
26		$result[] = array(
27			'name' => 'forText',
28			'desc' => 'Manually construct a tooltip',
29			'params' => array(
30				'content' => 'string',
31				'tooltip' => 'string',
32				'title (optional)' => 'string',
33				'preTitle (optional)' => 'string',
34				'classes (optional)' => 'string',
35				'textClasses (optional)' => 'string',
36			),
37			'return' => array('result' => 'string')
38		);
39		$result[] = array(
40			'name' => 'forWikilink',
41			'desc' => 'Generate a tooltip from a wikilink',
42			'params' => array(
43				'id' => 'string',
44				'content (optional)' => 'string',
45				'preTitle (optional)' => 'string',
46				'classes (optional)' => 'string',
47				'textClasses (optional)' => 'string',
48			),
49			'return' => array('result' => 'string')
50		);
51		return $result;
52	}
53
54
55	/**
56	 * Return a simple tooltip.
57	 *
58	 * @param string $content - The on-page content. May contain newlines.
59	 * @param string $tooltip - The tooltip content. Newlines will be rendered as line breaks.
60	 * @param string $title - The title inside the tooltip.
61	 * @param string $preTitle - Text to display before the title. Newlines will be rendered as line breaks.
62	 * @param string $classes - CSS classes to add to this tooltip.
63	 * @param string $textClasses - CSS classes to add to the linked text.
64	 * @return string
65	 */
66	public function forText($content, $tooltip, $title='', $preTitle = '', $classes = '', $textClasses = '') {
67		if (empty($classes)) {
68			$classes = $this->getConf('style');
69		}
70		if (empty($classes)) {
71			$classes = 'default';
72		}
73		$delay = $this->getConf('delay') ?: 0;
74
75		// Sanitize
76		$classes = htmlspecialchars($classes);
77		// Add the plugin prefix to all classes.
78		$classes = preg_replace('/(\w+)/', 'plugin-autotooltip__$1', $classes);
79
80		$partCount = (empty($title) ? 0 : 1) + (empty($preTitle) ? 0 : 1) + (empty($tooltip) ? 0 : 1);
81		if ($partCount > 1 || strchr($tooltip, "\n") !== FALSE || strlen($tooltip) > 40) {
82			$classes .= ' plugin-autotooltip_big';
83		}
84
85		if (empty($textClasses)) {
86			$textClasses = 'plugin-autotooltip_linked';
87			if (strstr($content, '<a ') === FALSE) {
88				$textClasses .= ' plugin-autotooltip_simple';
89			}
90		}
91
92		$contentParts = [];
93		if (!empty($preTitle)) {
94			$contentParts[] = $this->_formatTT($preTitle);
95		}
96		if (!empty($title)) {
97			$contentParts[] = '<span class="plugin-autotooltip-title">' . $title . '</span>';
98		}
99		if (!empty($tooltip)) {
100			$contentParts[] = $this->_formatTT($tooltip);
101		}
102
103		return '<span class="' . $textClasses . '" onmouseover="autotooltip.show(event)" onmouseout="autotooltip.hide()" data-delay="' . $delay . '">' .
104			$content .
105			'<span class="plugin-autotooltip-hidden-classes">' . $classes . '</span>' .
106			'<span class="plugin-autotooltip-hidden-tip">' .
107			implode('<br><br>', $contentParts) .
108			'</span>' .
109		'</span>';
110	}
111
112
113	/**
114	 * Render a tooltip, with the title and abstract of a page.
115	 *
116	 * @param string $id - A page id.
117	 * @param string $content - The on-page content. Newlines will be rendered as line breaks. Omit to use the page's title.
118	 * @param string $preTitle - Text to display before the title in the tooltip. Newlines will be rendered as line breaks.
119	 * @param string $classes - CSS classes to add to this tooltip.
120	 * @param string $textClasses - CSS classes to add to the linked text.
121	 * @return string
122	 */
123	public function forWikilink($id, $content = null, $preTitle = '', $classes = '', $textClasses = '') {
124		global $ID;
125		$id = resolve_id(getNS($ID), $id, false);
126
127		$meta = self::read_meta_fast($id);
128		$title = $meta['title'];
129
130		$link = $this->localRenderer->internallink($id, $content ?: $title, null, true);
131
132		if (page_exists(preg_replace('/\#.*$/', '', $id))) {
133			$link = $this->stripNativeTooltip($link);
134			return $this->forText($link, $meta['abstract'], $title, $preTitle, $classes, $textClasses);
135		}
136		else {
137			return $link;
138		}
139	}
140
141
142	/**
143	 * Is this id excluded from the plugin?
144	 *
145	 * @param string $id
146	 * @return boolean
147	 */
148	public function isExcluded($id) {
149		$inclusions = $this->getConf('linkall_inclusions');
150		$exclusions = $this->getConf('linkall_exclusions');
151		return (!empty($inclusions) && !preg_match("/$inclusions/", $id)) ||
152			(!empty($exclusions) && preg_match("/$exclusions/", $id));
153	}
154
155
156	/**
157	 * Strip the native title= tooltip from an anchor tag.
158	 *
159	 * @param string $link
160	 * @return string
161	 */
162	public function stripNativeTooltip($link) {
163		return preg_replace('/title="[^"]*"/', '', $link);
164	}
165
166
167	/**
168	 * Reads specific metadata about 10x faster than p_get_metadata. p_get_metadata only uses caching for the current
169	 * page, and uses the very slow php serialization. However, in a wiki with infrequently accessed pages, it's
170	 * extremely slow.
171	 *
172	 * @param string $id
173	 * @return array - An array containing 'title' and 'abstract.'
174	 */
175	static function read_meta_fast($id) {
176		global $ID;
177		$id = resolve_id(getNS($ID), preg_replace('/\#.*$/', '', $id), true);
178
179		if (isset(self::$metaCache[$id])) {
180			return self::$metaCache[$id];
181		}
182
183		$results = [
184			'title' => p_get_metadata(cleanID($id), 'title'),
185			'abstract' => p_get_metadata(cleanID($id), 'plugin_description keywords') ?: p_get_metadata(cleanID($id), 'description abstract')
186		];
187
188		// By default, the abstract starts with the title. Remove it so it's not displayed twice, but still fetch
189		// both pieces of metadata, in case another plugin rewrote the abstract.
190		$results['abstract'] = preg_replace(
191			'/^' . self::_pregEscape($results['title']) . '(\r?\n)+/',
192			'',
193			$results['abstract']
194		);
195
196		self::$metaCache[$id] = $results;
197		return $results;
198	}
199
200
201	/**
202	 * Format tooltip text.
203	 *
204	 * @param string $tt - Tooltip text.
205	 * @return string
206	 */
207	private function _formatTT($tt) {
208		// Convert double-newlines into vertical space.
209		$tt = preg_replace('/(\r?\n){2,}/', '<br><br>', $tt);
210		// Single newlines get collapsed, just like in HTML.
211		return preg_replace('/(\r?\n)/', ' ', $tt);
212	}
213
214
215	/**
216	 * Escape a string for inclusion in a regular expression, assuming forward slash is used as the delimiter.
217	 *
218	 * @param string $r - The regex string, without delimiters.
219	 * @return string
220	 */
221	private static function _pregEscape($r) {
222		return preg_replace('/\//', '\\/', preg_quote($r));
223	}
224}
225