summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/HierarchyLookup.php
blob: 584fb6f669803b450184d845cb0d47e9ecb51e47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
<?php

namespace SMW;

use InvalidArgumentException;
use Onoi\Cache\Cache;
use Psr\Log\LoggerAwareTrait;

/**
 * @license GNU GPL v2+
 * @since 2.3
 *
 * @author mwjames
 */
class HierarchyLookup {

	use LoggerAwareTrait;

	/**
	 * Persistent cache namespace
	 */
	const CACHE_NAMESPACE = 'smw:hierarchy';

	/**
	 * Consecutive hierarchy types
	 */
	const TYPE_PROPERTY = 'type.property';
	const TYPE_CATEGORY = 'type.category';

	/**
	 * @var Store
	 */
	private $store;

	/**
	 * @var Cache|null
	 */
	private $cache;

	/**
	 * @var []
	 */
	private $inMemoryCache = [];

	/**
	 * @var integer
	 */
	private $cacheTTL;

	/**
	 * Use 0 to disable the hierarchy lookup
	 *
	 * @var integer
	 */
	private $subcategoryDepth = 10;

	/**
	 * Use 0 to disable the hierarchy lookup
	 *
	 * @var integer
	 */
	private $subpropertyDepth = 10;

	/**
	 * @since 2.3
	 *
	 * @param Store $store
	 * @param Cache $cache
	 */
	public function __construct( Store $store, Cache $cache ) {
		$this->store = $store;
		$this->cache = $cache;

		$this->cacheTTL = 60 * 60 * 24 * 7;
	}

	/**
	 * @since 3.0
	 *
	 * @param ChangePropListener $changePropListener
	 */
	public function addListenersTo( ChangePropListener $changePropListener ) {

		// @see HierarchyLookup::getConsecutiveHierarchyList
		//
		// Remove the global hierarchy cache in the event that some entity was
		// annotated (or removed) with the `Subproperty of`/ `Subcategory of`
		// property, and while this purges the entire cache we ensure that the
		// hierarchy lookup is always correct without loosing too much sleep
		// over a more fine-grained caching strategy.

		$callback = function( $context ) {
			$this->cache->delete(
				smwfCacheKey( self::CACHE_NAMESPACE, [ self::TYPE_PROPERTY, $this->subpropertyDepth ] )
			);
		};

		$changePropListener->addListenerCallback( '_SUBP', $callback );

		$callback = function( $context ) {
			$this->cache->delete(
				smwfCacheKey( self::CACHE_NAMESPACE, [ self::TYPE_CATEGORY, $this->subcategoryDepth ] )
			);
		};

		$changePropListener->addListenerCallback( '_SUBC', $callback );
	}

	/**
	 * @since 2.3
	 *
	 * @param integer $subcategoryDepth
	 */
	public function setSubcategoryDepth( $subcategoryDepth ) {
		$this->subcategoryDepth = (int)$subcategoryDepth;
	}

	/**
	 * @since 2.3
	 *
	 * @param integer $subpropertyDepth
	 */
	public function setSubpropertyDepth( $subpropertyDepth ) {
		$this->subpropertyDepth = (int)$subpropertyDepth;
	}

	/**
	 * @since 2.3
	 *
	 * @param DIProperty $property
	 *
	 * @return boolean
	 */
	public function hasSubproperty( DIProperty $property ) {

		if ( $this->subpropertyDepth < 1 ) {
			return false;
		}

		$result = $this->getConsecutiveHierarchyList(
			$property
		);

		return $result !== [];
	}

	/**
	 * @since 2.3
	 *
	 * @param DIWikiPage $category
	 *
	 * @return boolean
	 */
	public function hasSubcategory( DIWikiPage $category ) {

		if ( $this->subcategoryDepth < 1 ) {
			return false;
		}

		$result = $this->getConsecutiveHierarchyList(
			$category
		);

		return $result !== [];
	}

	/**
	 * @since 2.3
	 *
	 * @param DIProperty $property
	 *
	 * @return DIWikiPage[]|[]
	 */
	public function findSubpropertyList( DIProperty $property ) {

		if ( $this->subpropertyDepth < 1 ) {
			return false;
		}

		return $this->lookup( '_SUBP', $property->getKey(), $property->getDiWikiPage(), new RequestOptions() );
	}

	/**
	 * @since 2.3
	 *
	 * @param DIWikiPage $category
	 *
	 * @return DIWikiPage[]|[]
	 */
	public function findSubcategoryList( DIWikiPage $category ) {

		if ( $this->subcategoryDepth < 1 ) {
			return [];
		}

		return $this->lookup( '_SUBC', $category->getDBKey(), $category, new RequestOptions() );
	}

