summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/SQLStore/Lookup/PropertyLabelSimilarityLookup.php
blob: 16bef59421d96824ec00d53506192652ed938756 (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
<?php

namespace SMW\SQLStore\Lookup;

use Exception;
use SMW\ApplicationFactory;
use SMW\DataValueFactory;
use SMW\DIProperty;
use SMW\PropertySpecificationLookup;
use SMW\RequestOptions;
use SMW\SQLStore\SQLStore;
use SMW\Store;

/**
 * @license GNU GPL v2+
 * @since 2.5
 *
 * @author mwjames
 */
class PropertyLabelSimilarityLookup {

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

	/**
	 * @var PropertySpecificationLookup
	 */
	private $propertySpecificationLookup;

	/**
	 * @var integer/float
	 */
	private $threshold = 50;

	/**
	 * @var DIProperty|null
	 */
	private $exemptionProperty;

	/**
	 * @var integer
	 */
	private $lookupCount = 0;

	/**
	 * @since 2.5
	 *
	 * @param Store $store
	 * @param PropertySpecificationLookup|null $propertySpecificationLookup
	 */
	public function __construct( Store $store, PropertySpecificationLookup $propertySpecificationLookup = null ) {
		$this->store = $store;
		$this->propertySpecificationLookup = $propertySpecificationLookup;

		if ( $this->propertySpecificationLookup === null ) {
			$this->propertySpecificationLookup = ApplicationFactory::getInstance()->getPropertySpecificationLookup();
		}
	}

	/**
	 * @since 2.5
	 *
	 * @param integer $threshold
	 *
	 * @return boolean
	 */
	public function setThreshold( $threshold ) {
		$this->threshold = $threshold;
	}

	/**
	 * @note A property that when annotated as part of a property specification
	 * will be used as exemption marker during the similarity comparison.
	 *
	 * @since 2.5
	 *
	 * @param string $exemptionProperty
	 */
	public function setExemptionProperty( $exemptionProperty ) {

		if ( $exemptionProperty === '' ) {
			return;
		}

		$this->exemptionProperty = DataValueFactory::getInstance()->newPropertyValueByLabel( $exemptionProperty )->getDataItem();
	}

	/**
	 * @since 2.5
	 *
	 * @return DIProperty|null
	 */
	public function getExemptionProperty() {
		return $this->exemptionProperty;
	}

	/**
	 * @since 2.5
	 *
	 * @return integer
	 */
	public function getLookupCount() {
		return $this->lookupCount;
	}

	/**
	 * @since 3.0
	 *
	 * @return integer
	 */
	public function getPropertyMaxCount() {
		$statistics = $this->store->getStatistics();

		if ( isset( $statistics['TOTALPROPS'] ) ) {
			return $statistics['TOTALPROPS'];
		}

		return 0;
	}

	/**
	 * @since 2.5
	 *
	 * @param RequestOptions|null $requestOptions
	 *
	 * @return array
	 */
	public function compareAndFindLabels( RequestOptions $requestOptions = null ) {

		$withType = false;
		$propertyList = $this->getPropertyList( $requestOptions );

		if ( $requestOptions !== null ) {
			foreach ( $requestOptions->getExtraConditions() as $extraCondition ) {
				if ( isset( $extraCondition['type'] ) ) {
					$withType = $extraCondition['type'];
				}
			}
		}

		$this->lookupCount = count( $propertyList );
		$similarities = $this->matchLabels( $propertyList, $withType );

		usort( $similarities, function ( $a, $b ) {
			return $a['similarity'] < $b['similarity'];
		} );

		return $similarities;
	}

	private function matchLabels( $propertyList, $withType ) {

		$similarities = [];
		$lookupComplete = [];

		foreach ( $propertyList as $first ) {

			if ( !$first->isUserDefined() ) {
				continue;
			}

			foreach ( $propertyList as $second ) {

				// Was already completed when used as first element
				if ( isset( $lookupComplete[$second->getKey()] ) ) {
					continue;
				}

				if ( $first->getKey() === $second->getKey() || !$second->isUserDefined() ) {
					continue;
				}

				$hash = $this->getHash( $first, $second );

				if ( $this->isExempted( $first, $second ) || isset( $similarities[$hash] ) ) {
					continue;
				}

				$percent = '';

				similar_text( $first->getLabel(), $second->getLabel(), $percent );

				if ( $percent >= $this->threshold ) {
					$similarities[$hash] = $this->getSummary( $first, $second, $percent, $withType );
				}
			}

			$lookupComplete[$first->getKey()] = true;
		}

		return $similarities;
	}

	/**
	 * @since 2.5
	 *
	 * @param  DIProperty $first
	 * @param  DIProperty $second
	 *
	 * @return boolean
	 */
	private function isExempted( DIProperty $first, DIProperty $second ) {

		if ( $this->exemptionProperty === null ) {
			return false;
		}

		$definedBy = $this->propertySpecificationLookup->getSpecification(
			$first,
			$this->exemptionProperty
		);

		foreach ( $definedBy as $dataItem ) {
			if ( $dataItem->equals( $second->getCanonicalDiWikiPage() ) ) {
				return true;
			}
		}

		$definedBy = $this->propertySpecificationLookup->getSpecification(
			$second,
			$this->exemptionProperty
		);

		foreach ( $definedBy as $dataItem ) {
			if ( $dataItem->equals( $first->getCanonicalDiWikiPage() ) ) {
				return true;
			}
		}

		return false;
	}

	private function getHash( DIProperty $first, DIProperty $second ) {

		$hashing = [];
		$hashing[] = $first->getKey();
		$hashing[] = $second->getKey();

		sort( $hashing );

		return md5( implode( '', $hashing ) );
	}

	private function getSummary( DIProperty $first, DIProperty $second, $percent, $withType ) {

		$summary = [];

		if ( $withType ) {
			$summary[] = [
				'label' => $first->getLabel(),
				'type'  => $first->findPropertyTypeID()
			];
		} else {
			$summary[] = $first->getLabel();
		}

		if ( $withType ) {
			$summary[] = [
				'label' => $second->getLabel(),
				'type'  => $second->findPropertyTypeID()
			];
		} else {
			$summary[] = $second->getLabel();
		}

		return [
			'property'   => $summary,
			'similarity' => round( $percent, 2 )
		];
	}

	private function getPropertyList( RequestOptions $requestOptions = null ) {

		$propertyList = [];

		// the query needs to do the filtering of internal properties, else LIMIT is wrong
		$options = [ 'ORDER BY' => 'smw_sort' ];

		$conditions = [
			'smw_namespace' => SMW_NS_PROPERTY,
			'smw_iw' => '',
			'smw_subobject' => ''
		];

		if ( $requestOptions !== null && $requestOptions->getLimit() > 0 ) {
			$options['LIMIT'] = $requestOptions->getLimit();
			$options['OFFSET'] = max( $requestOptions->getOffset(), 0 );
		}

		if ( $requestOptions !== null && $requestOptions->getStringConditions() ) {
			$conditions[] = $this->store->getSQLConditions( $requestOptions, '', 'smw_sortkey', false );
		}

		$connection = $this->store->getConnection( 'mw.db' );

		$res = $connection->select(
			SQLStore::ID_TABLE,
			[ 'smw_id', 'smw_title' ],
			$conditions,
			__METHOD__,
			$options
		);

		foreach ( $res as $row ) {

			try {
				$propertyList[] = new DIProperty( str_replace( ' ', '_', $row->smw_title ) );
			} catch ( Exception $e ) {
				// Do nothing ...
			}
		}

		return $propertyList;
	}

}