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			'<!-- googleoff: all -->' .
107			'<span class="plugin-autotooltip-hidden-tip">' .
108			implode('<br><br>', $contentParts) .
109			'</span>' .
110			'<!-- googleon: all -->' .
111		'</span>';
112	}
113
114
115	/**
116	 * Render a tooltip, with the title and abstract of a page.
117	 *
118	 * @param string $id - A page id.
119	 * @param string $content - The on-page content. Newlines will be rendered as line breaks. Omit to use the page's title.
120	 * @param string $preTitle - Text to display before the title in the tooltip. Newlines will be rendered as line breaks.
121	 * @param string $classes - CSS classes to add to this tooltip.
122	 * @param string $textClasses - CSS classes to add to the linked text.
123	 * @return string
124	 */
125	public function forWikilink($id, $content = null, $preTitle = '', $classes = '', $textClasses = '') {
126		global $ID;
127		$id = resolve_id(getNS($ID), $id, false);
128
129		$meta = self::read_meta_fast($id);
130		$title = $meta['title'];
131
132		$link = $this->localRenderer->internallink($id, $content ?: $title, null, true);
133
134		if (page_exists(preg_replace('/\#.*$/', '', $id))) {
135			$link = $this->stripNativeTooltip($link);
136			return $this->forText($link, $meta['abstract'], $title, $preTitle, $classes, $textClasses);
137		}
138		else {
139			return $link;
140		}
141	}
142
143
144	/**
145	 * Is this id excluded from the plugin?
146	 *
147	 * @param string $id
148	 * @return boolean
149	 */
150	public function isExcluded($id) {
151		$inclusions = $this->getConf('linkall_inclusions');
152		$exclusions = $this->getConf('linkall_exclusions');
153		return (!empty($inclusions) && !preg_match("/$inclusions/", $id)) ||
154			(!empty($exclusions) && preg_match("/$exclusions/", $id));
155	}
156
157
158	/**
159	 * Strip the native title= tooltip from an anchor tag.
160	 *
161	 * @param string $link
162	 * @return string
163	 */
164	public function stripNativeTooltip($link) {
165		return preg_replace('/title="[^"]*"/', '', $link);
166	}
167
168
169	/**
170	 * Reads specific metadata about 10x faster than p_get_metadata. p_get_metadata only uses caching for the current
171	 * page, and uses the very slow php serialization. However, in a wiki with infrequently accessed pages, it's
172	 * extremely slow.
173	 *
174	 * @param string $id
175	 * @return array - An array containing 'title' and 'abstract.'
176	 */
177	static function read_meta_fast($id) {
178		global $ID;
179		$id = resolve_id(getNS($ID), preg_replace('/\#.*$/', '', $id), true);
180
181		if (isset(self::$metaCache[$id])) {
182			return self::$metaCache[$id];
183		}
184
185		$results = [
186			'title' => p_get_metadata(cleanID($id), 'title'),
187			'abstract' => p_get_metadata(cleanID($id), 'plugin_description keywords') ?: p_get_metadata(cleanID($id), 'description abstract')
188		];
189
190		// By default, the abstract starts with the title. Remove it so it's not displayed twice, but still fetch
191		// both pieces of metadata, in case another plugin rewrote the abstract.
192		$results['abstract'] = preg_replace(
193			'/^' . self::_pregEscape($results['title']) . '(\r?\n)+/',
194			'',
195			$results['abstract']
196		);
197
198		self::$metaCache[$id] = $results;
199		return $results;
200	}
201
202
203	/**
204	 * Format tooltip text.
205	 *
206	 * @param string $tt - Tooltip text.
207	 * @return string
208	 */
209	private function _formatTT($tt) {
210		// Convert double-newlines into vertical space.
211		$tt = preg_replace('/(\r?\n){2,}/', '<br><br>', $tt);
212		// Single newlines get collapsed, just like in HTML.
213		return preg_replace('/(\r?\n)/', ' ', $tt);
214	}
215
216
217	/**
218	 * Escape a string for inclusion in a regular expression, assuming forward slash is used as the delimiter.
219	 *
220	 * @param string $r - The regex string, without delimiters.
221	 * @return string
222	 */
223	private static function _pregEscape($r) {
224		return preg_replace('/\//', '\\/', preg_quote($r));
225	}
226}
227