	/**
	 * @since 3.0
	 *
	 * @param DIProperty|DIWikiPage $id
	 *
	 * @return DIProperty[]|DIWikiPage[]|[]
	 */
	public function getConsecutiveHierarchyList( $id ) {

		$hierarchyType = null;

		if ( $id instanceof DIProperty ) {
			$hierarchyType = self::TYPE_PROPERTY;
		} elseif ( $id instanceof DIWikiPage && $id->getNamespace() === NS_CATEGORY ) {
			$hierarchyType = self::TYPE_CATEGORY;
		}

		if ( $hierarchyType === null ) {
			throw new InvalidArgumentException( 'No matchable hierarchy type, expected a property or category entity.' );
		}

		// Store elements of the hierarchy tree in one large cache slot
		// since we are unable to detect if or when a leaf is removed from within
		// a cached tree unless one stores child and parent in a secondary cache.
		//
		// On the assumption that hierarchy data are less frequently changed, using
		// a "global" cache should be sufficient to avoid constant DB lookups.
		//
		// Invalidation of the cache will occur on each _SUBP/_SUBC change event (see
		// ChangePropListener).
		$cacheKey = smwfCacheKey(
			self::CACHE_NAMESPACE,
			[
				$hierarchyType,
				( $hierarchyType === self::TYPE_PROPERTY ? $this->subpropertyDepth : $this->subcategoryDepth )
			]
		);

		$hierarchyCache = $this->cache->fetch( $cacheKey );
		$reqCacheUpdate = false;

		if ( $hierarchyCache === false ) {
			$hierarchyCache = [];
		}

		$hierarchyMembers = [];
		$key = $hierarchyType === self::TYPE_PROPERTY ? $id->getKey() : $id->getDBKey();

		if ( !isset( $hierarchyCache[$key] ) ) {
			$hierarchyCache[$key] = [];

			if ( $hierarchyType === self::TYPE_PROPERTY ) {
				$this->findSubproperties( $hierarchyMembers, $id, 1 );
			} else {
				$this->findSubcategories( $hierarchyMembers, $id, 1 );
			}

			$hierarchyList[$key] = $hierarchyMembers;

			// Store only the key to keep the cache size low
			foreach ( $hierarchyList[$key] as $k ) {
				if ( $hierarchyType === self::TYPE_PROPERTY ) {
					$hierarchyCache[$key][] = $k->getKey();
				} else {
					$hierarchyCache[$key][] = $k->getDBKey();
				}
			}

			$reqCacheUpdate = true;
		} else {
			$hierarchyList[$key] = [];

			foreach ( $hierarchyCache[$key] as $k ) {
				if ( $hierarchyType === self::TYPE_PROPERTY ) {
					$hierarchyList[$key][] = new DIProperty( $k );
				} else {
					$hierarchyList[$key][] = new DIWikiPage( $k, NS_CATEGORY );
				}
			}
		}

		if ( $reqCacheUpdate ) {
			$this->cache->save( $cacheKey, $hierarchyCache, $this->cacheTTL );
		}

		return $hierarchyList[$key];
	}

	private function findSubproperties( &$hierarchyMembers, DIProperty $property, $depth ) {

		if ( $depth++ > $this->subpropertyDepth ) {
			return;
		}

		$propertyList = $this->findSubpropertyList(
			$property
		);

		if ( $propertyList === null || $propertyList === [] ) {
			return;
		}

		foreach ( $propertyList as $property ) {
			$property = DIProperty::newFromUserLabel(
				$property->getDBKey()
			);

			$hierarchyMembers[] = $property;
			$this->findSubproperties( $hierarchyMembers, $property, $depth );
		}
	}

	private function findSubcategories( &$hierarchyMembers, DIWikiPage $category, $depth ) {

		if ( $depth++ > $this->subcategoryDepth ) {
			return;
		}

		$categoryList = $this->findSubcategoryList(
			$category
		);

		foreach ( $categoryList as $category ) {
			$hierarchyMembers[] = $category;
			$this->findSubcategories( $hierarchyMembers, $category, $depth );
		}
	}

	private function lookup( $id, $key, DIWikiPage $subject, $requestOptions ) {

		$key = $id . '#' . $key . '#' . md5( $requestOptions->getHash() );

		if ( isset( $this->inMemoryCache[$key] ) ) {
			return $this->inMemoryCache[$key];
		}

		$res = $this->store->getPropertySubjects(
			new DIProperty( $id ),
			$subject,
			$requestOptions
		);

		$this->inMemoryCache[$key] = $res;

		$context = [
			'method' => __METHOD__,
			'role' => 'user',
			'id' => $id,
			'origin' => $subject
		];

		$this->logger->info( "[HierarchyLookup] Lookup: {id}, {origin}", $context );

		return $res;
	}

}