r76957 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r76956‎ | r76957 | r76958 >
Date:20:34, 18 November 2010
Author:ialex
Status:ok
Tags:
Comment:
svn:eol-style native
Modified paths:
  • /trunk/extensions/DonationInterface/payflowpro_gateway/forms/TwoStepTwoColumnLetter3.php (modified) (history)
  • /trunk/extensions/DonationInterface/payflowpro_gateway/forms/TwoStepTwoColumnLetterCA.php (modified) (history)
  • /trunk/extensions/DonationInterface/payflowpro_gateway/forms/css/TwoStepTwoColumnLetter3.css (modified) (history)
  • /trunk/extensions/DonationInterface/payflowpro_gateway/includes/provinceAbbreviations.inc (modified) (history)
  • /trunk/extensions/SemanticNotifyMe/includes/SMW_NotifyProcessor.smw15.php (modified) (history)
  • /trunk/extensions/SemanticNotifyMe/includes/storage/SMW_SQLStore2_QueriesNM.smw15.php (modified) (history)

Diff [purge]

Property changes on: trunk/extensions/DonationInterface/payflowpro_gateway/forms/TwoStepTwoColumnLetterCA.php
___________________________________________________________________
Added: svn:eol-style
11 + native
Property changes on: trunk/extensions/DonationInterface/payflowpro_gateway/forms/css/TwoStepTwoColumnLetter3.css
___________________________________________________________________
Added: svn:eol-style
22 + native
Property changes on: trunk/extensions/DonationInterface/payflowpro_gateway/forms/TwoStepTwoColumnLetter3.php
___________________________________________________________________
Added: svn:eol-style
33 + native
Property changes on: trunk/extensions/DonationInterface/payflowpro_gateway/includes/provinceAbbreviations.inc
___________________________________________________________________
Added: svn:eol-style
44 + native
Index: trunk/extensions/SemanticNotifyMe/includes/SMW_NotifyProcessor.smw15.php
@@ -1,1698 +1,1698 @@
2 -<?php
3 -/**
4 - * This file contains a static class for accessing functions to generate and execute
5 - * notify me semantic queries and to serialise their results.
6 - *
7 - * @author ning
8 - */
9 -if ( !defined( 'MEDIAWIKI' ) ) {
10 - exit( 1 );
11 -}
12 -
13 -global $smwgIP, $smwgNMIP ;
14 -require_once( $smwgIP . '/includes/storage/SMW_Store.php' );
15 -require_once( $smwgNMIP . '/includes/SMW_NMStorage.php' );
16 -
17 -/**
18 - * Static class for accessing functions to generate and execute semantic queries
19 - * and to serialise their results.
20 - */
21 -class SMWNotifyProcessor {
22 -
23 - static public function getNotifications() {
24 - $sStore = NMStorage::getDatabase();
25 - global $wgUser;
26 - $user_id = $wgUser->getId();
27 -
28 - $notifications = $sStore->getNotifications( $user_id );
29 -
30 - return $notifications;
31 - }
32 -
33 - /**
34 - * Enable a NotifyMe with specified id and querystring
35 - *
36 - * used for inline query only
37 - */
38 - static public function enableNotify( $notify_id, $querystring, &$msg = NULL ) {
39 - wfProfileIn( 'SMWNotifyProcessor::enableNotify (SMW)' );
40 -
41 - $sStore = NMStorage::getDatabase();
42 - global $smwgQDefaultNamespaces;
43 -
44 - SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $querystring ), $querystring, $params, $printouts );
45 - $relatedArticles = array();
46 - foreach ( $printouts as $po ) {
47 - $printoutArticles[] = array(
48 - 'namespace' => SMW_NS_PROPERTY,
49 - 'title' => Title::makeTitle( SMW_NS_PROPERTY, $po->getText( SMW_OUTPUT_WIKI ) )->getDBkey() );
50 - }
51 -
52 - $qp = new SMWNotifyParser( $notify_id, $printoutArticles );
53 - $qp->setDefaultNamespaces( $smwgQDefaultNamespaces );
54 - $desc = $qp->getQueryDescription( $querystring );
55 -
56 - if ( !$qp->m_result ) {
57 - $qp->m_errors[] = wfMsg( 'smw_nm_proc_pagenotexist' );
58 - }
59 -
60 - if ( isset( $msg ) && $qp->hasSubquery() ) {
61 - $msg .= "\n" . wfMsg( 'smw_nm_proc_subqueryhint' );
62 - }
63 -
64 - $query = new SMWQuery( $desc, true, false );
65 - $query->setQueryString( $querystring );
66 - $query->addErrors( $qp->getErrors() ); // keep parsing errors for later output
67 -
68 - $res = $sStore->getNMQueryResult( $query );
69 -
70 - if ( count( $query->getErrors() ) > 0 ) {
71 - if ( isset( $msg ) ) {
72 - $msg .= "\n\n" . implode( '\n', $query->getErrors() ) . "\n\n" . wfMsg( 'smw_nm_proc_enablehint' );
73 - }
74 - $sStore->disableNotifyState( $notify_id );
75 - wfProfileOut( 'SMWNotifyProcessor::enableNotify (SMW)' );
76 - return false;
77 - }
78 -
79 - $sStore->updateNMSql( $notify_id, $res['sql'], $res['tmp_hierarchy'] );
80 - if ( count( $res['page_ids'] ) > 0 ) {
81 - $add_monitor = array();
82 - foreach ( $res['page_ids'] as $page_id ) {
83 - $add_monitor[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
84 - }
85 - $sStore->addNotifyMonitor( $add_monitor );
86 - }
87 - $sStore->updateNotifyState( $notify_id, 1 );
88 - wfProfileOut( 'SMWNotifyProcessor::enableNotify (SMW)' );
89 -
90 - return true;
91 - }
92 -
93 - static public function getQueryRawParams( $querystring ) {
94 - // read query with printouts and (possibly) other parameters like sort, order, limit, etc...
95 - $pos = strpos( $querystring, "|?" );
96 - if ( $pos > 0 ) {
97 - $rawparams[] = trim( substr( $querystring, 0, $pos ) );
98 - $ps = explode( "|?", trim( substr( $querystring, $pos + 2 ) ) );
99 - foreach ( $ps as $param ) {
100 - $rawparams[] = "?" . trim( $param );
101 - }
102 - } else {
103 - $ps = preg_split( '/[^\|]{1}\|{1}(?!\|)/s', $querystring );
104 - if ( count( $ps ) > 1 ) {
105 - // last char of query condition is missing (matched with [^\|]{1}) therefore copy from original
106 - $rawparams[] = trim( substr( $querystring, 0, strlen( $ps[0] ) + 1 ) );
107 - array_shift( $ps ); // remove the query condition
108 - // add other params for formating etc.
109 - foreach ( $ps as $param )
110 - $rawparams[] = trim( $param );
111 - } // no single pipe found, no params specified in query
112 - else $rawparams[] = trim( $querystring );
113 - }
114 - $rawparams[] = "format=table";
115 - $rawparams[] = "link=all";
116 - return $rawparams;
117 - }
118 -
119 - static public function addNotify( $rawquery, $name, $rep_all, $show_all, $delegate ) {
120 - global $wgTitle;
121 - // Take care at least of some templates -- for better template support use #ask
122 - $parser = new Parser();
123 - $parserOptions = new ParserOptions();
124 - $parser->startExternalParse( $wgTitle, $parserOptions, OT_HTML );
125 - $rawquery = $parser->transformMsg( $rawquery, $parserOptions );
126 -
127 - wfProfileIn( 'SMWNotifyProcessor::createNotify (SMW)' );
128 - $sStore = NMStorage::getDatabase();
129 - global $wgUser;
130 - $user_id = $wgUser->getId();
131 - if ( $user_id == 0 ) {
132 - wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
133 - return wfMsg( 'smw_nm_proc_notlogin' );
134 - }
135 -
136 - // check notify query first, use QueryParser from SMW
137 - SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $rawquery ), $querystring, $params, $printouts );
138 -
139 - $qp = new SMWQueryParser();
140 - $qp->setDefaultNamespaces( $smwgQDefaultNamespaces );
141 - $desc = $qp->getQueryDescription( $querystring );
142 -
143 - if ( count( $qp->getErrors() ) > 0 ) {
144 - wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
145 - return wfMsg( 'smw_nm_proc_createfail', implode( "\n", $qp->getErrors() ) );
146 - }
147 -
148 - $notify_id = $sStore->addNotifyQuery( $user_id, $rawquery, $name, $rep_all, $show_all, $delegate );
149 - if ( $notify_id == 0 ) {
150 - wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
151 - return wfMsg( 'smw_nm_proc_savefail' );
152 - }
153 - wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
154 -
155 - wfProfileIn( 'SMWNotifyProcessor::enableNotify (SMW)' );
156 - $msg = '';
157 - $result = SMWNotifyProcessor::enableNotify( $notify_id, $rawquery, $msg );
158 - wfProfileOut( 'SMWNotifyProcessor::enableNotify (SMW)' );
159 - return "1" . ( $result ? "1":"0" ) . "$notify_id,$msg";
160 - }
161 -
162 - static public function updateStates( $notify_ids ) {
163 - wfProfileIn( 'SMWNotifyProcessor::updateStates (SMW)' );
164 -
165 - $notifications = SMWNotifyProcessor::getNotifications();
166 - if ( $notifications == null || !is_array( $notifications ) ) {
167 - return wfMsg( 'smw_nm_proc_nonoti' );
168 - }
169 - $result = true;
170 - $idx = 0;
171 - $count = count( $notify_ids ) - 1;
172 - $msg = '';
173 - $errs = '';
174 - $sStore = NMStorage::getDatabase();
175 - foreach ( $notifications as $row ) {
176 - if ( ( $idx < $count ) && ( $notify_ids[$idx] == $row['notify_id'] ) ) {
177 - if ( $row['enable'] == 0 ) {
178 - $m = '';
179 - $r = SMWNotifyProcessor::enableNotify( $row['notify_id'], $row['query'], $m );
180 - if ( !$r ) {
181 - $msg .= "NotifyMe : '" . $row['name'] . "'$m\n\n";
182 - $errs .= $row['notify_id'] . ",";
183 - $result = false;
184 - }
185 - }
186 - $idx ++;
187 - } else {
188 - if ( $row['enable'] == 1 ) {
189 - $result = $sStore->disableNotifyState( $row['notify_id'] );
190 - }
191 - }
192 - }
193 -
194 - wfProfileOut( 'SMWNotifyProcessor::updateStates (SMW)' );
195 - return $result ? wfMsg( 'smw_nm_proc_statesucc' ) : "0$errs|\n\n$msg";
196 - }
197 -
198 - static public function updateDelegates( $delegates ) {
199 - wfProfileIn( 'SMWNotifyProcessor::updateDelegates (SMW)' );
200 -
201 - $notifications = SMWNotifyProcessor::getNotifications();
202 - if ( $notifications == null || !is_array( $notifications ) ) {
203 - return wfMsg( 'smw_nm_proc_nonoti' );
204 - }
205 - $result = true;
206 - $idx = 0;
207 - $s = explode( ':', $delegates[$idx], 2 );
208 - $count = count( $delegates ) - 1;
209 - $sStore = NMStorage::getDatabase();
210 - foreach ( $notifications as $row ) {
211 - if ( ( $idx < $count ) && ( $s[0] == $row['notify_id'] ) ) {
212 - $result = $sStore->updateDelegate( $row['notify_id'], $s[1] );
213 - $idx ++;
214 - $s = explode( ':', $delegates[$idx], 2 );
215 - } else {
216 - $result = $sStore->updateDelegate( $row['notify_id'], '' );
217 - }
218 - if ( !$result ) break;
219 - }
220 -
221 - wfProfileOut( 'SMWNotifyProcessor::updateDelegates (SMW)' );
222 - return $result ? wfMsg( 'smw_nm_proc_delegatesucc' ) : wfMsg( 'smw_nm_proc_delegateerr' );
223 - }
224 -
225 - static public function refreshNotifyMe() {
226 - wfProfileIn( 'SMWNotifyProcessor::refreshNotifyMe (SMW)' );
227 - NMStorage::getDatabase()->cleanUp();
228 - $notifications = NMStorage::getDatabase()->getAllNotifications();
229 - foreach ( $notifications as $row ) {
230 - if ( $row['enable'] ) {
231 - $result = SMWNotifyProcessor::enableNotify( $row['notify_id'], $row['query'] );
232 - }
233 - }
234 - wfProfileOut( 'SMWNotifyProcessor::refreshNotifyMe (SMW)' );
235 - }
236 -
237 - static public function updateReportAll( $notify_ids ) {
238 - wfProfileIn( 'SMWNotifyProcessor::updateReportAlls (SMW)' );
239 -
240 - $notifications = SMWNotifyProcessor::getNotifications();
241 - if ( $notifications == null || !is_array( $notifications ) ) {
242 - return wfMsg( 'smw_nm_proc_nonoti' );
243 - }
244 - $result = true;
245 - $idx = 0;
246 - $count = count( $notify_ids ) - 1;
247 - $sStore = NMStorage::getDatabase();
248 - foreach ( $notifications as $row ) {
249 - if ( ( $idx < $count ) && ( $notify_ids[$idx] == $row['notify_id'] ) ) {
250 - if ( $row['rep_all'] == 0 ) {
251 - $result = $sStore->updateNotifyReportAll( $row['notify_id'], 1 );
252 - }
253 - $idx ++;
254 - } else {
255 - if ( $row['rep_all'] == 1 ) {
256 - $result = $sStore->updateNotifyReportAll( $row['notify_id'], 0 );
257 - }
258 - }
259 - if ( !$result ) break;
260 - }
261 -
262 - wfProfileOut( 'SMWNotifyProcessor::updateStates (SMW)' );
263 - return $result ? wfMsg( 'smw_nm_proc_reportsucc' ) : wfMsg( 'smw_nm_proc_reporterr' );
264 - }
265 -
266 - static public function updateShowAll( $notify_ids ) {
267 - wfProfileIn( 'SMWNotifyProcessor::updateShowAlls (SMW)' );
268 -
269 - $notifications = SMWNotifyProcessor::getNotifications();
270 - if ( $notifications == null || !is_array( $notifications ) ) {
271 - return wfMsg( 'smw_nm_proc_nonoti' );
272 - }
273 - $result = true;
274 - $idx = 0;
275 - $count = count( $notify_ids ) - 1;
276 - $sStore = NMStorage::getDatabase();
277 - foreach ( $notifications as $row ) {
278 - if ( ( $idx < $count ) && ( $notify_ids[$idx] == $row['notify_id'] ) ) {
279 - if ( $row['show_all'] == 0 ) {
280 - $result = $sStore->updateNotifyShowAll( $row['notify_id'], 1 );
281 - }
282 - $idx ++;
283 - } else {
284 - if ( $row['show_all'] == 1 ) {
285 - $result = $sStore->updateNotifyShowAll( $row['notify_id'], 0 );
286 - }
287 - }
288 - if ( !$result ) break;
289 - }
290 -
291 - wfProfileOut( 'SMWNotifyProcessor::updateStates (SMW)' );
292 - return $result ? wfMsg( 'smw_nm_proc_showsucc' ) : wfMsg( 'smw_nm_proc_showerr' );
293 - }
294 -
295 - static public function delNotify( $notify_ids ) {
296 - wfProfileIn( 'SMWNotifyProcessor::delNotify (SMW)' );
297 - $sStore = NMStorage::getDatabase();
298 - $result = $sStore->removeNotifyQuery( $notify_ids );
299 - wfProfileOut( 'SMWNotifyProcessor::delNotify (SMW)' );
300 - return $result ? wfMsg( 'smw_nm_proc_delsucc' ) : wfMsg( 'smw_nm_proc_delerr' );
301 - }
302 -
303 - static protected $notifyJobs = array();
304 - static public function prepareArticleSave( $title ) {
305 - $page_id = $title->getArticleID();
306 - if ( $page_id == 0 ) {
307 - return;
308 - }
309 - $updates = SMWNotifyProcessor::$notifyJobs[$page_id];
310 - if ( empty( $updates ) ) {
311 - SMWNotifyProcessor::$notifyJobs[$page_id] = new SMWNotifyUpdate( $title );
312 - }
313 - }
314 - static public function articleSavedComplete( $title ) {
315 - $page_id = $title->getArticleID();
316 - if ( $page_id == 0 ) {
317 - return;
318 - }
319 - $updates = SMWNotifyProcessor::$notifyJobs[$page_id];
320 - if ( empty( $updates ) ) {
321 - SMWNotifyProcessor::$notifyJobs[$page_id] = new SMWNotifyUpdate( $title );
322 - $updates = SMWNotifyProcessor::$notifyJobs[$page_id];
323 - } else {
324 - $updates->executeNotifyUpdate();
325 - }
326 - $updates->updateNotifyMonitor();
327 - $updates->notifyUsers();
328 - unset( SMWNotifyProcessor::$notifyJobs[$page_id] );
329 - }
330 - static public function articleDelete( $title, $reason ) {
331 - $page_id = $title->getArticleID();
332 - if ( $page_id == 0 ) {
333 - return;
334 - }
335 - $updates = new SMWNotifyUpdate( $title );
336 - $updates->executeNotifyDelete( $reason );
337 - }
338 - static public function toInfoId( $type, $subquery, $attr_id ) {
339 - return base_convert( strval( ( $subquery << 8 ) | $type ), 10, 9 ) . '9' . $attr_id;
340 - }
341 - static public function getInfoFromId( $id ) {
342 - $idx = strpos( $id, '9' );
343 - $t = intval( base_convert( substr( $id, 0, $idx ), 9, 10 ) );
344 - return array(
345 - 'type' => $t&0xFF,
346 - 'subquery' => $t >> 8,
347 - 'attr_id' => intval( substr( $id, $idx + 1 ) )
348 - );
349 - }
350 -
351 -}
352 -
353 -// based on SMW_QueryProcessor.php (v 1.4.2)
354 -/**
355 - * Objects of this class are in charge of parsing a query string in order
356 - * to create an SMWDescription. The class and methods are not static in order
357 - * to more cleanly store the intermediate state and progress of the parser.
358 - */
359 -class SMWNotifyParser {
360 -
361 - protected $m_sepstack; // list of open blocks ("parentheses") that need closing at current step
362 - protected $m_curstring; // remaining string to be parsed (parsing eats query string from the front)
363 - var $m_errors; // empty array if all went right, array of strings otherwise
364 - protected $m_label; // label of the main query result
365 - protected $m_defaultns; // description of the default namespace restriction, or NULL if not used
366 -
367 - protected $m_categoryprefix; // cache label of category namespace . ':'
368 - protected $m_conceptprefix; // cache label of concept namespace . ':'
369 - protected $m_queryfeatures; // query features to be supported, format similar to $smwgQFeatures
370 -
371 - // added by ning
372 - protected $m_notify_id;
373 - protected $m_subquery;
374 - protected $m_printoutArticles;
375 - public $m_result;
376 -
377 - // modified by ning
378 - public function SMWNotifyParser( $notify_id, $printoutArticles, $queryfeatures = false ) {
379 - $this->m_notify_id = $notify_id;
380 - $this->m_printoutArticles = $printoutArticles;
381 - $this->m_result = true;
382 -
383 - global $wgContLang, $smwgQFeatures;
384 - $this->m_categoryprefix = $wgContLang->getNsText( NS_CATEGORY ) . ':';
385 - $this->m_conceptprefix = $wgContLang->getNsText( SMW_NS_CONCEPT ) . ':';
386 - $this->m_defaultns = NULL;
387 - $this->m_queryfeatures = $queryfeatures === false ? $smwgQFeatures:$queryfeatures;
388 - }
389 -
390 - // added by ning
391 - public function hasSubquery() {
392 - return $this->m_subquery > 1;
393 - }
394 -
395 - /**
396 - * Provide an array of namespace constants that are used as default restrictions.
397 - * If NULL is given, no such default restrictions will be added (faster).
398 - */
399 - public function setDefaultNamespaces( $nsarray ) {
400 - $this->m_defaultns = NULL;
401 - if ( $nsarray !== NULL ) {
402 - foreach ( $nsarray as $ns ) {
403 - $this->m_defaultns = $this->addDescription( $this->m_defaultns, new SMWNamespaceDescription( $ns ), false );
404 - }
405 - }
406 - }
407 -
408 - /**
409 - * Compute an SMWDescription from a query string. Returns whatever descriptions could be
410 - * wrestled from the given string (the most general result being SMWThingDescription if
411 - * no meaningful condition was extracted).
412 - */
413 - public function getQueryDescription( $querystring ) {
414 - wfProfileIn( 'SMWNotifyParser::getQueryDescription (SMW)' );
415 - $this->m_errors = array();
416 - $this->m_label = '';
417 - $this->m_curstring = $querystring;
418 - $this->m_sepstack = array();
419 - $setNS = false;
420 -
421 - // added by ning
422 - $this->m_subquery = 0;
423 -
424 - $result = $this->getSubqueryDescription( $setNS, $this->m_label );
425 - if ( !$setNS ) { // add default namespaces if applicable
426 - $result = $this->addDescription( $this->m_defaultns, $result );
427 - }
428 - if ( $result === NULL ) { // parsing went wrong, no default namespaces
429 - $result = new SMWThingDescription();
430 - }
431 - wfProfileOut( 'SMWNotifyParser::getQueryDescription (SMW)' );
432 - return $result;
433 - }
434 -
435 - /**
436 - * Return array of error messages (possibly empty).
437 - */
438 - public function getErrors() {
439 - return $this->m_errors;
440 - }
441 -
442 - /**
443 - * Return error message or empty string if no error occurred.
444 - */
445 - public function getErrorString() {
446 - return smwfEncodeMessages( $this->m_errors );
447 - }
448 -
449 - /**
450 - * Return label for the results of this query (which
451 - * might be empty if no such information was passed).
452 - */
453 - public function getLabel() {
454 - return $this->m_label;
455 - }
456 -
457 -
458 - /**
459 - * Compute an SMWDescription for current part of a query, which should
460 - * be a standalone query (the main query or a subquery enclosed within
461 - * "\<q\>...\</q\>". Recursively calls similar methods and returns NULL upon error.
462 - *
463 - * The call-by-ref parameter $setNS is a boolean. Its input specifies whether
464 - * the query should set the current default namespace if no namespace restrictions
465 - * were given. If false, the calling super-query is happy to set the required
466 - * NS-restrictions by itself if needed. Otherwise the subquery has to impose the defaults.
467 - * This is so, since outermost queries and subqueries of disjunctions will have to set
468 - * their own default restrictions.
469 - *
470 - * The return value of $setNS specifies whether or not the subquery has a namespace
471 - * specification in place. This might happen automatically if the query string imposes
472 - * such restrictions. The return value is important for those callers that otherwise
473 - * set up their own restrictions.
474 - *
475 - * Note that $setNS is no means to switch on or off default namespaces in general,
476 - * but just controls query generation. For general effect, the default namespaces
477 - * should be set to NULL.
478 - *
479 - * The call-by-ref parameter $label is used to append any label strings found.
480 - */
481 - protected function getSubqueryDescription( &$setNS, &$label ) {
482 - global $smwgQPrintoutLimit;
483 - wfLoadExtensionMessages( 'SemanticMediaWiki' );
484 - $conjunction = NULL; // used for the current inner conjunction
485 - $disjuncts = array(); // (disjunctive) array of subquery conjunctions
486 - $printrequests = array(); // the printrequests found for this query level
487 - $hasNamespaces = false; // does the current $conjnuction have its own namespace restrictions?
488 - $mustSetNS = $setNS; // must ns restrictions be set? (may become true even if $setNS is false)
489 -
490 - // added by ning
491 - $subquery = $this->m_subquery;
492 - if ( $subquery == 0 ) {
493 - $relatedArticles = $this->m_printoutArticles;
494 - } else {
495 - $relatedArticles = array();
496 - }
497 - $this->m_subquery ++;
498 -
499 - $continue = ( $chunk = $this->readChunk() ) != ''; // skip empty subquery completely, thorwing an error
500 - while ( $continue ) {
501 - $setsubNS = false;
502 - switch ( $chunk ) {
503 - case '[[': // start new link block
504 - // modified by ning
505 - $ld = $this->getLinkDescription( $setsubNS, $label, $relatedArticles );
506 -
507 - if ( $ld instanceof SMWPrintRequest ) {
508 - $printrequests[] = $ld;
509 - } elseif ( $ld instanceof SMWDescription ) {
510 - $conjunction = $this->addDescription( $conjunction, $ld );
511 - }
512 - break;
513 - case '<q>': // enter new subquery, currently irrelevant but possible
514 - $this->pushDelimiter( '</q>' );
515 - $conjunction = $this->addDescription( $conjunction, $this->getSubqueryDescription( $setsubNS, $label ) );
516 - // / TODO: print requests from subqueries currently are ignored, should be moved down
517 - break;
518 - case 'OR': case '||': case '': case '</q>': // finish disjunction and maybe subquery
519 - if ( $this->m_defaultns !== NULL ) { // possibly add namespace restrictions
520 - if ( $hasNamespaces && !$mustSetNS ) {
521 - // add ns restrictions to all earlier conjunctions (all of which did not have them yet)
522 - $mustSetNS = true; // enforce NS restrictions from now on
523 - $newdisjuncts = array();
524 - foreach ( $disjuncts as $conj ) {
525 - $newdisjuncts[] = $this->addDescription( $conj, $this->m_defaultns );
526 - }
527 - $disjuncts = $newdisjuncts;
528 - } elseif ( !$hasNamespaces && $mustSetNS ) {
529 - // add ns restriction to current result
530 - $conjunction = $this->addDescription( $conjunction, $this->m_defaultns );
531 - }
532 - }
533 - $disjuncts[] = $conjunction;
534 - // start anew
535 - $conjunction = NULL;
536 - $hasNamespaces = false;
537 - // finish subquery?
538 - if ( $chunk == '</q>' ) {
539 - if ( $this->popDelimiter( '</q>' ) ) {
540 - $continue = false; // leave the loop
541 - } else {
542 - $this->m_errors[] = wfMsgForContent( 'smw_toomanyclosing', $chunk );
543 - return NULL;
544 - }
545 - } elseif ( $chunk == '' ) {
546 - $continue = false;
547 - }
548 - break;
549 - case '+': // "... AND true" (ignore)
550 - break;
551 - default: // error: unexpected $chunk
552 - $this->m_errors[] = wfMsgForContent( 'smw_unexpectedpart', $chunk );
553 - // return NULL; // Try to go on, it can only get better ...
554 - }
555 - if ( $setsubNS ) { // namespace restrictions encountered in current conjunct
556 - $hasNamespaces = true;
557 - }
558 - if ( $continue ) { // read on only if $continue remained true
559 - $chunk = $this->readChunk();
560 - }
561 - }
562 -
563 - if ( count( $disjuncts ) > 0 ) { // make disjunctive result
564 - $result = NULL;
565 - foreach ( $disjuncts as $d ) {
566 - if ( $d === NULL ) {
567 - $this->m_errors[] = wfMsgForContent( 'smw_emptysubquery' );
568 - $setNS = false;
569 - return NULL;
570 - } else {
571 - $result = $this->addDescription( $result, $d, false );
572 - }
573 - }
574 - } else {
575 - $this->m_errors[] = wfMsgForContent( 'smw_emptysubquery' );
576 - $setNS = false;
577 - return NULL;
578 - }
579 - $setNS = $mustSetNS; // NOTE: also false if namespaces were given but no default NS descs are available
580 -
581 - $prcount = 0;
582 - foreach ( $printrequests as $pr ) { // add printrequests
583 - if ( $prcount < $smwgQPrintoutLimit ) {
584 - $result->addPrintRequest( $pr );
585 - $prcount++;
586 - } else {
587 - $this->m_errors[] = wfMsgForContent( 'smw_overprintoutlimit' );
588 - break;
589 - }
590 - }
591 -
592 - // added by ning
593 - if ( $this->m_result ) {
594 - $sStore = NMStorage::getDatabase();
595 - $this->m_result = $sStore->addNotifyRelations( $this->m_notify_id, $relatedArticles, $subquery );
596 - }
597 -
598 - return $result;
599 - }
600 -
601 - /**
602 - * Compute an SMWDescription for current part of a query, which should
603 - * be the content of "[[ ... ]]". Alternatively, if the current syntax
604 - * specifies a print request, return the print request object.
605 - * Returns NULL upon error.
606 - *
607 - * Parameters $setNS and $label have the same use as in getSubqueryDescription().
608 - */
609 - // modified by ning, add $relatedArticles
610 - protected function getLinkDescription( &$setNS, &$label, &$relatedArticles ) {
611 - // This method is called when we encountered an opening '[['. The following
612 - // block could be a Category-statement, fixed object, property statements,
613 - // or according print statements.
614 - $chunk = $this->readChunk( '', true, false ); // NOTE: untrimmed, initial " " escapes prop. chains
615 - if ( ( smwfNormalTitleText( $chunk ) == $this->m_categoryprefix ) || // category statement or
616 - ( smwfNormalTitleText( $chunk ) == $this->m_conceptprefix ) ) { // concept statement
617 - return $this->getClassDescription( $setNS, $label, $relatedArticles,
618 - ( smwfNormalTitleText( $chunk ) == $this->m_categoryprefix ) );
619 - } else { // fixed subject, namespace restriction, property query, or subquery
620 - $sep = $this->readChunk( '', false ); // do not consume hit, "look ahead"
621 - if ( ( $sep == '::' ) || ( $sep == ':=' ) ) {
622 - if ( $chunk { 0 } != ':' ) { // property statement
623 - return $this->getPropertyDescription( $chunk, $setNS, $label, $relatedArticles );
624 - } else { // escaped article description, read part after :: to get full contents
625 - $chunk .= $this->readChunk( '\[\[|\]\]|\|\||\|' );
626 - return $this->getArticleDescription( trim( $chunk ), $setNS, $label, $relatedArticles );
627 - }
628 - } else { // Fixed article/namespace restriction. $sep should be ]] or ||
629 - return $this->getArticleDescription( trim( $chunk ), $setNS, $label, $relatedArticles );
630 - }
631 - }
632 - }
633 -
634 - /**
635 - * Parse a category description (the part of an inline query that
636 - * is in between "[[Category:" and the closing "]]" and create a
637 - * suitable description.
638 - */
639 - // modified by ning ,add $relatedArticles
640 - protected function getClassDescription( &$setNS, &$label, &$relatedArticles, $category = true ) {
641 - global $smwgSMWBetaCompatible; // * printouts only for this old version
642 - // note: no subqueries allowed here, inline disjunction allowed, wildcards allowed
643 - $result = NULL;
644 - $continue = true;
645 - while ( $continue ) {
646 - $chunk = $this->readChunk();
647 - if ( $chunk == '+' ) {
648 - // wildcard, ignore for categories (semantically meaningless, everything is in some class)
649 - } elseif ( ( $chunk == '+' ) && $category && $smwgSMWBetaCompatible ) { // print statement
650 - $chunk = $this->readChunk( '\]\]|\|' );
651 - if ( $chunk == '|' ) {
652 - $printlabel = $this->readChunk( '\]\]' );
653 - if ( $printlabel != ']]' ) {
654 - $chunk = $this->readChunk( '\]\]' );
655 - } else {
656 - $printlabel = '';
657 - $chunk = ']]';
658 - }
659 - } else {
660 - global $wgContLang;
661 - $printlabel = $wgContLang->getNSText( NS_CATEGORY );
662 - }
663 - if ( $chunk == ']]' ) {
664 - return new SMWPrintRequest( SMWPrintRequest::PRINT_CATS, $printlabel );
665 - } else {
666 - $this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
667 - return NULL;
668 - }
669 - } else { // assume category/concept title
670 - // / NOTE: use m_c...prefix to prevent problems with, e.g., [[Category:Template:Test]]
671 - $class = Title::newFromText( ( $category ? $this->m_categoryprefix:$this->m_conceptprefix ) . $chunk );
672 - if ( $class !== NULL ) {
673 - $desc = $category ? new SMWClassDescription( $class ):new SMWConceptDescription( $class );
674 - $result = $this->addDescription( $result, $desc, false );
675 - }
676 -
677 - // added by ning
678 - if ( $category ) {
679 - $relatedArticles[] = array(
680 - 'namespace' => NS_CATEGORY,
681 - 'title' => $class->getDBkey() );
682 - }
683 -
684 - }
685 - $chunk = $this->readChunk();
686 - $continue = ( $chunk == '||' ) && $category; // disjunctions only for cateories
687 - }
688 -
689 - return $this->finishLinkDescription( $chunk, false, $result, $setNS, $label );
690 - }
691 -
692 - /**
693 - * Parse a property description (the part of an inline query that
694 - * is in between "[[Some property::" and the closing "]]" and create a
695 - * suitable description. The "::" is the first chunk on the current
696 - * string.
697 - */
698 - // modified by ning ,add $relatedArticles
699 - protected function getPropertyDescription( $propertyname, &$setNS, &$label, &$relatedArticles ) {
700 - global $smwgSMWBetaCompatible; // support for old * printouts of beta
701 - wfLoadExtensionMessages( 'SemanticMediaWiki' );
702 - $this->readChunk(); // consume separator ":=" or "::"
703 - // first process property chain syntax (e.g. "property1.property2::value"):
704 - if ( $propertyname { 0 } == ' ' ) { // escape
705 - $propertynames = array( $propertyname );
706 - } else {
707 - $propertynames = explode( '.', $propertyname );
708 - }
709 - $properties = array();
710 - $typeid = '_wpg';
711 - foreach ( $propertynames as $name ) {
712 - if ( $typeid != '_wpg' ) { // non-final property in chain was no wikipage: not allowed
713 - $this->m_errors[] = wfMsgForContent( 'smw_valuesubquery', $prevname );
714 - return NULL; // /TODO: read some more chunks and try to finish [[ ]]
715 - }
716 - $property = SMWPropertyValue::makeUserProperty( $name );
717 - if ( !$property->isValid() ) { // illegal property identifier
718 - $this->m_errors = array_merge( $this->m_errors, $property->getErrors() );
719 - return NULL; // /TODO: read some more chunks and try to finish [[ ]]
720 - }
721 - $typeid = $property->getTypeID();
722 - $prevname = $name;
723 - $properties[] = $property;
724 -
725 - // added by ning
726 - $relatedArticles[] = array(
727 - 'namespace' => SMW_NS_PROPERTY,
728 - 'title' => $property->getDBkey() );
729 -
730 - } // /NOTE: after iteration, $property and $typeid correspond to last value
731 -
732 - $innerdesc = NULL;
733 - $continue = true;
734 - while ( $continue ) {
735 - $chunk = $this->readChunk();
736 - switch ( $chunk ) {
737 - case '+': // wildcard, add namespaces for page-type properties
738 - if ( ( $this->m_defaultns !== NULL ) && ( $typeid == '_wpg' ) ) {
739 - $innerdesc = $this->addDescription( $innerdesc, $this->m_defaultns, false );
740 - } else {
741 - $innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
742 - }
743 - $chunk = $this->readChunk();
744 - break;
745 - case '<q>': // subquery, set default namespaces
746 - if ( $typeid == '_wpg' ) {
747 - $this->pushDelimiter( '</q>' );
748 - $setsubNS = true;
749 - $sublabel = '';
750 - $innerdesc = $this->addDescription( $innerdesc, $this->getSubqueryDescription( $setsubNS, $sublabel ), false );
751 - } else { // no subqueries allowed for non-pages
752 - $this->m_errors[] = wfMsgForContent( 'smw_valuesubquery', end( $propertynames ) );
753 - $innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
754 - }
755 - $chunk = $this->readChunk();
756 - break;
757 - default: // normal object value or print statement
758 - // read value(s), possibly with inner [[...]]
759 - $open = 1;
760 - $value = $chunk;
761 - $continue2 = true;
762 - // read value with inner [[, ]], ||
763 - while ( ( $open > 0 ) && ( $continue2 ) ) {
764 - $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
765 - switch ( $chunk ) {
766 - case '[[': // open new [[ ]]
767 - $open++;
768 - break;
769 - case ']]': // close [[ ]]
770 - $open--;
771 - break;
772 - case '|': case '||': // terminates only outermost [[ ]]
773 - if ( $open == 1 ) {
774 - $open = 0;
775 - }
776 - break;
777 - case '': // /TODO: report error; this is not good right now
778 - $continue2 = false;
779 - break;
780 - }
781 - if ( $open != 0 ) {
782 - $value .= $chunk;
783 - }
784 - } // /NOTE: at this point, we normally already read one more chunk behind the value
785 -
786 - if ( $typeid == '__nry' ) { // nary value
787 - $dv = SMWDataValueFactory::newPropertyObjectValue( $property );
788 - $dv->acceptQuerySyntax();
789 - $dv->setUserValue( $value );
790 - $vl = $dv->getValueList();
791 - $pm = $dv->getPrintModifier();
792 - if ( $vl !== NULL ) { // prefer conditions over print statements (only one possible right now)
793 - $innerdesc = $this->addDescription( $innerdesc, $vl, false );
794 - } elseif ( $pm !== false ) {
795 - if ( $chunk == '|' ) {
796 - $printlabel = $this->readChunk( '\]\]' );
797 - if ( $printlabel != ']]' ) {
798 - $chunk = $this->readChunk( '\]\]' );
799 - } else {
800 - $printlabel = '';
801 - $chunk = ']]';
802 - }
803 - } else {
804 - $printlabel = $property->getWikiValue();
805 - }
806 - if ( $chunk == ']]' ) {
807 - return new SMWPrintRequest( SMWPrintRequest::PRINT_PROP, $printlabel, $property, $pm );
808 - } else {
809 - $this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
810 - return NULL;
811 - }
812 - }
813 - } else { // unary value
814 - $comparator = SMW_CMP_EQ;
815 - $printmodifier = '';
816 - SMWNotifyParser::prepareValue( $value, $comparator, $printmodifier );
817 - if ( ( $value == '*' ) && $smwgSMWBetaCompatible ) {
818 - if ( $chunk == '|' ) {
819 - $printlabel = $this->readChunk( '\]\]' );
820 - if ( $printlabel != ']]' ) {
821 - $chunk = $this->readChunk( '\]\]' );
822 - } else {
823 - $printlabel = '';
824 - $chunk = ']]';
825 - }
826 - } else {
827 - $printlabel = $property->getWikiValue();
828 - }
829 - if ( $chunk == ']]' ) {
830 - return new SMWPrintRequest( SMWPrintRequest::PRINT_PROP, $printlabel, $property, $printmodifier );
831 - } else {
832 - $this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
833 - return NULL;
834 - }
835 - } else {
836 - $dv = SMWDataValueFactory::newPropertyObjectValue( $property, $value );
837 - if ( !$dv->isValid() ) {
838 - $this->m_errors = $this->m_errors + $dv->getErrors();
839 - $vd = new SMWThingDescription();
840 - } else {
841 - $vd = new SMWValueDescription( $dv, $comparator );
842 - }
843 - $innerdesc = $this->addDescription( $innerdesc, $vd, false );
844 - }
845 - }
846 - }
847 - $continue = ( $chunk == '||' );
848 - }
849 -
850 - if ( $innerdesc === NULL ) { // make a wildcard search
851 - if ( ( $this->m_defaultns !== NULL ) && ( $typeid == '_wpg' ) ) {
852 - $innerdesc = $this->addDescription( $innerdesc, $this->m_defaultns, false );
853 - } else {
854 - $innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
855 - }
856 - $this->m_errors[] = wfMsgForContent( 'smw_propvalueproblem', $property->getWikiValue() );
857 - }
858 - $properties = array_reverse( $properties );
859 - foreach ( $properties as $property ) {
860 - $innerdesc = new SMWSomeProperty( $property, $innerdesc );
861 - }
862 - $result = $innerdesc;
863 - return $this->finishLinkDescription( $chunk, false, $result, $setNS, $label );
864 - }
865 -
866 -
867 - /**
868 - * Prepare a single value string, possibly extracting comparators and
869 - * printmodifier. $value is changed to consist only of the remaining
870 - * effective value string, or of "*" for print statements.
871 - */
872 - static public function prepareValue( &$value, &$comparator, &$printmodifier ) {
873 - global $smwgQComparators, $smwgSMWBetaCompatible; // support for old * printouts of beta
874 - // get print modifier behind *
875 - if ( $smwgSMWBetaCompatible ) {
876 - $list = preg_split( '/^\*/', $value, 2 );
877 - if ( count( $list ) == 2 ) { // hit
878 - $value = '*';
879 - $printmodifier = $list[1];
880 - } else {
881 - $printmodifier = '';
882 - }
883 - if ( $value == '*' ) { // printout statement
884 - return;
885 - }
886 - }
887 - $list = preg_split( '/^(' . $smwgQComparators . ')/u', $value, 2, PREG_SPLIT_DELIM_CAPTURE );
888 - $comparator = SMW_CMP_EQ;
889 - if ( count( $list ) == 3 ) { // initial comparator found ($list[1] should be empty)
890 - switch ( $list[1] ) {
891 - case '<':
892 - $comparator = SMW_CMP_LEQ;
893 - $value = $list[2];
894 - break;
895 - case '>':
896 - $comparator = SMW_CMP_GEQ;
897 - $value = $list[2];
898 - break;
899 - case '!':
900 - $comparator = SMW_CMP_NEQ;
901 - $value = $list[2];
902 - break;
903 - case '~':
904 - $comparator = SMW_CMP_LIKE;
905 - $value = $list[2];
906 - break;
907 - // default: not possible
908 - }
909 - }
910 - }
911 -
912 - /**
913 - * Parse an article description (the part of an inline query that
914 - * is in between "[[" and the closing "]]" assuming it is not specifying
915 - * a category or property) and create a suitable description.
916 - * The first chunk behind the "[[" has already been read and is
917 - * passed as a parameter.
918 - */
919 - // modified by ning ,add $relatedArticles
920 - protected function getArticleDescription( $firstchunk, &$setNS, &$label, &$relatedArticles ) {
921 - wfLoadExtensionMessages( 'SemanticMediaWiki' );
922 - $chunk = $firstchunk;
923 - $result = NULL;
924 - $continue = true;
925 - // $innerdesc = NULL;
926 - while ( $continue ) {
927 - if ( $chunk == '<q>' ) { // no subqueries of the form [[<q>...</q>]] (not needed)
928 - $this->m_errors[] = wfMsgForContent( 'smw_misplacedsubquery' );
929 - return NULL;
930 - }
931 - $list = preg_split( '/:/', $chunk, 3 ); // ":Category:Foo" "User:bar" ":baz" ":+"
932 - if ( ( $list[0] == '' ) && ( count( $list ) == 3 ) ) {
933 - $list = array_slice( $list, 1 );
934 - }
935 - if ( ( count( $list ) == 2 ) && ( $list[1] == '+' ) ) { // try namespace restriction
936 - global $wgContLang;
937 - $idx = $wgContLang->getNsIndex( $list[0] );
938 - if ( $idx !== false ) {
939 - $result = $this->addDescription( $result, new SMWNamespaceDescription( $idx ), false );
940 - }
941 - } else {
942 - $value = SMWDataValueFactory::newTypeIDValue( '_wpg', $chunk );
943 - if ( $value->isValid() ) {
944 - $result = $this->addDescription( $result, new SMWValueDescription( $value ), false );
945 - // added by ning
946 - $relatedArticles[] = array(
947 - 'namespace' => NS_MAIN,
948 - 'title' => Title::makeTitle( NS_MAIN, $chunk )->getDBkey() );
949 - }
950 - }
951 -
952 - $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
953 - if ( $chunk == '||' ) {
954 - $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
955 - $continue = true;
956 - } else {
957 - $continue = false;
958 - }
959 - }
960 -
961 - return $this->finishLinkDescription( $chunk, true, $result, $setNS, $label );
962 - }
963 -
964 - protected function finishLinkDescription( $chunk, $hasNamespaces, $result, &$setNS, &$label ) {
965 - wfLoadExtensionMessages( 'SemanticMediaWiki' );
966 - if ( $result === NULL ) { // no useful information or concrete error found
967 - $this->m_errors[] = wfMsgForContent( 'smw_badqueryatom' );
968 - } elseif ( !$hasNamespaces && $setNS && ( $this->m_defaultns !== NULL ) ) {
969 - $result = $this->addDescription( $result, $this->m_defaultns );
970 - $hasNamespaces = true;
971 - }
972 - $setNS = $hasNamespaces;
973 -
974 - // terminate link (assuming that next chunk was read already)
975 - if ( $chunk == '|' ) {
976 - $chunk = $this->readChunk( '\]\]' );
977 - if ( $chunk != ']]' ) {
978 - $label .= $chunk;
979 - $chunk = $this->readChunk( '\]\]' );
980 - } else { // empty label does not add to overall label
981 - $chunk = ']]';
982 - }
983 - }
984 - if ( $chunk != ']]' ) {
985 - // What happended? We found some chunk that could not be processed as
986 - // link content (as in [[Category:Test<q>]]) and there was no label to
987 - // eat it. Or the closing ]] are just missing entirely.
988 - if ( $chunk != '' ) {
989 - $this->m_errors[] = wfMsgForContent( 'smw_misplacedsymbol', htmlspecialchars( $chunk ) );
990 - // try to find a later closing ]] to finish this misshaped subpart
991 - $chunk = $this->readChunk( '\]\]' );
992 - if ( $chunk != ']]' ) {
993 - $chunk = $this->readChunk( '\]\]' );
994 - }
995 - }
996 - if ( $chunk == '' ) {
997 - $this->m_errors[] = wfMsgForContent( 'smw_noclosingbrackets' );
998 - }
999 - }
1000 - return $result;
1001 - }
1002 -
1003 - /**
1004 - * Get the next unstructured string chunk from the query string.
1005 - * Chunks are delimited by any of the special strings used in inline queries
1006 - * (such as [[, ]], <q>, ...). If the string starts with such a delimiter,
1007 - * this delimiter is returned. Otherwise the first string in front of such a
1008 - * delimiter is returned.
1009 - * Trailing and initial spaces are ignored if $trim is true, and chunks
1010 - * consisting only of spaces are not returned.
1011 - * If there is no more qurey string left to process, the empty string is
1012 - * returned (and in no other case).
1013 - *
1014 - * The stoppattern can be used to customise the matching, especially in order to
1015 - * overread certain special symbols.
1016 - *
1017 - * $consume specifies whether the returned chunk should be removed from the
1018 - * query string.
1019 - */
1020 - protected function readChunk( $stoppattern = '', $consume = true, $trim = true ) {
1021 - if ( $stoppattern == '' ) {
1022 - $stoppattern = '\[\[|\]\]|::|:=|<q>|<\/q>|^' . $this->m_categoryprefix .
1023 - '|^' . $this->m_conceptprefix . '|\|\||\|';
1024 - }
1025 - $chunks = preg_split( '/[\s]*(' . $stoppattern . ')/u', $this->m_curstring, 2, PREG_SPLIT_DELIM_CAPTURE );
1026 - if ( count( $chunks ) == 1 ) { // no matches anymore, strip spaces and finish
1027 - if ( $consume ) {
1028 - $this->m_curstring = '';
1029 - }
1030 - return $trim ? trim( $chunks[0] ):$chunks[0];
1031 - } elseif ( count( $chunks ) == 3 ) { // this should generally happen if count is not 1
1032 - if ( $chunks[0] == '' ) { // string started with delimiter
1033 - if ( $consume ) {
1034 - $this->m_curstring = $chunks[2];
1035 - }
1036 - return $trim ? trim( $chunks[1] ):$chunks[1];
1037 - } else {
1038 - if ( $consume ) {
1039 - $this->m_curstring = $chunks[1] . $chunks[2];
1040 - }
1041 - return $trim ? trim( $chunks[0] ):$chunks[0];
1042 - }
1043 - } else { return false; } // should never happen
1044 - }
1045 -
1046 - /**
1047 - * Enter a new subblock in the query, which must at some time be terminated by the
1048 - * given $endstring delimiter calling popDelimiter();
1049 - */
1050 - protected function pushDelimiter( $endstring ) {
1051 - array_push( $this->m_sepstack, $endstring );
1052 - }
1053 -
1054 - /**
1055 - * Exit a subblock in the query ending with the given delimiter.
1056 - * If the delimiter does not match the top-most open block, false
1057 - * will be returned. Otherwise return true.
1058 - */
1059 - protected function popDelimiter( $endstring ) {
1060 - $topdelim = array_pop( $this->m_sepstack );
1061 - return ( $topdelim == $endstring );
1062 - }
1063 -
1064 - /**
1065 - * Extend a given description by a new one, either by adding the new description
1066 - * (if the old one is a container description) or by creating a new container.
1067 - * The parameter $conjunction determines whether the combination of both descriptions
1068 - * should be a disjunction or conjunction.
1069 - *
1070 - * In the special case that the current description is NULL, the new one will just
1071 - * replace the current one.
1072 - *
1073 - * The return value is the expected combined description. The object $curdesc will
1074 - * also be changed (if it was non-NULL).
1075 - */
1076 - protected function addDescription( $curdesc, $newdesc, $conjunction = true ) {
1077 - wfLoadExtensionMessages( 'SemanticMediaWiki' );
1078 - $notallowedmessage = 'smw_noqueryfeature';
1079 - if ( $newdesc instanceof SMWSomeProperty ) {
1080 - $allowed = $this->m_queryfeatures & SMW_PROPERTY_QUERY;
1081 - } elseif ( $newdesc instanceof SMWClassDescription ) {
1082 - $allowed = $this->m_queryfeatures & SMW_CATEGORY_QUERY;
1083 - } elseif ( $newdesc instanceof SMWConceptDescription ) {
1084 - $allowed = $this->m_queryfeatures & SMW_CONCEPT_QUERY;
1085 - } elseif ( $newdesc instanceof SMWConjunction ) {
1086 - $allowed = $this->m_queryfeatures & SMW_CONJUNCTION_QUERY;
1087 - $notallowedmessage = 'smw_noconjunctions';
1088 - } elseif ( $newdesc instanceof SMWDisjunction ) {
1089 - $allowed = $this->m_queryfeatures & SMW_DISJUNCTION_QUERY;
1090 - $notallowedmessage = 'smw_nodisjunctions';
1091 - } else {
1092 - $allowed = true;
1093 - }
1094 - if ( !$allowed ) {
1095 - $this->m_errors[] = wfMsgForContent( $notallowedmessage, str_replace( '[', '&#x005B;', $newdesc->getQueryString() ) );
1096 - return $curdesc;
1097 - }
1098 - if ( $newdesc === NULL ) {
1099 - return $curdesc;
1100 - } elseif ( $curdesc === NULL ) {
1101 - return $newdesc;
1102 - } else { // we already found descriptions
1103 - if ( ( ( $conjunction ) && ( $curdesc instanceof SMWConjunction ) ) ||
1104 - ( ( !$conjunction ) && ( $curdesc instanceof SMWDisjunction ) ) ) { // use existing container
1105 - $curdesc->addDescription( $newdesc );
1106 - return $curdesc;
1107 - } elseif ( $conjunction ) { // make new conjunction
1108 - if ( $this->m_queryfeatures & SMW_CONJUNCTION_QUERY ) {
1109 - return new SMWConjunction( array( $curdesc, $newdesc ) );
1110 - } else {
1111 - $this->m_errors[] = wfMsgForContent( 'smw_noconjunctions', str_replace( '[', '&#x005B;', $newdesc->getQueryString() ) );
1112 - return $curdesc;
1113 - }
1114 - } else { // make new disjunction
1115 - if ( $this->m_queryfeatures & SMW_DISJUNCTION_QUERY ) {
1116 - return new SMWDisjunction( array( $curdesc, $newdesc ) );
1117 - } else {
1118 - $this->m_errors[] = wfMsgForContent( 'smw_nodisjunctions', str_replace( '[', '&#x005B;', $newdesc->getQueryString() ) );
1119 - return $curdesc;
1120 - }
1121 - }
1122 - }
1123 - }
1124 -}
1125 -
1126 -class SMWNotifyUpdate {
1127 - protected $m_info;
1128 - protected $m_title; // current title of the update
1129 - protected $m_userMsgs; // user_id => plain text message
1130 - protected $m_userHtmlPropMsgs; // user_id => html message, prop change detail
1131 - protected $m_userHtmlNMMsgs; // user_id => html message, all notify hint
1132 - protected $m_userNMs; // user_id => notify_id
1133 - protected $m_notifyHtmlPropMsgs; // notify_id => html message, prop change detail
1134 - protected $m_notifyHtmlMsgs; // notify_id => html message, all notify hint
1135 - protected $m_newMonitor; // notify newly matches the page, array( notify id, page id )
1136 - protected $m_removeMonitored; // notify no longer matches the page, array( notify id, page id )
1137 - protected $m_subQueryNotify; // subquery, will go through all pages, attention!!!
1138 -
1139 - protected $m_linker;
1140 -
1141 - protected function getSemanticInfo( $title ) {
1142 - $result = array();
1143 - $sStore = NMStorage::getDatabase();
1144 - $semdata = smwfGetStore()->getSemanticData( $title );
1145 - foreach ( $semdata->getProperties() as $property ) {
1146 - if ( !$property->isShown() && $property->getWikiValue() != '' ) { // showing this is not desired, hide
1147 - continue;
1148 - } elseif ( $property->isUserDefined() ) { // user defined property
1149 - $property->setCaption( preg_replace( '/[ ]/u', '&#160;', $property->getWikiValue(), 2 ) );
1150 - }
1151 -
1152 - $propvalues = $semdata->getPropertyValues( $property );
1153 - if ( $property->getWikiValue() != '' ) {
1154 - foreach ( $propvalues as $propvalue ) {
1155 - if ( $propvalue->getWikiValue() != '' ) {
1156 - $result[SMWNotifyProcessor::toInfoId( 2, 0, $sStore->lookupSmwId( SMW_NS_PROPERTY, $property->getWikiValue() ) )][] = array( 'name' => $property, 'value' => $propvalue );
1157 - }
1158 - }
1159 - } else {
1160 - foreach ( $propvalues as $propvalue ) {
1161 - if ( ( $propvalue instanceof SMWWikiPageValue ) && ( $propvalue->getNamespace() == NS_CATEGORY ) ) {
1162 - $result[SMWNotifyProcessor::toInfoId( 0, 0, $sStore->lookupSmwId( NS_CATEGORY, $propvalue->getWikiValue() ) )][] = array( 'name' => $propvalue, 'value' => null );
1163 - }
1164 - }
1165 - }
1166 - }
1167 - return $result;
1168 - }
1169 -
1170 - public function SMWNotifyUpdate( $title ) {
1171 - $this->m_title = $title;
1172 - $this->m_userMsgs = array();
1173 - $this->m_userHtmlPropMsgs = array();
1174 - $this->m_userHtmlNMMsgs = array();
1175 - $this->m_userNMs = array();
1176 - $this->m_notifyHtmlPropMsgs = array();
1177 - $this->m_notifyHtmlMsgs = array();
1178 - $this->m_newMonitor = array();
1179 - $this->m_removeMonitored = array();
1180 - $this->m_subQueryNotify = array();
1181 - $this->m_linker = new Linker();
1182 -
1183 - $page_id = $title->getArticleID();
1184 - if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
1185 - return;
1186 - }
1187 - $this->m_info = $this->getSemanticInfo( $this->m_title );
1188 - }
1189 - public function executeNotifyDelete( $reason ) {
1190 - $page_id = $this->m_title->getArticleID();
1191 - if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
1192 - return;
1193 - }
1194 - $page_name = $this->m_title->getText() . ' (' . $this->m_title->getFullUrl() . ')';
1195 - $page_html_name = '<a href="' . $this->m_title->getFullUrl() . '">' . htmlspecialchars( $this->m_title->getText() ) . '</a>';
1196 -
1197 - $msg .= wfMsg( 'smw_nm_hint_delete', $page_name, $reason );
1198 - $sStore = NMStorage::getDatabase();
1199 - $notifications = $sStore->getMonitoredNotifications( $page_id );
1200 -
1201 - $notifyMsgAdded = array();
1202 - foreach ( $notifications as $user_id => $notifies ) {
1203 - $this->m_userMsgs[$user_id] .= $msg . '\r\n( NM: ';
1204 - $hint = wfMsg( 'smw_nm_hint_delete_html', $page_html_name, htmlspecialchars( $reason ) );
1205 - $this->m_userHtmlNMMsgs[$user_id] .= $hint;
1206 - $htmlMsg = '';
1207 - $first = true;
1208 - foreach ( $notifies as $notify_id => $notify_detail ) {
1209 - if ( !$first ) {
1210 - $this->m_userMsgs[$user_id] .= ', ';
1211 - $htmlMsg .= ', ';
1212 - } else {
1213 - $first = false;
1214 - }
1215 - if ( !isset( $notifyMsgAdded[$notify_id] ) ) {
1216 - $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
1217 - $notifyMsgAdded[$notify_id] = true;
1218 - }
1219 -
1220 - $this->m_userMsgs[$user_id] .= $notify_detail['name'];
1221 - $htmlMsg .= '<b>' . htmlspecialchars( $notify_detail['name'] ) . '</b>';
1222 - $this->m_removeMonitored[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
1223 -
1224 - $this->m_userNMs[$user_id][] = $notify_id;
1225 - }
1226 -
1227 - $this->m_userMsgs[$user_id] .= " ).";
1228 - $this->m_userHtmlNMMsgs[$user_id] .= wfMsg( 'smw_nm_hint_notmatch_html', $htmlMsg );
1229 - }
1230 -
1231 - $this->notifyUsers();
1232 - $sStore->removeNotifyMonitor( $this->m_removeMonitored );
1233 - }
1234 - function isEqual( $v1, $v2 ) {
1235 - return ( strval( $v1[value]->getWikiValue() ) == strval( $v2[value]->getWikiValue() ) );
1236 - }
1237 - function getNotifyPlain( $info, $key ) {
1238 - $i = SMWNotifyProcessor::getInfoFromId( $key );
1239 - if ( $i[type] == 0 ) {
1240 - return "\r\n'" . $info[name]->getWikiValue() . "' has been " . ( $info[sem_act] == 0 ? "deleted":"added" ) . ".";
1241 - } else {
1242 - $tmp = "\r\nProperty '" . $info[name]->getWikiValue() . "' has been " . ( $info[sem_act] == 0 ? "deleted.":( $info[sem_act] == 1 ? "modified":"added" ) ) . ".";
1243 - $first = true;
1244 - foreach ( $info[del_vals] as $val ) {
1245 - if ( $first ) {
1246 - $tmp .= "\r\nValue '";
1247 - $first = false;
1248 - } else {
1249 - $tmp .= "', '";
1250 - }
1251 - $tmp .= $val[plain];
1252 - }
1253 - if ( !$first ) {
1254 - $tmp .= "' deleted.";
1255 - }
1256 - $first = true;
1257 - foreach ( $info[new_vals] as $val ) {
1258 - if ( $first ) {
1259 - $tmp .= "\r\nValue '";
1260 - $first = false;
1261 - } else {
1262 - $tmp .= "', '";
1263 - }
1264 - $tmp .= $val[plain];
1265 - }
1266 - if ( !$first ) {
1267 - $tmp .= "' added.";
1268 - }
1269 - return $tmp . "\r\n";
1270 - }
1271 - }
1272 - function getNotifyHtml( $info, $key ) {
1273 - $i = SMWNotifyProcessor::getInfoFromId( $key );
1274 - if ( $i[type] == 0 ) {
1275 - return "<td>Category</td>
1276 - <td>" . $this->getFullLink( $info[name] ) . "</td>
1277 - <td>" . ( $info[sem_act] == 0 ? "<font color='green'>remove</font>":"<font color='red'>cite</font>" ) . "</td>
1278 - <td colspan='2'>N/A</td>";
1279 - } else {
1280 - $rows = max( count( $info[del_vals] ), count( $info[new_vals] ) );
1281 - $tmp = "<tr><td rowspan='$rows'>Property</td>
1282 - <td rowspan='$rows'>" . $this->getFullLink( $info[name] ) . "</td>
1283 - <td rowspan='$rows'>" . ( $info[sem_act] == 0 ? "<font color='green'>remove</font>":( $info[sem_act] == 1 ? "<font color='blue'>modify</font>":"<font color='red'>cite</font>" ) ) . "</td>";
1284 - for ( $idx = 0; $idx < $rows; ++$idx ) {
1285 - if ( $idx > 0 ) {
1286 - $tmp .= "<tr>";
1287 - }
1288 - $tmp .= "<td>" . ( isset( $info[del_vals][$idx] ) ? $info[del_vals][$idx][html]:"&#160;" ) . "</td>
1289 - <td>" . ( isset( $info[new_vals][$idx] ) ? $info[new_vals][$idx][html]:"&#160;" ) . "</td>
1290 - </tr>";
1291 - }
1292 - return $tmp;
1293 - }
1294 - }
1295 - public function executeNotifyUpdate() {
1296 - $page_id = $this->m_title->getArticleID();
1297 - if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
1298 - return;
1299 - }
1300 - $sStore = NMStorage::getDatabase();
1301 -
1302 - $info = $this->getSemanticInfo( $this->m_title );
1303 - // get different
1304 - $tmp_info = array(); // type : category 0, property 2; name; sem action : del 0, modify 1, add 2; val action : del 0, add 1
1305 - foreach ( $this->m_info as $key => $value ) {
1306 - $i = SMWNotifyProcessor::getInfoFromId( $key );
1307 - $updated = false;
1308 - if ( !isset( $info[$key] ) ) {
1309 - if ( $i[type] == 0 ) {
1310 - $tmp_info[$key] = array( 'sem_act' => 0, 'name' => $value[0][name] );
1311 - } else {
1312 - $tmp_info[$key] = array( 'sem_act' => 0, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
1313 - foreach ( $value as $v ) {
1314 - $tmp_info[$key][del_vals][] = array( 'plain' => $v[value]->getWikiValue(), 'html' => $this->getFullLink( $v[value] ) );
1315 - }
1316 - }
1317 - } else if ( $i[type] == 2 ) {
1318 - $mvalue = $info[$key];
1319 - foreach ( $value as $v1 ) {
1320 - $found = false;
1321 - foreach ( $mvalue as $v2 ) {
1322 - if ( $this->isEqual( $v1, $v2 ) ) {
1323 - $found = true;
1324 - break;
1325 - }
1326 - }
1327 - if ( !$found ) {
1328 - if ( !$updated ) {
1329 - $updated = true;
1330 - $tmp_info[$key] = array( 'sem_act' => 1, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
1331 - }
1332 - $tmp_info[$key][del_vals][] = array( 'plain' => $v1[value]->getWikiValue(), 'html' => $this->getFullLink( $v1[value] ) );
1333 - }
1334 - }
1335 - foreach ( $mvalue as $v1 ) {
1336 - $found = false;
1337 - foreach ( $value as $v2 ) {
1338 - if ( $this->isEqual( $v1, $v2 ) ) {
1339 - $found = true;
1340 - break;
1341 - }
1342 - }
1343 - if ( !$found ) {
1344 - if ( !$updated ) {
1345 - $updated = true;
1346 - $tmp_info[$key] = array( 'sem_act' => 1, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
1347 - }
1348 - $tmp_info[$key][new_vals][] = array( 'plain' => $v1[value]->getWikiValue(), 'html' => $this->getFullLink( $v1[value] ) );
1349 - }
1350 - }
1351 - }
1352 - }
1353 - foreach ( $info as $key => $value ) {
1354 - $i = SMWNotifyProcessor::getInfoFromId( $key );
1355 - if ( !isset( $this->m_info[$key] ) ) {
1356 - if ( $i[type] == 0 ) {
1357 - $tmp_info[$key] = array( 'sem_act' => 2, 'name' => $value[0][name] );
1358 - } else {
1359 - $tmp_info[$key] = array( 'sem_act' => 2, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
1360 - foreach ( $value as $v ) {
1361 - $tmp_info[$key][new_vals][] = array( 'plain' => $v[value]->getWikiValue(), 'html' => $this->getFullLink( $v[value] ) );
1362 - }
1363 - }
1364 - }
1365 - }
1366 -
1367 - $notifications = $sStore->getMonitoredNotificationsDetail( $page_id );
1368 - // add semantic info to report all NM
1369 - foreach ( $notifications as $user_id => $notifies ) {
1370 - foreach ( $notifies['rep_all'] as $notify_id => $notify_name ) {
1371 - foreach ( array_keys( $tmp_info ) as $key ) {
1372 - $notifications[$user_id]['semantic'][$key][$notify_id] = $notify_name;
1373 - }
1374 - }
1375 - }
1376 - $page_name = $this->m_title->getText() . ' (' . $this->m_title->getFullUrl() . ')';
1377 -
1378 - $notifyMsgAdded = array();
1379 - foreach ( $notifications as $user_id => $notifies ) {
1380 - if ( !isset( $notifies['semantic'] ) ) continue;
1381 - foreach ( $notifies['semantic'] as $key => $notify ) {
1382 - if ( isset( $tmp_info[$key] ) ) {
1383 - $hint = "";
1384 - if ( !isset( $this->m_userMsgs[$user_id] ) ) {
1385 - $this->m_userMsgs[$user_id] = wfMsg( 'smw_nm_hint_change', $page_name );
1386 - $hint = wfMsg( 'smw_nm_hint_change_html', $this->m_title->getFullUrl(), htmlspecialchars( $this->m_title->getText() ) );
1387 - $this->m_userHtmlNMMsgs[$user_id] .= $hint;
1388 - }
1389 -
1390 - $this->m_userMsgs[$user_id] .= $this->getNotifyPlain( $tmp_info[$key], $key ) . ' ( NM: ';
1391 - $propHint = $this->getNotifyHtml( $tmp_info[$key], $key );
1392 - $this->m_userHtmlPropMsgs[$user_id] .= $propHint . "<tr><td colspan='5'>" . wfMsg( 'smw_notifyme' ) . ": ";
1393 - $first = true;
1394 - foreach ( $notify as $notify_id => $notify_name ) {
1395 - if ( !$first ) {
1396 - $this->m_userMsgs[$user_id] .= ', ';
1397 - $this->m_userHtmlPropMsgs[$user_id] .= ', ';
1398 - } else {
1399 - $first = false;
1400 - }
1401 - $this->m_userMsgs[$user_id] .= $notify_name;
1402 - $this->m_userHtmlPropMsgs[$user_id] .= '<b>' . htmlspecialchars( $notify_name ) . '</b>';
1403 -
1404 - if ( !isset( $notifyMsgAdded[$notify_id] ) ) {
1405 - $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
1406 - }
1407 - if ( !isset( $notifyMsgAdded[$notify_id][$key] ) ) {
1408 - $this->m_notifyHtmlPropMsgs[$notify_id] .= $propHint;
1409 - $notifyMsgAdded[$notify_id][$key] = true;
1410 - }
1411 -
1412 - $this->m_userNMs[$user_id][] = $notify_id;
1413 - }
1414 - $this->m_userMsgs[$user_id] .= ' ).';
1415 - $this->m_userHtmlPropMsgs[$user_id] .= "</td></tr>";
1416 - }
1417 - }
1418 - }
1419 - // get possible subquery
1420 - $this->m_subQueryNotify = array();
1421 - $queries = $sStore->getPossibleQuery( $this->m_info );
1422 - if ( is_array( $queries ) ) {
1423 - foreach ( $queries[1] as $notify_id => $notify ) {
1424 - $this->m_subQueryNotify[$notify_id] = $notify;
1425 - }
1426 - }
1427 -
1428 - $this->m_info = $info;
1429 - }
1430 -
1431 - // this will cost time, think we can update monitor in a single thread, like Job
1432 - public function updateNotifyMonitor() {
1433 - $page_id = $this->m_title->getArticleID();
1434 - if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
1435 - return;
1436 - }
1437 - $sStore = NMStorage::getDatabase();
1438 - $queries = $sStore->getPossibleQuery( $this->m_info );
1439 - if ( !is_array( $queries ) ) {
1440 - return;
1441 - }
1442 - // get monitored query
1443 - $main_queries = $sStore->getMonitoredQuery( $page_id );
1444 - foreach ( $queries[0] as $notify_id => $notify ) {
1445 - $main_queries[$notify_id] = $notify;
1446 - }
1447 -
1448 - // begin notify query on main query
1449 - $page_name = $this->m_title->getText() . ' (' . $this->m_title->getFullUrl() . ')';
1450 - $page_html_name = '<a href="' . $this->m_title->getFullUrl() . '">' . htmlspecialchars( $this->m_title->getText() ) . '</a>';
1451 -
1452 - foreach ( $main_queries as $notify_id => $notify ) {
1453 - $sStore->getNotifyInMainQuery( $page_id, $notify_id, $notify['sql'], $notify['hierarchy'], $match, $monitoring );
1454 - if ( ( !$monitoring ) && $match ) {
1455 - $hint = wfMsg( 'smw_nm_hint_match_html', $page_html_name, htmlspecialchars( $notify[name] ) );
1456 - foreach ( $notify['user_ids'] as $uid ) {
1457 - $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_match', $page_name, $notify[name] );
1458 - $this->m_userHtmlNMMsgs[$uid] .= $hint;
1459 - }
1460 - $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
1461 - $this->m_newMonitor[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
1462 - } else if ( ( !$match ) && $monitoring ) {
1463 - $hint = wfMsg( 'smw_nm_hint_nomatch_html', $page_html_name, htmlspecialchars( $notify[name] ) );
1464 - foreach ( $notify['user_ids'] as $uid ) {
1465 - $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_nomatch', $page_name, $notify[name] );
1466 - $this->m_userHtmlNMMsgs[$uid] .= $hint;
1467 - }
1468 - $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
1469 - $this->m_removeMonitored[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
1470 - }
1471 - foreach ( $notify['user_ids'] as $uid ) {
1472 - $this->m_userNMs[$uid][] = $notify_id;
1473 - }
1474 - }
1475 - // begin notify query on sub query, should go through all pages
1476 - foreach ( $queries[1] as $notify_id => $notify ) {
1477 - $this->m_subQueryNotify[$notify_id] = $notify;
1478 - }
1479 - foreach ( $this->m_subQueryNotify as $notify_id => $notify ) {
1480 - $res = $sStore->getNotifyInSubquery( $notify_id, $notify['sql'], $notify['hierarchy'] );
1481 -
1482 - $no_matches = array_diff( $res['monitoring'], $res['match'] );
1483 - $matches = array_diff( $res['match'], $res['monitoring'] );
1484 - foreach ( $matches as $pid ) {
1485 - $pt = $sStore->getPageTitle( $pid );
1486 - if ( !$pt ) {
1487 - continue;
1488 - }
1489 - $t = Title::makeTitle( NS_MAIN, $pt->page_title );
1490 - $p_name = $t->getText() . ' (' . $t->getFullUrl() . ')';
1491 - $p_html_name = '<a href="' . $t->getFullUrl() . '">' . htmlspecialchars( $t->getText() ) . '</a>';
1492 -
1493 - $hint = wfMsg( 'smw_nm_hint_submatch_html', $page_html_name, $p_html_name, htmlspecialchars( $notify[name] ) );
1494 - foreach ( $notify['user_ids'] as $uid ) {
1495 - $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_submatch', $page_name, $p_name, $notify[name] );
1496 - $this->m_userHtmlNMMsgs[$uid] .= $hint;
1497 - }
1498 - $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
1499 - $this->m_newMonitor[] = array( 'notify_id' => $notify_id, 'page_id' => $pid );
1500 -
1501 - foreach ( $notify['user_ids'] as $uid ) {
1502 - $this->m_userNMs[$uid][] = $notify_id;
1503 - }
1504 - }
1505 - foreach ( $no_matches as $pid ) {
1506 - $pt = $sStore->getPageTitle( $pid );
1507 - if ( !$pt ) {
1508 - continue;
1509 - }
1510 - $t = Title::makeTitle( NS_MAIN, $pt->page_title );
1511 - $p_name = $t->getText() . ' (' . $t->getFullUrl() . ')';
1512 - $p_html_name = '<a href="' . $t->getFullUrl() . '">' . htmlspecialchars( $t->getText() ) . '</a>';
1513 -
1514 - $hint = wfMsg( 'smw_nm_hint_subnomatch_html', $page_html_name, $p_html_name, htmlspecialchars( $notify[name] ) );
1515 - foreach ( $notify['user_ids'] as $uid ) {
1516 - $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_subnomatch', $page_name, $p_name, $notify[name] );
1517 - $this->m_userHtmlNMMsgs[$uid] .= $hint;
1518 - }
1519 - $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
1520 - $this->m_removeMonitored[] = array( 'notify_id' => $notify_id, 'page_id' => $pid );
1521 -
1522 - foreach ( $notify['user_ids'] as $uid ) {
1523 - $this->m_userNMs[$uid][] = $notify_id;
1524 - }
1525 - }
1526 - }
1527 -
1528 - $sStore->removeNotifyMonitor( $this->m_removeMonitored );
1529 - $sStore->addNotifyMonitor( $this->m_newMonitor );
1530 - }
1531 - private function getFullLink( $val ) {
1532 - if ( $val instanceof SMWWikiPageValue ) {
1533 - return '<a href="' . $val->getTitle()->getFullUrl() . '">' . htmlspecialchars( $val->getTitle()->getText() ) . '</a>';
1534 - } else if ( $val instanceof SMWPropertyValue ) {
1535 - $val = $val->getWikiPageValue();
1536 - return '<a href="' . $val->getTitle()->getFullUrl() . '">' . htmlspecialchars( $val->getTitle()->getText() ) . '</a>';
1537 - } else {
1538 - return $val->getShortHTMLText( $this->m_linker );
1539 - }
1540 - }
1541 - private function applyStyle( $html ) {
1542 - $html = str_replace( "class=\"smwtable\"", "style=\"background-color: #EEEEFF;\"", $html );
1543 - $html = str_replace( "<th", "<th style=\"background-color: #EEEEFF;text-align: left;\"", $html );
1544 - $html = str_replace( "<td", "<td style=\"background-color: #FFFFFF;padding: 1px;padding-left: 5px;padding-right: 5px;text-align: left;vertical-align: top;\"", $html );
1545 - return $html;
1546 - }
1547 - public function notifyUsers() {
1548 - global $wgSitename, $wgSMTP, $wgEmergencyContact, $wgEnotifyMeJob;
1549 - $sStore = NMStorage::getDatabase();
1550 -
1551 - $nm_send_jobs = array();
1552 - $id = 0;
1553 -
1554 - if ( count( $this->m_notifyHtmlMsgs ) > 0 ) {
1555 - $notifications = $sStore->getNotifyMe( array_keys( $this->m_notifyHtmlMsgs ) );
1556 - }
1557 - $html_style = '';
1558 - // <style>
1559 - // table.smwtable{background-color: #EEEEFF;}
1560 - // table.smwtable th{background-color: #EEEEFF;text-align: left;}
1561 - // table.smwtable td{background-color: #FFFFFF;padding: 1px;padding-left: 5px;padding-right: 5px;text-align: left;vertical-align: top;}
1562 - // table.smwtable tr.smwfooter td{font-size: 90%;line-height: 1;background-color: #EEEEFF;padding: 0px;padding-left: 5px;padding-right: 5px;text-align: right;vertical-align: top;}
1563 - // </style>';
1564 - $html_showall = array();
1565 - foreach ( $this->m_notifyHtmlMsgs as $notify_id => $msg ) {
1566 - $html_msg = $html_style;
1567 - $showing_all = false;
1568 - if ( isset( $notifications[$notify_id] ) && $notifications[$notify_id]['show_all'] ) {
1569 - SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $notifications[$notify_id]['query'] ), $querystring, $params, $printouts );
1570 -
1571 - $format = 'auto';
1572 - if ( array_key_exists( 'format', $params ) ) {
1573 - $format = strtolower( trim( $params['format'] ) );
1574 - global $smwgResultFormats;
1575 - if ( !array_key_exists( $format, $smwgResultFormats ) ) {
1576 - $format = 'auto';
1577 - }
1578 - }
1579 - $query = SMWQueryProcessor::createQuery( $querystring, $params, SMWQueryProcessor::INLINE_QUERY, $format, $printouts );
1580 - $res = smwfGetStore()->getQueryResult( $query );
1581 - $printer = SMWQueryProcessor::getResultPrinter( $format, SMWQueryProcessor::INLINE_QUERY, $res );
1582 - $result = $printer->getResult( $res, $params, SMW_OUTPUT_HTML );
1583 - $html_msg .= $result . '<br/>';
1584 - $html_showall[$notify_id] = array ( 'name' => $notifications[$notify_id]['name'], 'html' => $result );
1585 -
1586 - $showing_all = true;
1587 - $link = $res->getQueryLink()->getURL();
1588 - }
1589 - global $smwgNMHideDiffWhenShowAll;
1590 - if ( !( $smwgNMHideDiffWhenShowAll && $showing_all ) ) {
1591 - $html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_notifyHtmlMsgs[$notify_id] );
1592 - if ( isset( $this->m_notifyHtmlPropMsgs[$notify_id] ) ) {
1593 - $html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_notifyHtmlPropMsgs[$notify_id] );
1594 - }
1595 - }
1596 - if ( $showing_all ) {
1597 - $id = $sStore->addNotifyRSS( 'nid', $notify_id, "All current items, " . date( 'Y-m-d H:i:s', time() ), $this->applyStyle( $html_msg ), $link );
1598 - } else {
1599 - $id = $sStore->addNotifyRSS( 'nid', $notify_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );
1600 - }
1601 - }
1602 - foreach ( $this->m_userMsgs as $user_id => $msg ) {
1603 - // generate RSS items
1604 - $html_msg = $html_style;
1605 - foreach ( array_unique( $this->m_userNMs[$user_id] ) as $showall_nid ) {
1606 - if ( isset( $html_showall[$showall_nid] ) ) {
1607 - $html_msg .= wfMsg( 'smw_nm_hint_item_html', $html_showall[$showall_nid]['name'], $html_showall[$showall_nid]['html'] );
1608 - }
1609 - }
1610 -
1611 - $html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_userHtmlNMMsgs[$user_id] );
1612 - if ( isset( $this->m_userHtmlPropMsgs[$user_id] ) ) {
1613 - $html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_userHtmlPropMsgs[$user_id] );
1614 - }
1615 -
1616 - global $wgNMReportModifier, $wgUser;
1617 - if ( $wgNMReportModifier ) {
1618 - $userText = $wgUser->getName();
1619 - if ( $wgUser->getId() == 0 ) {
1620 - $page = SpecialPage::getTitleFor( 'Contributions', $userText );
1621 - } else {
1622 - $page = Title::makeTitle( NS_USER, $userText );
1623 - }
1624 - $l = '<a href="' . $page->getFullUrl() . '">' . htmlspecialchars( $userText ) . '</a>';
1625 - $html_msg .= wfMsg( 'smw_nm_hint_modifier_html', $l );
1626 - $msg .= wfMsg( 'smw_nm_hint_modifier', $wgUser->getName() );
1627 - }
1628 -
1629 - $id = $sStore->addNotifyRSS( 'uid', $user_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );
1630 -
1631 - if ( $wgEnotifyMeJob ) {
1632 - // send notifications by mail
1633 - $user_info = $sStore->getUserInfo( $user_id );
1634 - if ( ( $user_info->user_email != '' ) && $this->getUserNMOption( $user_info->user_options ) ) {
1635 - $name = ( ( $user_info->user_real_name == '' ) ? $user_info->user_name:$user_info->user_real_name );
1636 -
1637 - $params = array( 'to' => new MailAddress( $user_info->user_email, $name ),
1638 - 'from' => new MailAddress( $wgEmergencyContact, 'Admin' ),
1639 - 'subj' => wfMsg( 'smw_nm_hint_mail_title', $this->m_title->getText(), $wgSitename ),
1640 - 'body' => wfMsg( 'smw_nm_hint_mail_body', $name, $msg ),
1641 - 'replyto' => new MailAddress( $wgEmergencyContact, 'Admin' ) );
1642 -
1643 - $nm_send_jobs[] = new SMW_NMSendMailJob( $this->m_title, $params );
1644 - }
1645 - }
1646 - }
1647 -
1648 - if ( $wgEnotifyMeJob ) {
1649 - if ( count( $nm_send_jobs ) ) {
1650 - Job :: batchInsert( $nm_send_jobs );
1651 - }
1652 - } else {
1653 - global $phpInterpreter;
1654 - if ( !isset( $phpInterpreter ) ) {
1655 - // if $phpInterpreter is not set, assume it is in search path
1656 - // if not, starting of bot will FAIL!
1657 - $phpInterpreter = "php";
1658 - }
1659 - // copy from SMW_GardeningBot.php
1660 - ob_start();
1661 - phpinfo();
1662 - $info = ob_get_contents();
1663 - ob_end_clean();
1664 - // Get Systemstring
1665 - preg_match( '!\nSystem(.*?)\n!is', strip_tags( $info ), $ma );
1666 - // Check if it consists 'windows' as string
1667 - preg_match( '/[Ww]indows/', $ma[1], $os );
1668 - global $smwgNMIP ;
1669 - if ( $os[0] == '' && $os[0] == null ) {
1670 -
1671 - // FIXME: $runCommand must allow whitespaces in paths too
1672 - $runCommand = "$phpInterpreter -q $smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php";
1673 - // TODO: test async code for linux.
1674 - // low prio
1675 - $nullResult = `$runCommand > /dev/null &`;
1676 - }
1677 - else // windowze
1678 - {
1679 - $runCommand = "\"\"$phpInterpreter\" -q \"$smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php\"\"";
1680 - $wshShell = new COM( "WScript.Shell" );
1681 - $runCommand = "cmd /C " . $runCommand;
1682 -
1683 - $oExec = $wshShell->Run( $runCommand, 7, false );
1684 - }
1685 - }
1686 - }
1687 - // copy from user class
1688 - function getUserNMOption( $str ) {
1689 - $options = array();
1690 - $a = explode( "\n", $str );
1691 - foreach ( $a as $s ) {
1692 - $m = array();
1693 - if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1694 - $options[$m[1]] = $m[2];
1695 - }
1696 - }
1697 - return $options['enotifyme'];
1698 - }
1699 -}
 2+<?php
 3+/**
 4+ * This file contains a static class for accessing functions to generate and execute
 5+ * notify me semantic queries and to serialise their results.
 6+ *
 7+ * @author ning
 8+ */
 9+if ( !defined( 'MEDIAWIKI' ) ) {
 10+ exit( 1 );
 11+}
 12+
 13+global $smwgIP, $smwgNMIP ;
 14+require_once( $smwgIP . '/includes/storage/SMW_Store.php' );
 15+require_once( $smwgNMIP . '/includes/SMW_NMStorage.php' );
 16+
 17+/**
 18+ * Static class for accessing functions to generate and execute semantic queries
 19+ * and to serialise their results.
 20+ */
 21+class SMWNotifyProcessor {
 22+
 23+ static public function getNotifications() {
 24+ $sStore = NMStorage::getDatabase();
 25+ global $wgUser;
 26+ $user_id = $wgUser->getId();
 27+
 28+ $notifications = $sStore->getNotifications( $user_id );
 29+
 30+ return $notifications;
 31+ }
 32+
 33+ /**
 34+ * Enable a NotifyMe with specified id and querystring
 35+ *
 36+ * used for inline query only
 37+ */
 38+ static public function enableNotify( $notify_id, $querystring, &$msg = NULL ) {
 39+ wfProfileIn( 'SMWNotifyProcessor::enableNotify (SMW)' );
 40+
 41+ $sStore = NMStorage::getDatabase();
 42+ global $smwgQDefaultNamespaces;
 43+
 44+ SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $querystring ), $querystring, $params, $printouts );
 45+ $relatedArticles = array();
 46+ foreach ( $printouts as $po ) {
 47+ $printoutArticles[] = array(
 48+ 'namespace' => SMW_NS_PROPERTY,
 49+ 'title' => Title::makeTitle( SMW_NS_PROPERTY, $po->getText( SMW_OUTPUT_WIKI ) )->getDBkey() );
 50+ }
 51+
 52+ $qp = new SMWNotifyParser( $notify_id, $printoutArticles );
 53+ $qp->setDefaultNamespaces( $smwgQDefaultNamespaces );
 54+ $desc = $qp->getQueryDescription( $querystring );
 55+
 56+ if ( !$qp->m_result ) {
 57+ $qp->m_errors[] = wfMsg( 'smw_nm_proc_pagenotexist' );
 58+ }
 59+
 60+ if ( isset( $msg ) && $qp->hasSubquery() ) {
 61+ $msg .= "\n" . wfMsg( 'smw_nm_proc_subqueryhint' );
 62+ }
 63+
 64+ $query = new SMWQuery( $desc, true, false );
 65+ $query->setQueryString( $querystring );
 66+ $query->addErrors( $qp->getErrors() ); // keep parsing errors for later output
 67+
 68+ $res = $sStore->getNMQueryResult( $query );
 69+
 70+ if ( count( $query->getErrors() ) > 0 ) {
 71+ if ( isset( $msg ) ) {
 72+ $msg .= "\n\n" . implode( '\n', $query->getErrors() ) . "\n\n" . wfMsg( 'smw_nm_proc_enablehint' );
 73+ }
 74+ $sStore->disableNotifyState( $notify_id );
 75+ wfProfileOut( 'SMWNotifyProcessor::enableNotify (SMW)' );
 76+ return false;
 77+ }
 78+
 79+ $sStore->updateNMSql( $notify_id, $res['sql'], $res['tmp_hierarchy'] );
 80+ if ( count( $res['page_ids'] ) > 0 ) {
 81+ $add_monitor = array();
 82+ foreach ( $res['page_ids'] as $page_id ) {
 83+ $add_monitor[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
 84+ }
 85+ $sStore->addNotifyMonitor( $add_monitor );
 86+ }
 87+ $sStore->updateNotifyState( $notify_id, 1 );
 88+ wfProfileOut( 'SMWNotifyProcessor::enableNotify (SMW)' );
 89+
 90+ return true;
 91+ }
 92+
 93+ static public function getQueryRawParams( $querystring ) {
 94+ // read query with printouts and (possibly) other parameters like sort, order, limit, etc...
 95+ $pos = strpos( $querystring, "|?" );
 96+ if ( $pos > 0 ) {
 97+ $rawparams[] = trim( substr( $querystring, 0, $pos ) );
 98+ $ps = explode( "|?", trim( substr( $querystring, $pos + 2 ) ) );
 99+ foreach ( $ps as $param ) {
 100+ $rawparams[] = "?" . trim( $param );
 101+ }
 102+ } else {
 103+ $ps = preg_split( '/[^\|]{1}\|{1}(?!\|)/s', $querystring );
 104+ if ( count( $ps ) > 1 ) {
 105+ // last char of query condition is missing (matched with [^\|]{1}) therefore copy from original
 106+ $rawparams[] = trim( substr( $querystring, 0, strlen( $ps[0] ) + 1 ) );
 107+ array_shift( $ps ); // remove the query condition
 108+ // add other params for formating etc.
 109+ foreach ( $ps as $param )
 110+ $rawparams[] = trim( $param );
 111+ } // no single pipe found, no params specified in query
 112+ else $rawparams[] = trim( $querystring );
 113+ }
 114+ $rawparams[] = "format=table";
 115+ $rawparams[] = "link=all";
 116+ return $rawparams;
 117+ }
 118+
 119+ static public function addNotify( $rawquery, $name, $rep_all, $show_all, $delegate ) {
 120+ global $wgTitle;
 121+ // Take care at least of some templates -- for better template support use #ask
 122+ $parser = new Parser();
 123+ $parserOptions = new ParserOptions();
 124+ $parser->startExternalParse( $wgTitle, $parserOptions, OT_HTML );
 125+ $rawquery = $parser->transformMsg( $rawquery, $parserOptions );
 126+
 127+ wfProfileIn( 'SMWNotifyProcessor::createNotify (SMW)' );
 128+ $sStore = NMStorage::getDatabase();
 129+ global $wgUser;
 130+ $user_id = $wgUser->getId();
 131+ if ( $user_id == 0 ) {
 132+ wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
 133+ return wfMsg( 'smw_nm_proc_notlogin' );
 134+ }
 135+
 136+ // check notify query first, use QueryParser from SMW
 137+ SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $rawquery ), $querystring, $params, $printouts );
 138+
 139+ $qp = new SMWQueryParser();
 140+ $qp->setDefaultNamespaces( $smwgQDefaultNamespaces );
 141+ $desc = $qp->getQueryDescription( $querystring );
 142+
 143+ if ( count( $qp->getErrors() ) > 0 ) {
 144+ wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
 145+ return wfMsg( 'smw_nm_proc_createfail', implode( "\n", $qp->getErrors() ) );
 146+ }
 147+
 148+ $notify_id = $sStore->addNotifyQuery( $user_id, $rawquery, $name, $rep_all, $show_all, $delegate );
 149+ if ( $notify_id == 0 ) {
 150+ wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
 151+ return wfMsg( 'smw_nm_proc_savefail' );
 152+ }
 153+ wfProfileOut( 'SMWNotifyProcessor::createNotify (SMW)' );
 154+
 155+ wfProfileIn( 'SMWNotifyProcessor::enableNotify (SMW)' );
 156+ $msg = '';
 157+ $result = SMWNotifyProcessor::enableNotify( $notify_id, $rawquery, $msg );
 158+ wfProfileOut( 'SMWNotifyProcessor::enableNotify (SMW)' );
 159+ return "1" . ( $result ? "1":"0" ) . "$notify_id,$msg";
 160+ }
 161+
 162+ static public function updateStates( $notify_ids ) {
 163+ wfProfileIn( 'SMWNotifyProcessor::updateStates (SMW)' );
 164+
 165+ $notifications = SMWNotifyProcessor::getNotifications();
 166+ if ( $notifications == null || !is_array( $notifications ) ) {
 167+ return wfMsg( 'smw_nm_proc_nonoti' );
 168+ }
 169+ $result = true;
 170+ $idx = 0;
 171+ $count = count( $notify_ids ) - 1;
 172+ $msg = '';
 173+ $errs = '';
 174+ $sStore = NMStorage::getDatabase();
 175+ foreach ( $notifications as $row ) {
 176+ if ( ( $idx < $count ) && ( $notify_ids[$idx] == $row['notify_id'] ) ) {
 177+ if ( $row['enable'] == 0 ) {
 178+ $m = '';
 179+ $r = SMWNotifyProcessor::enableNotify( $row['notify_id'], $row['query'], $m );
 180+ if ( !$r ) {
 181+ $msg .= "NotifyMe : '" . $row['name'] . "'$m\n\n";
 182+ $errs .= $row['notify_id'] . ",";
 183+ $result = false;
 184+ }
 185+ }
 186+ $idx ++;
 187+ } else {
 188+ if ( $row['enable'] == 1 ) {
 189+ $result = $sStore->disableNotifyState( $row['notify_id'] );
 190+ }
 191+ }
 192+ }
 193+
 194+ wfProfileOut( 'SMWNotifyProcessor::updateStates (SMW)' );
 195+ return $result ? wfMsg( 'smw_nm_proc_statesucc' ) : "0$errs|\n\n$msg";
 196+ }
 197+
 198+ static public function updateDelegates( $delegates ) {
 199+ wfProfileIn( 'SMWNotifyProcessor::updateDelegates (SMW)' );
 200+
 201+ $notifications = SMWNotifyProcessor::getNotifications();
 202+ if ( $notifications == null || !is_array( $notifications ) ) {
 203+ return wfMsg( 'smw_nm_proc_nonoti' );
 204+ }
 205+ $result = true;
 206+ $idx = 0;
 207+ $s = explode( ':', $delegates[$idx], 2 );
 208+ $count = count( $delegates ) - 1;
 209+ $sStore = NMStorage::getDatabase();
 210+ foreach ( $notifications as $row ) {
 211+ if ( ( $idx < $count ) && ( $s[0] == $row['notify_id'] ) ) {
 212+ $result = $sStore->updateDelegate( $row['notify_id'], $s[1] );
 213+ $idx ++;
 214+ $s = explode( ':', $delegates[$idx], 2 );
 215+ } else {
 216+ $result = $sStore->updateDelegate( $row['notify_id'], '' );
 217+ }
 218+ if ( !$result ) break;
 219+ }
 220+
 221+ wfProfileOut( 'SMWNotifyProcessor::updateDelegates (SMW)' );
 222+ return $result ? wfMsg( 'smw_nm_proc_delegatesucc' ) : wfMsg( 'smw_nm_proc_delegateerr' );
 223+ }
 224+
 225+ static public function refreshNotifyMe() {
 226+ wfProfileIn( 'SMWNotifyProcessor::refreshNotifyMe (SMW)' );
 227+ NMStorage::getDatabase()->cleanUp();
 228+ $notifications = NMStorage::getDatabase()->getAllNotifications();
 229+ foreach ( $notifications as $row ) {
 230+ if ( $row['enable'] ) {
 231+ $result = SMWNotifyProcessor::enableNotify( $row['notify_id'], $row['query'] );
 232+ }
 233+ }
 234+ wfProfileOut( 'SMWNotifyProcessor::refreshNotifyMe (SMW)' );
 235+ }
 236+
 237+ static public function updateReportAll( $notify_ids ) {
 238+ wfProfileIn( 'SMWNotifyProcessor::updateReportAlls (SMW)' );
 239+
 240+ $notifications = SMWNotifyProcessor::getNotifications();
 241+ if ( $notifications == null || !is_array( $notifications ) ) {
 242+ return wfMsg( 'smw_nm_proc_nonoti' );
 243+ }
 244+ $result = true;
 245+ $idx = 0;
 246+ $count = count( $notify_ids ) - 1;
 247+ $sStore = NMStorage::getDatabase();
 248+ foreach ( $notifications as $row ) {
 249+ if ( ( $idx < $count ) && ( $notify_ids[$idx] == $row['notify_id'] ) ) {
 250+ if ( $row['rep_all'] == 0 ) {
 251+ $result = $sStore->updateNotifyReportAll( $row['notify_id'], 1 );
 252+ }
 253+ $idx ++;
 254+ } else {
 255+ if ( $row['rep_all'] == 1 ) {
 256+ $result = $sStore->updateNotifyReportAll( $row['notify_id'], 0 );
 257+ }
 258+ }
 259+ if ( !$result ) break;
 260+ }
 261+
 262+ wfProfileOut( 'SMWNotifyProcessor::updateStates (SMW)' );
 263+ return $result ? wfMsg( 'smw_nm_proc_reportsucc' ) : wfMsg( 'smw_nm_proc_reporterr' );
 264+ }
 265+
 266+ static public function updateShowAll( $notify_ids ) {
 267+ wfProfileIn( 'SMWNotifyProcessor::updateShowAlls (SMW)' );
 268+
 269+ $notifications = SMWNotifyProcessor::getNotifications();
 270+ if ( $notifications == null || !is_array( $notifications ) ) {
 271+ return wfMsg( 'smw_nm_proc_nonoti' );
 272+ }
 273+ $result = true;
 274+ $idx = 0;
 275+ $count = count( $notify_ids ) - 1;
 276+ $sStore = NMStorage::getDatabase();
 277+ foreach ( $notifications as $row ) {
 278+ if ( ( $idx < $count ) && ( $notify_ids[$idx] == $row['notify_id'] ) ) {
 279+ if ( $row['show_all'] == 0 ) {
 280+ $result = $sStore->updateNotifyShowAll( $row['notify_id'], 1 );
 281+ }
 282+ $idx ++;
 283+ } else {
 284+ if ( $row['show_all'] == 1 ) {
 285+ $result = $sStore->updateNotifyShowAll( $row['notify_id'], 0 );
 286+ }
 287+ }
 288+ if ( !$result ) break;
 289+ }
 290+
 291+ wfProfileOut( 'SMWNotifyProcessor::updateStates (SMW)' );
 292+ return $result ? wfMsg( 'smw_nm_proc_showsucc' ) : wfMsg( 'smw_nm_proc_showerr' );
 293+ }
 294+
 295+ static public function delNotify( $notify_ids ) {
 296+ wfProfileIn( 'SMWNotifyProcessor::delNotify (SMW)' );
 297+ $sStore = NMStorage::getDatabase();
 298+ $result = $sStore->removeNotifyQuery( $notify_ids );
 299+ wfProfileOut( 'SMWNotifyProcessor::delNotify (SMW)' );
 300+ return $result ? wfMsg( 'smw_nm_proc_delsucc' ) : wfMsg( 'smw_nm_proc_delerr' );
 301+ }
 302+
 303+ static protected $notifyJobs = array();
 304+ static public function prepareArticleSave( $title ) {
 305+ $page_id = $title->getArticleID();
 306+ if ( $page_id == 0 ) {
 307+ return;
 308+ }
 309+ $updates = SMWNotifyProcessor::$notifyJobs[$page_id];
 310+ if ( empty( $updates ) ) {
 311+ SMWNotifyProcessor::$notifyJobs[$page_id] = new SMWNotifyUpdate( $title );
 312+ }
 313+ }
 314+ static public function articleSavedComplete( $title ) {
 315+ $page_id = $title->getArticleID();
 316+ if ( $page_id == 0 ) {
 317+ return;
 318+ }
 319+ $updates = SMWNotifyProcessor::$notifyJobs[$page_id];
 320+ if ( empty( $updates ) ) {
 321+ SMWNotifyProcessor::$notifyJobs[$page_id] = new SMWNotifyUpdate( $title );
 322+ $updates = SMWNotifyProcessor::$notifyJobs[$page_id];
 323+ } else {
 324+ $updates->executeNotifyUpdate();
 325+ }
 326+ $updates->updateNotifyMonitor();
 327+ $updates->notifyUsers();
 328+ unset( SMWNotifyProcessor::$notifyJobs[$page_id] );
 329+ }
 330+ static public function articleDelete( $title, $reason ) {
 331+ $page_id = $title->getArticleID();
 332+ if ( $page_id == 0 ) {
 333+ return;
 334+ }
 335+ $updates = new SMWNotifyUpdate( $title );
 336+ $updates->executeNotifyDelete( $reason );
 337+ }
 338+ static public function toInfoId( $type, $subquery, $attr_id ) {
 339+ return base_convert( strval( ( $subquery << 8 ) | $type ), 10, 9 ) . '9' . $attr_id;
 340+ }
 341+ static public function getInfoFromId( $id ) {
 342+ $idx = strpos( $id, '9' );
 343+ $t = intval( base_convert( substr( $id, 0, $idx ), 9, 10 ) );
 344+ return array(
 345+ 'type' => $t&0xFF,
 346+ 'subquery' => $t >> 8,
 347+ 'attr_id' => intval( substr( $id, $idx + 1 ) )
 348+ );
 349+ }
 350+
 351+}
 352+
 353+// based on SMW_QueryProcessor.php (v 1.4.2)
 354+/**
 355+ * Objects of this class are in charge of parsing a query string in order
 356+ * to create an SMWDescription. The class and methods are not static in order
 357+ * to more cleanly store the intermediate state and progress of the parser.
 358+ */
 359+class SMWNotifyParser {
 360+
 361+ protected $m_sepstack; // list of open blocks ("parentheses") that need closing at current step
 362+ protected $m_curstring; // remaining string to be parsed (parsing eats query string from the front)
 363+ var $m_errors; // empty array if all went right, array of strings otherwise
 364+ protected $m_label; // label of the main query result
 365+ protected $m_defaultns; // description of the default namespace restriction, or NULL if not used
 366+
 367+ protected $m_categoryprefix; // cache label of category namespace . ':'
 368+ protected $m_conceptprefix; // cache label of concept namespace . ':'
 369+ protected $m_queryfeatures; // query features to be supported, format similar to $smwgQFeatures
 370+
 371+ // added by ning
 372+ protected $m_notify_id;
 373+ protected $m_subquery;
 374+ protected $m_printoutArticles;
 375+ public $m_result;
 376+
 377+ // modified by ning
 378+ public function SMWNotifyParser( $notify_id, $printoutArticles, $queryfeatures = false ) {
 379+ $this->m_notify_id = $notify_id;
 380+ $this->m_printoutArticles = $printoutArticles;
 381+ $this->m_result = true;
 382+
 383+ global $wgContLang, $smwgQFeatures;
 384+ $this->m_categoryprefix = $wgContLang->getNsText( NS_CATEGORY ) . ':';
 385+ $this->m_conceptprefix = $wgContLang->getNsText( SMW_NS_CONCEPT ) . ':';
 386+ $this->m_defaultns = NULL;
 387+ $this->m_queryfeatures = $queryfeatures === false ? $smwgQFeatures:$queryfeatures;
 388+ }
 389+
 390+ // added by ning
 391+ public function hasSubquery() {
 392+ return $this->m_subquery > 1;
 393+ }
 394+
 395+ /**
 396+ * Provide an array of namespace constants that are used as default restrictions.
 397+ * If NULL is given, no such default restrictions will be added (faster).
 398+ */
 399+ public function setDefaultNamespaces( $nsarray ) {
 400+ $this->m_defaultns = NULL;
 401+ if ( $nsarray !== NULL ) {
 402+ foreach ( $nsarray as $ns ) {
 403+ $this->m_defaultns = $this->addDescription( $this->m_defaultns, new SMWNamespaceDescription( $ns ), false );
 404+ }
 405+ }
 406+ }
 407+
 408+ /**
 409+ * Compute an SMWDescription from a query string. Returns whatever descriptions could be
 410+ * wrestled from the given string (the most general result being SMWThingDescription if
 411+ * no meaningful condition was extracted).
 412+ */
 413+ public function getQueryDescription( $querystring ) {
 414+ wfProfileIn( 'SMWNotifyParser::getQueryDescription (SMW)' );
 415+ $this->m_errors = array();
 416+ $this->m_label = '';
 417+ $this->m_curstring = $querystring;
 418+ $this->m_sepstack = array();
 419+ $setNS = false;
 420+
 421+ // added by ning
 422+ $this->m_subquery = 0;
 423+
 424+ $result = $this->getSubqueryDescription( $setNS, $this->m_label );
 425+ if ( !$setNS ) { // add default namespaces if applicable
 426+ $result = $this->addDescription( $this->m_defaultns, $result );
 427+ }
 428+ if ( $result === NULL ) { // parsing went wrong, no default namespaces
 429+ $result = new SMWThingDescription();
 430+ }
 431+ wfProfileOut( 'SMWNotifyParser::getQueryDescription (SMW)' );
 432+ return $result;
 433+ }
 434+
 435+ /**
 436+ * Return array of error messages (possibly empty).
 437+ */
 438+ public function getErrors() {
 439+ return $this->m_errors;
 440+ }
 441+
 442+ /**
 443+ * Return error message or empty string if no error occurred.
 444+ */
 445+ public function getErrorString() {
 446+ return smwfEncodeMessages( $this->m_errors );
 447+ }
 448+
 449+ /**
 450+ * Return label for the results of this query (which
 451+ * might be empty if no such information was passed).
 452+ */
 453+ public function getLabel() {
 454+ return $this->m_label;
 455+ }
 456+
 457+
 458+ /**
 459+ * Compute an SMWDescription for current part of a query, which should
 460+ * be a standalone query (the main query or a subquery enclosed within
 461+ * "\<q\>...\</q\>". Recursively calls similar methods and returns NULL upon error.
 462+ *
 463+ * The call-by-ref parameter $setNS is a boolean. Its input specifies whether
 464+ * the query should set the current default namespace if no namespace restrictions
 465+ * were given. If false, the calling super-query is happy to set the required
 466+ * NS-restrictions by itself if needed. Otherwise the subquery has to impose the defaults.
 467+ * This is so, since outermost queries and subqueries of disjunctions will have to set
 468+ * their own default restrictions.
 469+ *
 470+ * The return value of $setNS specifies whether or not the subquery has a namespace
 471+ * specification in place. This might happen automatically if the query string imposes
 472+ * such restrictions. The return value is important for those callers that otherwise
 473+ * set up their own restrictions.
 474+ *
 475+ * Note that $setNS is no means to switch on or off default namespaces in general,
 476+ * but just controls query generation. For general effect, the default namespaces
 477+ * should be set to NULL.
 478+ *
 479+ * The call-by-ref parameter $label is used to append any label strings found.
 480+ */
 481+ protected function getSubqueryDescription( &$setNS, &$label ) {
 482+ global $smwgQPrintoutLimit;
 483+ wfLoadExtensionMessages( 'SemanticMediaWiki' );
 484+ $conjunction = NULL; // used for the current inner conjunction
 485+ $disjuncts = array(); // (disjunctive) array of subquery conjunctions
 486+ $printrequests = array(); // the printrequests found for this query level
 487+ $hasNamespaces = false; // does the current $conjnuction have its own namespace restrictions?
 488+ $mustSetNS = $setNS; // must ns restrictions be set? (may become true even if $setNS is false)
 489+
 490+ // added by ning
 491+ $subquery = $this->m_subquery;
 492+ if ( $subquery == 0 ) {
 493+ $relatedArticles = $this->m_printoutArticles;
 494+ } else {
 495+ $relatedArticles = array();
 496+ }
 497+ $this->m_subquery ++;
 498+
 499+ $continue = ( $chunk = $this->readChunk() ) != ''; // skip empty subquery completely, thorwing an error
 500+ while ( $continue ) {
 501+ $setsubNS = false;
 502+ switch ( $chunk ) {
 503+ case '[[': // start new link block
 504+ // modified by ning
 505+ $ld = $this->getLinkDescription( $setsubNS, $label, $relatedArticles );
 506+
 507+ if ( $ld instanceof SMWPrintRequest ) {
 508+ $printrequests[] = $ld;
 509+ } elseif ( $ld instanceof SMWDescription ) {
 510+ $conjunction = $this->addDescription( $conjunction, $ld );
 511+ }
 512+ break;
 513+ case '<q>': // enter new subquery, currently irrelevant but possible
 514+ $this->pushDelimiter( '</q>' );
 515+ $conjunction = $this->addDescription( $conjunction, $this->getSubqueryDescription( $setsubNS, $label ) );
 516+ // / TODO: print requests from subqueries currently are ignored, should be moved down
 517+ break;
 518+ case 'OR': case '||': case '': case '</q>': // finish disjunction and maybe subquery
 519+ if ( $this->m_defaultns !== NULL ) { // possibly add namespace restrictions
 520+ if ( $hasNamespaces && !$mustSetNS ) {
 521+ // add ns restrictions to all earlier conjunctions (all of which did not have them yet)
 522+ $mustSetNS = true; // enforce NS restrictions from now on
 523+ $newdisjuncts = array();
 524+ foreach ( $disjuncts as $conj ) {
 525+ $newdisjuncts[] = $this->addDescription( $conj, $this->m_defaultns );
 526+ }
 527+ $disjuncts = $newdisjuncts;
 528+ } elseif ( !$hasNamespaces && $mustSetNS ) {
 529+ // add ns restriction to current result
 530+ $conjunction = $this->addDescription( $conjunction, $this->m_defaultns );
 531+ }
 532+ }
 533+ $disjuncts[] = $conjunction;
 534+ // start anew
 535+ $conjunction = NULL;
 536+ $hasNamespaces = false;
 537+ // finish subquery?
 538+ if ( $chunk == '</q>' ) {
 539+ if ( $this->popDelimiter( '</q>' ) ) {
 540+ $continue = false; // leave the loop
 541+ } else {
 542+ $this->m_errors[] = wfMsgForContent( 'smw_toomanyclosing', $chunk );
 543+ return NULL;
 544+ }
 545+ } elseif ( $chunk == '' ) {
 546+ $continue = false;
 547+ }
 548+ break;
 549+ case '+': // "... AND true" (ignore)
 550+ break;
 551+ default: // error: unexpected $chunk
 552+ $this->m_errors[] = wfMsgForContent( 'smw_unexpectedpart', $chunk );
 553+ // return NULL; // Try to go on, it can only get better ...
 554+ }
 555+ if ( $setsubNS ) { // namespace restrictions encountered in current conjunct
 556+ $hasNamespaces = true;
 557+ }
 558+ if ( $continue ) { // read on only if $continue remained true
 559+ $chunk = $this->readChunk();
 560+ }
 561+ }
 562+
 563+ if ( count( $disjuncts ) > 0 ) { // make disjunctive result
 564+ $result = NULL;
 565+ foreach ( $disjuncts as $d ) {
 566+ if ( $d === NULL ) {
 567+ $this->m_errors[] = wfMsgForContent( 'smw_emptysubquery' );
 568+ $setNS = false;
 569+ return NULL;
 570+ } else {
 571+ $result = $this->addDescription( $result, $d, false );
 572+ }
 573+ }
 574+ } else {
 575+ $this->m_errors[] = wfMsgForContent( 'smw_emptysubquery' );
 576+ $setNS = false;
 577+ return NULL;
 578+ }
 579+ $setNS = $mustSetNS; // NOTE: also false if namespaces were given but no default NS descs are available
 580+
 581+ $prcount = 0;
 582+ foreach ( $printrequests as $pr ) { // add printrequests
 583+ if ( $prcount < $smwgQPrintoutLimit ) {
 584+ $result->addPrintRequest( $pr );
 585+ $prcount++;
 586+ } else {
 587+ $this->m_errors[] = wfMsgForContent( 'smw_overprintoutlimit' );
 588+ break;
 589+ }
 590+ }
 591+
 592+ // added by ning
 593+ if ( $this->m_result ) {
 594+ $sStore = NMStorage::getDatabase();
 595+ $this->m_result = $sStore->addNotifyRelations( $this->m_notify_id, $relatedArticles, $subquery );
 596+ }
 597+
 598+ return $result;
 599+ }
 600+
 601+ /**
 602+ * Compute an SMWDescription for current part of a query, which should
 603+ * be the content of "[[ ... ]]". Alternatively, if the current syntax
 604+ * specifies a print request, return the print request object.
 605+ * Returns NULL upon error.
 606+ *
 607+ * Parameters $setNS and $label have the same use as in getSubqueryDescription().
 608+ */
 609+ // modified by ning, add $relatedArticles
 610+ protected function getLinkDescription( &$setNS, &$label, &$relatedArticles ) {
 611+ // This method is called when we encountered an opening '[['. The following
 612+ // block could be a Category-statement, fixed object, property statements,
 613+ // or according print statements.
 614+ $chunk = $this->readChunk( '', true, false ); // NOTE: untrimmed, initial " " escapes prop. chains
 615+ if ( ( smwfNormalTitleText( $chunk ) == $this->m_categoryprefix ) || // category statement or
 616+ ( smwfNormalTitleText( $chunk ) == $this->m_conceptprefix ) ) { // concept statement
 617+ return $this->getClassDescription( $setNS, $label, $relatedArticles,
 618+ ( smwfNormalTitleText( $chunk ) == $this->m_categoryprefix ) );
 619+ } else { // fixed subject, namespace restriction, property query, or subquery
 620+ $sep = $this->readChunk( '', false ); // do not consume hit, "look ahead"
 621+ if ( ( $sep == '::' ) || ( $sep == ':=' ) ) {
 622+ if ( $chunk { 0 } != ':' ) { // property statement
 623+ return $this->getPropertyDescription( $chunk, $setNS, $label, $relatedArticles );
 624+ } else { // escaped article description, read part after :: to get full contents
 625+ $chunk .= $this->readChunk( '\[\[|\]\]|\|\||\|' );
 626+ return $this->getArticleDescription( trim( $chunk ), $setNS, $label, $relatedArticles );
 627+ }
 628+ } else { // Fixed article/namespace restriction. $sep should be ]] or ||
 629+ return $this->getArticleDescription( trim( $chunk ), $setNS, $label, $relatedArticles );
 630+ }
 631+ }
 632+ }
 633+
 634+ /**
 635+ * Parse a category description (the part of an inline query that
 636+ * is in between "[[Category:" and the closing "]]" and create a
 637+ * suitable description.
 638+ */
 639+ // modified by ning ,add $relatedArticles
 640+ protected function getClassDescription( &$setNS, &$label, &$relatedArticles, $category = true ) {
 641+ global $smwgSMWBetaCompatible; // * printouts only for this old version
 642+ // note: no subqueries allowed here, inline disjunction allowed, wildcards allowed
 643+ $result = NULL;
 644+ $continue = true;
 645+ while ( $continue ) {
 646+ $chunk = $this->readChunk();
 647+ if ( $chunk == '+' ) {
 648+ // wildcard, ignore for categories (semantically meaningless, everything is in some class)
 649+ } elseif ( ( $chunk == '+' ) && $category && $smwgSMWBetaCompatible ) { // print statement
 650+ $chunk = $this->readChunk( '\]\]|\|' );
 651+ if ( $chunk == '|' ) {
 652+ $printlabel = $this->readChunk( '\]\]' );
 653+ if ( $printlabel != ']]' ) {
 654+ $chunk = $this->readChunk( '\]\]' );
 655+ } else {
 656+ $printlabel = '';
 657+ $chunk = ']]';
 658+ }
 659+ } else {
 660+ global $wgContLang;
 661+ $printlabel = $wgContLang->getNSText( NS_CATEGORY );
 662+ }
 663+ if ( $chunk == ']]' ) {
 664+ return new SMWPrintRequest( SMWPrintRequest::PRINT_CATS, $printlabel );
 665+ } else {
 666+ $this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
 667+ return NULL;
 668+ }
 669+ } else { // assume category/concept title
 670+ // / NOTE: use m_c...prefix to prevent problems with, e.g., [[Category:Template:Test]]
 671+ $class = Title::newFromText( ( $category ? $this->m_categoryprefix:$this->m_conceptprefix ) . $chunk );
 672+ if ( $class !== NULL ) {
 673+ $desc = $category ? new SMWClassDescription( $class ):new SMWConceptDescription( $class );
 674+ $result = $this->addDescription( $result, $desc, false );
 675+ }
 676+
 677+ // added by ning
 678+ if ( $category ) {
 679+ $relatedArticles[] = array(
 680+ 'namespace' => NS_CATEGORY,
 681+ 'title' => $class->getDBkey() );
 682+ }
 683+
 684+ }
 685+ $chunk = $this->readChunk();
 686+ $continue = ( $chunk == '||' ) && $category; // disjunctions only for cateories
 687+ }
 688+
 689+ return $this->finishLinkDescription( $chunk, false, $result, $setNS, $label );
 690+ }
 691+
 692+ /**
 693+ * Parse a property description (the part of an inline query that
 694+ * is in between "[[Some property::" and the closing "]]" and create a
 695+ * suitable description. The "::" is the first chunk on the current
 696+ * string.
 697+ */
 698+ // modified by ning ,add $relatedArticles
 699+ protected function getPropertyDescription( $propertyname, &$setNS, &$label, &$relatedArticles ) {
 700+ global $smwgSMWBetaCompatible; // support for old * printouts of beta
 701+ wfLoadExtensionMessages( 'SemanticMediaWiki' );
 702+ $this->readChunk(); // consume separator ":=" or "::"
 703+ // first process property chain syntax (e.g. "property1.property2::value"):
 704+ if ( $propertyname { 0 } == ' ' ) { // escape
 705+ $propertynames = array( $propertyname );
 706+ } else {
 707+ $propertynames = explode( '.', $propertyname );
 708+ }
 709+ $properties = array();
 710+ $typeid = '_wpg';
 711+ foreach ( $propertynames as $name ) {
 712+ if ( $typeid != '_wpg' ) { // non-final property in chain was no wikipage: not allowed
 713+ $this->m_errors[] = wfMsgForContent( 'smw_valuesubquery', $prevname );
 714+ return NULL; // /TODO: read some more chunks and try to finish [[ ]]
 715+ }
 716+ $property = SMWPropertyValue::makeUserProperty( $name );
 717+ if ( !$property->isValid() ) { // illegal property identifier
 718+ $this->m_errors = array_merge( $this->m_errors, $property->getErrors() );
 719+ return NULL; // /TODO: read some more chunks and try to finish [[ ]]
 720+ }
 721+ $typeid = $property->getTypeID();
 722+ $prevname = $name;
 723+ $properties[] = $property;
 724+
 725+ // added by ning
 726+ $relatedArticles[] = array(
 727+ 'namespace' => SMW_NS_PROPERTY,
 728+ 'title' => $property->getDBkey() );
 729+
 730+ } // /NOTE: after iteration, $property and $typeid correspond to last value
 731+
 732+ $innerdesc = NULL;
 733+ $continue = true;
 734+ while ( $continue ) {
 735+ $chunk = $this->readChunk();
 736+ switch ( $chunk ) {
 737+ case '+': // wildcard, add namespaces for page-type properties
 738+ if ( ( $this->m_defaultns !== NULL ) && ( $typeid == '_wpg' ) ) {
 739+ $innerdesc = $this->addDescription( $innerdesc, $this->m_defaultns, false );
 740+ } else {
 741+ $innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
 742+ }
 743+ $chunk = $this->readChunk();
 744+ break;
 745+ case '<q>': // subquery, set default namespaces
 746+ if ( $typeid == '_wpg' ) {
 747+ $this->pushDelimiter( '</q>' );
 748+ $setsubNS = true;
 749+ $sublabel = '';
 750+ $innerdesc = $this->addDescription( $innerdesc, $this->getSubqueryDescription( $setsubNS, $sublabel ), false );
 751+ } else { // no subqueries allowed for non-pages
 752+ $this->m_errors[] = wfMsgForContent( 'smw_valuesubquery', end( $propertynames ) );
 753+ $innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
 754+ }
 755+ $chunk = $this->readChunk();
 756+ break;
 757+ default: // normal object value or print statement
 758+ // read value(s), possibly with inner [[...]]
 759+ $open = 1;
 760+ $value = $chunk;
 761+ $continue2 = true;
 762+ // read value with inner [[, ]], ||
 763+ while ( ( $open > 0 ) && ( $continue2 ) ) {
 764+ $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
 765+ switch ( $chunk ) {
 766+ case '[[': // open new [[ ]]
 767+ $open++;
 768+ break;
 769+ case ']]': // close [[ ]]
 770+ $open--;
 771+ break;
 772+ case '|': case '||': // terminates only outermost [[ ]]
 773+ if ( $open == 1 ) {
 774+ $open = 0;
 775+ }
 776+ break;
 777+ case '': // /TODO: report error; this is not good right now
 778+ $continue2 = false;
 779+ break;
 780+ }
 781+ if ( $open != 0 ) {
 782+ $value .= $chunk;
 783+ }
 784+ } // /NOTE: at this point, we normally already read one more chunk behind the value
 785+
 786+ if ( $typeid == '__nry' ) { // nary value
 787+ $dv = SMWDataValueFactory::newPropertyObjectValue( $property );
 788+ $dv->acceptQuerySyntax();
 789+ $dv->setUserValue( $value );
 790+ $vl = $dv->getValueList();
 791+ $pm = $dv->getPrintModifier();
 792+ if ( $vl !== NULL ) { // prefer conditions over print statements (only one possible right now)
 793+ $innerdesc = $this->addDescription( $innerdesc, $vl, false );
 794+ } elseif ( $pm !== false ) {
 795+ if ( $chunk == '|' ) {
 796+ $printlabel = $this->readChunk( '\]\]' );
 797+ if ( $printlabel != ']]' ) {
 798+ $chunk = $this->readChunk( '\]\]' );
 799+ } else {
 800+ $printlabel = '';
 801+ $chunk = ']]';
 802+ }
 803+ } else {
 804+ $printlabel = $property->getWikiValue();
 805+ }
 806+ if ( $chunk == ']]' ) {
 807+ return new SMWPrintRequest( SMWPrintRequest::PRINT_PROP, $printlabel, $property, $pm );
 808+ } else {
 809+ $this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
 810+ return NULL;
 811+ }
 812+ }
 813+ } else { // unary value
 814+ $comparator = SMW_CMP_EQ;
 815+ $printmodifier = '';
 816+ SMWNotifyParser::prepareValue( $value, $comparator, $printmodifier );
 817+ if ( ( $value == '*' ) && $smwgSMWBetaCompatible ) {
 818+ if ( $chunk == '|' ) {
 819+ $printlabel = $this->readChunk( '\]\]' );
 820+ if ( $printlabel != ']]' ) {
 821+ $chunk = $this->readChunk( '\]\]' );
 822+ } else {
 823+ $printlabel = '';
 824+ $chunk = ']]';
 825+ }
 826+ } else {
 827+ $printlabel = $property->getWikiValue();
 828+ }
 829+ if ( $chunk == ']]' ) {
 830+ return new SMWPrintRequest( SMWPrintRequest::PRINT_PROP, $printlabel, $property, $printmodifier );
 831+ } else {
 832+ $this->m_errors[] = wfMsgForContent( 'smw_badprintout' );
 833+ return NULL;
 834+ }
 835+ } else {
 836+ $dv = SMWDataValueFactory::newPropertyObjectValue( $property, $value );
 837+ if ( !$dv->isValid() ) {
 838+ $this->m_errors = $this->m_errors + $dv->getErrors();
 839+ $vd = new SMWThingDescription();
 840+ } else {
 841+ $vd = new SMWValueDescription( $dv, $comparator );
 842+ }
 843+ $innerdesc = $this->addDescription( $innerdesc, $vd, false );
 844+ }
 845+ }
 846+ }
 847+ $continue = ( $chunk == '||' );
 848+ }
 849+
 850+ if ( $innerdesc === NULL ) { // make a wildcard search
 851+ if ( ( $this->m_defaultns !== NULL ) && ( $typeid == '_wpg' ) ) {
 852+ $innerdesc = $this->addDescription( $innerdesc, $this->m_defaultns, false );
 853+ } else {
 854+ $innerdesc = $this->addDescription( $innerdesc, new SMWThingDescription(), false );
 855+ }
 856+ $this->m_errors[] = wfMsgForContent( 'smw_propvalueproblem', $property->getWikiValue() );
 857+ }
 858+ $properties = array_reverse( $properties );
 859+ foreach ( $properties as $property ) {
 860+ $innerdesc = new SMWSomeProperty( $property, $innerdesc );
 861+ }
 862+ $result = $innerdesc;
 863+ return $this->finishLinkDescription( $chunk, false, $result, $setNS, $label );
 864+ }
 865+
 866+
 867+ /**
 868+ * Prepare a single value string, possibly extracting comparators and
 869+ * printmodifier. $value is changed to consist only of the remaining
 870+ * effective value string, or of "*" for print statements.
 871+ */
 872+ static public function prepareValue( &$value, &$comparator, &$printmodifier ) {
 873+ global $smwgQComparators, $smwgSMWBetaCompatible; // support for old * printouts of beta
 874+ // get print modifier behind *
 875+ if ( $smwgSMWBetaCompatible ) {
 876+ $list = preg_split( '/^\*/', $value, 2 );
 877+ if ( count( $list ) == 2 ) { // hit
 878+ $value = '*';
 879+ $printmodifier = $list[1];
 880+ } else {
 881+ $printmodifier = '';
 882+ }
 883+ if ( $value == '*' ) { // printout statement
 884+ return;
 885+ }
 886+ }
 887+ $list = preg_split( '/^(' . $smwgQComparators . ')/u', $value, 2, PREG_SPLIT_DELIM_CAPTURE );
 888+ $comparator = SMW_CMP_EQ;
 889+ if ( count( $list ) == 3 ) { // initial comparator found ($list[1] should be empty)
 890+ switch ( $list[1] ) {
 891+ case '<':
 892+ $comparator = SMW_CMP_LEQ;
 893+ $value = $list[2];
 894+ break;
 895+ case '>':
 896+ $comparator = SMW_CMP_GEQ;
 897+ $value = $list[2];
 898+ break;
 899+ case '!':
 900+ $comparator = SMW_CMP_NEQ;
 901+ $value = $list[2];
 902+ break;
 903+ case '~':
 904+ $comparator = SMW_CMP_LIKE;
 905+ $value = $list[2];
 906+ break;
 907+ // default: not possible
 908+ }
 909+ }
 910+ }
 911+
 912+ /**
 913+ * Parse an article description (the part of an inline query that
 914+ * is in between "[[" and the closing "]]" assuming it is not specifying
 915+ * a category or property) and create a suitable description.
 916+ * The first chunk behind the "[[" has already been read and is
 917+ * passed as a parameter.
 918+ */
 919+ // modified by ning ,add $relatedArticles
 920+ protected function getArticleDescription( $firstchunk, &$setNS, &$label, &$relatedArticles ) {
 921+ wfLoadExtensionMessages( 'SemanticMediaWiki' );
 922+ $chunk = $firstchunk;
 923+ $result = NULL;
 924+ $continue = true;
 925+ // $innerdesc = NULL;
 926+ while ( $continue ) {
 927+ if ( $chunk == '<q>' ) { // no subqueries of the form [[<q>...</q>]] (not needed)
 928+ $this->m_errors[] = wfMsgForContent( 'smw_misplacedsubquery' );
 929+ return NULL;
 930+ }
 931+ $list = preg_split( '/:/', $chunk, 3 ); // ":Category:Foo" "User:bar" ":baz" ":+"
 932+ if ( ( $list[0] == '' ) && ( count( $list ) == 3 ) ) {
 933+ $list = array_slice( $list, 1 );
 934+ }
 935+ if ( ( count( $list ) == 2 ) && ( $list[1] == '+' ) ) { // try namespace restriction
 936+ global $wgContLang;
 937+ $idx = $wgContLang->getNsIndex( $list[0] );
 938+ if ( $idx !== false ) {
 939+ $result = $this->addDescription( $result, new SMWNamespaceDescription( $idx ), false );
 940+ }
 941+ } else {
 942+ $value = SMWDataValueFactory::newTypeIDValue( '_wpg', $chunk );
 943+ if ( $value->isValid() ) {
 944+ $result = $this->addDescription( $result, new SMWValueDescription( $value ), false );
 945+ // added by ning
 946+ $relatedArticles[] = array(
 947+ 'namespace' => NS_MAIN,
 948+ 'title' => Title::makeTitle( NS_MAIN, $chunk )->getDBkey() );
 949+ }
 950+ }
 951+
 952+ $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
 953+ if ( $chunk == '||' ) {
 954+ $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' );
 955+ $continue = true;
 956+ } else {
 957+ $continue = false;
 958+ }
 959+ }
 960+
 961+ return $this->finishLinkDescription( $chunk, true, $result, $setNS, $label );
 962+ }
 963+
 964+ protected function finishLinkDescription( $chunk, $hasNamespaces, $result, &$setNS, &$label ) {
 965+ wfLoadExtensionMessages( 'SemanticMediaWiki' );
 966+ if ( $result === NULL ) { // no useful information or concrete error found
 967+ $this->m_errors[] = wfMsgForContent( 'smw_badqueryatom' );
 968+ } elseif ( !$hasNamespaces && $setNS && ( $this->m_defaultns !== NULL ) ) {
 969+ $result = $this->addDescription( $result, $this->m_defaultns );
 970+ $hasNamespaces = true;
 971+ }
 972+ $setNS = $hasNamespaces;
 973+
 974+ // terminate link (assuming that next chunk was read already)
 975+ if ( $chunk == '|' ) {
 976+ $chunk = $this->readChunk( '\]\]' );
 977+ if ( $chunk != ']]' ) {
 978+ $label .= $chunk;
 979+ $chunk = $this->readChunk( '\]\]' );
 980+ } else { // empty label does not add to overall label
 981+ $chunk = ']]';
 982+ }
 983+ }
 984+ if ( $chunk != ']]' ) {
 985+ // What happended? We found some chunk that could not be processed as
 986+ // link content (as in [[Category:Test<q>]]) and there was no label to
 987+ // eat it. Or the closing ]] are just missing entirely.
 988+ if ( $chunk != '' ) {
 989+ $this->m_errors[] = wfMsgForContent( 'smw_misplacedsymbol', htmlspecialchars( $chunk ) );
 990+ // try to find a later closing ]] to finish this misshaped subpart
 991+ $chunk = $this->readChunk( '\]\]' );
 992+ if ( $chunk != ']]' ) {
 993+ $chunk = $this->readChunk( '\]\]' );
 994+ }
 995+ }
 996+ if ( $chunk == '' ) {
 997+ $this->m_errors[] = wfMsgForContent( 'smw_noclosingbrackets' );
 998+ }
 999+ }
 1000+ return $result;
 1001+ }
 1002+
 1003+ /**
 1004+ * Get the next unstructured string chunk from the query string.
 1005+ * Chunks are delimited by any of the special strings used in inline queries
 1006+ * (such as [[, ]], <q>, ...). If the string starts with such a delimiter,
 1007+ * this delimiter is returned. Otherwise the first string in front of such a
 1008+ * delimiter is returned.
 1009+ * Trailing and initial spaces are ignored if $trim is true, and chunks
 1010+ * consisting only of spaces are not returned.
 1011+ * If there is no more qurey string left to process, the empty string is
 1012+ * returned (and in no other case).
 1013+ *
 1014+ * The stoppattern can be used to customise the matching, especially in order to
 1015+ * overread certain special symbols.
 1016+ *
 1017+ * $consume specifies whether the returned chunk should be removed from the
 1018+ * query string.
 1019+ */
 1020+ protected function readChunk( $stoppattern = '', $consume = true, $trim = true ) {
 1021+ if ( $stoppattern == '' ) {
 1022+ $stoppattern = '\[\[|\]\]|::|:=|<q>|<\/q>|^' . $this->m_categoryprefix .
 1023+ '|^' . $this->m_conceptprefix . '|\|\||\|';
 1024+ }
 1025+ $chunks = preg_split( '/[\s]*(' . $stoppattern . ')/u', $this->m_curstring, 2, PREG_SPLIT_DELIM_CAPTURE );
 1026+ if ( count( $chunks ) == 1 ) { // no matches anymore, strip spaces and finish
 1027+ if ( $consume ) {
 1028+ $this->m_curstring = '';
 1029+ }
 1030+ return $trim ? trim( $chunks[0] ):$chunks[0];
 1031+ } elseif ( count( $chunks ) == 3 ) { // this should generally happen if count is not 1
 1032+ if ( $chunks[0] == '' ) { // string started with delimiter
 1033+ if ( $consume ) {
 1034+ $this->m_curstring = $chunks[2];
 1035+ }
 1036+ return $trim ? trim( $chunks[1] ):$chunks[1];
 1037+ } else {
 1038+ if ( $consume ) {
 1039+ $this->m_curstring = $chunks[1] . $chunks[2];
 1040+ }
 1041+ return $trim ? trim( $chunks[0] ):$chunks[0];
 1042+ }
 1043+ } else { return false; } // should never happen
 1044+ }
 1045+
 1046+ /**
 1047+ * Enter a new subblock in the query, which must at some time be terminated by the
 1048+ * given $endstring delimiter calling popDelimiter();
 1049+ */
 1050+ protected function pushDelimiter( $endstring ) {
 1051+ array_push( $this->m_sepstack, $endstring );
 1052+ }
 1053+
 1054+ /**
 1055+ * Exit a subblock in the query ending with the given delimiter.
 1056+ * If the delimiter does not match the top-most open block, false
 1057+ * will be returned. Otherwise return true.
 1058+ */
 1059+ protected function popDelimiter( $endstring ) {
 1060+ $topdelim = array_pop( $this->m_sepstack );
 1061+ return ( $topdelim == $endstring );
 1062+ }
 1063+
 1064+ /**
 1065+ * Extend a given description by a new one, either by adding the new description
 1066+ * (if the old one is a container description) or by creating a new container.
 1067+ * The parameter $conjunction determines whether the combination of both descriptions
 1068+ * should be a disjunction or conjunction.
 1069+ *
 1070+ * In the special case that the current description is NULL, the new one will just
 1071+ * replace the current one.
 1072+ *
 1073+ * The return value is the expected combined description. The object $curdesc will
 1074+ * also be changed (if it was non-NULL).
 1075+ */
 1076+ protected function addDescription( $curdesc, $newdesc, $conjunction = true ) {
 1077+ wfLoadExtensionMessages( 'SemanticMediaWiki' );
 1078+ $notallowedmessage = 'smw_noqueryfeature';
 1079+ if ( $newdesc instanceof SMWSomeProperty ) {
 1080+ $allowed = $this->m_queryfeatures & SMW_PROPERTY_QUERY;
 1081+ } elseif ( $newdesc instanceof SMWClassDescription ) {
 1082+ $allowed = $this->m_queryfeatures & SMW_CATEGORY_QUERY;
 1083+ } elseif ( $newdesc instanceof SMWConceptDescription ) {
 1084+ $allowed = $this->m_queryfeatures & SMW_CONCEPT_QUERY;
 1085+ } elseif ( $newdesc instanceof SMWConjunction ) {
 1086+ $allowed = $this->m_queryfeatures & SMW_CONJUNCTION_QUERY;
 1087+ $notallowedmessage = 'smw_noconjunctions';
 1088+ } elseif ( $newdesc instanceof SMWDisjunction ) {
 1089+ $allowed = $this->m_queryfeatures & SMW_DISJUNCTION_QUERY;
 1090+ $notallowedmessage = 'smw_nodisjunctions';
 1091+ } else {
 1092+ $allowed = true;
 1093+ }
 1094+ if ( !$allowed ) {
 1095+ $this->m_errors[] = wfMsgForContent( $notallowedmessage, str_replace( '[', '&#x005B;', $newdesc->getQueryString() ) );
 1096+ return $curdesc;
 1097+ }
 1098+ if ( $newdesc === NULL ) {
 1099+ return $curdesc;
 1100+ } elseif ( $curdesc === NULL ) {
 1101+ return $newdesc;
 1102+ } else { // we already found descriptions
 1103+ if ( ( ( $conjunction ) && ( $curdesc instanceof SMWConjunction ) ) ||
 1104+ ( ( !$conjunction ) && ( $curdesc instanceof SMWDisjunction ) ) ) { // use existing container
 1105+ $curdesc->addDescription( $newdesc );
 1106+ return $curdesc;
 1107+ } elseif ( $conjunction ) { // make new conjunction
 1108+ if ( $this->m_queryfeatures & SMW_CONJUNCTION_QUERY ) {
 1109+ return new SMWConjunction( array( $curdesc, $newdesc ) );
 1110+ } else {
 1111+ $this->m_errors[] = wfMsgForContent( 'smw_noconjunctions', str_replace( '[', '&#x005B;', $newdesc->getQueryString() ) );
 1112+ return $curdesc;
 1113+ }
 1114+ } else { // make new disjunction
 1115+ if ( $this->m_queryfeatures & SMW_DISJUNCTION_QUERY ) {
 1116+ return new SMWDisjunction( array( $curdesc, $newdesc ) );
 1117+ } else {
 1118+ $this->m_errors[] = wfMsgForContent( 'smw_nodisjunctions', str_replace( '[', '&#x005B;', $newdesc->getQueryString() ) );
 1119+ return $curdesc;
 1120+ }
 1121+ }
 1122+ }
 1123+ }
 1124+}
 1125+
 1126+class SMWNotifyUpdate {
 1127+ protected $m_info;
 1128+ protected $m_title; // current title of the update
 1129+ protected $m_userMsgs; // user_id => plain text message
 1130+ protected $m_userHtmlPropMsgs; // user_id => html message, prop change detail
 1131+ protected $m_userHtmlNMMsgs; // user_id => html message, all notify hint
 1132+ protected $m_userNMs; // user_id => notify_id
 1133+ protected $m_notifyHtmlPropMsgs; // notify_id => html message, prop change detail
 1134+ protected $m_notifyHtmlMsgs; // notify_id => html message, all notify hint
 1135+ protected $m_newMonitor; // notify newly matches the page, array( notify id, page id )
 1136+ protected $m_removeMonitored; // notify no longer matches the page, array( notify id, page id )
 1137+ protected $m_subQueryNotify; // subquery, will go through all pages, attention!!!
 1138+
 1139+ protected $m_linker;
 1140+
 1141+ protected function getSemanticInfo( $title ) {
 1142+ $result = array();
 1143+ $sStore = NMStorage::getDatabase();
 1144+ $semdata = smwfGetStore()->getSemanticData( $title );
 1145+ foreach ( $semdata->getProperties() as $property ) {
 1146+ if ( !$property->isShown() && $property->getWikiValue() != '' ) { // showing this is not desired, hide
 1147+ continue;
 1148+ } elseif ( $property->isUserDefined() ) { // user defined property
 1149+ $property->setCaption( preg_replace( '/[ ]/u', '&#160;', $property->getWikiValue(), 2 ) );
 1150+ }
 1151+
 1152+ $propvalues = $semdata->getPropertyValues( $property );
 1153+ if ( $property->getWikiValue() != '' ) {
 1154+ foreach ( $propvalues as $propvalue ) {
 1155+ if ( $propvalue->getWikiValue() != '' ) {
 1156+ $result[SMWNotifyProcessor::toInfoId( 2, 0, $sStore->lookupSmwId( SMW_NS_PROPERTY, $property->getWikiValue() ) )][] = array( 'name' => $property, 'value' => $propvalue );
 1157+ }
 1158+ }
 1159+ } else {
 1160+ foreach ( $propvalues as $propvalue ) {
 1161+ if ( ( $propvalue instanceof SMWWikiPageValue ) && ( $propvalue->getNamespace() == NS_CATEGORY ) ) {
 1162+ $result[SMWNotifyProcessor::toInfoId( 0, 0, $sStore->lookupSmwId( NS_CATEGORY, $propvalue->getWikiValue() ) )][] = array( 'name' => $propvalue, 'value' => null );
 1163+ }
 1164+ }
 1165+ }
 1166+ }
 1167+ return $result;
 1168+ }
 1169+
 1170+ public function SMWNotifyUpdate( $title ) {
 1171+ $this->m_title = $title;
 1172+ $this->m_userMsgs = array();
 1173+ $this->m_userHtmlPropMsgs = array();
 1174+ $this->m_userHtmlNMMsgs = array();
 1175+ $this->m_userNMs = array();
 1176+ $this->m_notifyHtmlPropMsgs = array();
 1177+ $this->m_notifyHtmlMsgs = array();
 1178+ $this->m_newMonitor = array();
 1179+ $this->m_removeMonitored = array();
 1180+ $this->m_subQueryNotify = array();
 1181+ $this->m_linker = new Linker();
 1182+
 1183+ $page_id = $title->getArticleID();
 1184+ if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
 1185+ return;
 1186+ }
 1187+ $this->m_info = $this->getSemanticInfo( $this->m_title );
 1188+ }
 1189+ public function executeNotifyDelete( $reason ) {
 1190+ $page_id = $this->m_title->getArticleID();
 1191+ if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
 1192+ return;
 1193+ }
 1194+ $page_name = $this->m_title->getText() . ' (' . $this->m_title->getFullUrl() . ')';
 1195+ $page_html_name = '<a href="' . $this->m_title->getFullUrl() . '">' . htmlspecialchars( $this->m_title->getText() ) . '</a>';
 1196+
 1197+ $msg .= wfMsg( 'smw_nm_hint_delete', $page_name, $reason );
 1198+ $sStore = NMStorage::getDatabase();
 1199+ $notifications = $sStore->getMonitoredNotifications( $page_id );
 1200+
 1201+ $notifyMsgAdded = array();
 1202+ foreach ( $notifications as $user_id => $notifies ) {
 1203+ $this->m_userMsgs[$user_id] .= $msg . '\r\n( NM: ';
 1204+ $hint = wfMsg( 'smw_nm_hint_delete_html', $page_html_name, htmlspecialchars( $reason ) );
 1205+ $this->m_userHtmlNMMsgs[$user_id] .= $hint;
 1206+ $htmlMsg = '';
 1207+ $first = true;
 1208+ foreach ( $notifies as $notify_id => $notify_detail ) {
 1209+ if ( !$first ) {
 1210+ $this->m_userMsgs[$user_id] .= ', ';
 1211+ $htmlMsg .= ', ';
 1212+ } else {
 1213+ $first = false;
 1214+ }
 1215+ if ( !isset( $notifyMsgAdded[$notify_id] ) ) {
 1216+ $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
 1217+ $notifyMsgAdded[$notify_id] = true;
 1218+ }
 1219+
 1220+ $this->m_userMsgs[$user_id] .= $notify_detail['name'];
 1221+ $htmlMsg .= '<b>' . htmlspecialchars( $notify_detail['name'] ) . '</b>';
 1222+ $this->m_removeMonitored[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
 1223+
 1224+ $this->m_userNMs[$user_id][] = $notify_id;
 1225+ }
 1226+
 1227+ $this->m_userMsgs[$user_id] .= " ).";
 1228+ $this->m_userHtmlNMMsgs[$user_id] .= wfMsg( 'smw_nm_hint_notmatch_html', $htmlMsg );
 1229+ }
 1230+
 1231+ $this->notifyUsers();
 1232+ $sStore->removeNotifyMonitor( $this->m_removeMonitored );
 1233+ }
 1234+ function isEqual( $v1, $v2 ) {
 1235+ return ( strval( $v1[value]->getWikiValue() ) == strval( $v2[value]->getWikiValue() ) );
 1236+ }
 1237+ function getNotifyPlain( $info, $key ) {
 1238+ $i = SMWNotifyProcessor::getInfoFromId( $key );
 1239+ if ( $i[type] == 0 ) {
 1240+ return "\r\n'" . $info[name]->getWikiValue() . "' has been " . ( $info[sem_act] == 0 ? "deleted":"added" ) . ".";
 1241+ } else {
 1242+ $tmp = "\r\nProperty '" . $info[name]->getWikiValue() . "' has been " . ( $info[sem_act] == 0 ? "deleted.":( $info[sem_act] == 1 ? "modified":"added" ) ) . ".";
 1243+ $first = true;
 1244+ foreach ( $info[del_vals] as $val ) {
 1245+ if ( $first ) {
 1246+ $tmp .= "\r\nValue '";
 1247+ $first = false;
 1248+ } else {
 1249+ $tmp .= "', '";
 1250+ }
 1251+ $tmp .= $val[plain];
 1252+ }
 1253+ if ( !$first ) {
 1254+ $tmp .= "' deleted.";
 1255+ }
 1256+ $first = true;
 1257+ foreach ( $info[new_vals] as $val ) {
 1258+ if ( $first ) {
 1259+ $tmp .= "\r\nValue '";
 1260+ $first = false;
 1261+ } else {
 1262+ $tmp .= "', '";
 1263+ }
 1264+ $tmp .= $val[plain];
 1265+ }
 1266+ if ( !$first ) {
 1267+ $tmp .= "' added.";
 1268+ }
 1269+ return $tmp . "\r\n";
 1270+ }
 1271+ }
 1272+ function getNotifyHtml( $info, $key ) {
 1273+ $i = SMWNotifyProcessor::getInfoFromId( $key );
 1274+ if ( $i[type] == 0 ) {
 1275+ return "<td>Category</td>
 1276+ <td>" . $this->getFullLink( $info[name] ) . "</td>
 1277+ <td>" . ( $info[sem_act] == 0 ? "<font color='green'>remove</font>":"<font color='red'>cite</font>" ) . "</td>
 1278+ <td colspan='2'>N/A</td>";
 1279+ } else {
 1280+ $rows = max( count( $info[del_vals] ), count( $info[new_vals] ) );
 1281+ $tmp = "<tr><td rowspan='$rows'>Property</td>
 1282+ <td rowspan='$rows'>" . $this->getFullLink( $info[name] ) . "</td>
 1283+ <td rowspan='$rows'>" . ( $info[sem_act] == 0 ? "<font color='green'>remove</font>":( $info[sem_act] == 1 ? "<font color='blue'>modify</font>":"<font color='red'>cite</font>" ) ) . "</td>";
 1284+ for ( $idx = 0; $idx < $rows; ++$idx ) {
 1285+ if ( $idx > 0 ) {
 1286+ $tmp .= "<tr>";
 1287+ }
 1288+ $tmp .= "<td>" . ( isset( $info[del_vals][$idx] ) ? $info[del_vals][$idx][html]:"&#160;" ) . "</td>
 1289+ <td>" . ( isset( $info[new_vals][$idx] ) ? $info[new_vals][$idx][html]:"&#160;" ) . "</td>
 1290+ </tr>";
 1291+ }
 1292+ return $tmp;
 1293+ }
 1294+ }
 1295+ public function executeNotifyUpdate() {
 1296+ $page_id = $this->m_title->getArticleID();
 1297+ if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
 1298+ return;
 1299+ }
 1300+ $sStore = NMStorage::getDatabase();
 1301+
 1302+ $info = $this->getSemanticInfo( $this->m_title );
 1303+ // get different
 1304+ $tmp_info = array(); // type : category 0, property 2; name; sem action : del 0, modify 1, add 2; val action : del 0, add 1
 1305+ foreach ( $this->m_info as $key => $value ) {
 1306+ $i = SMWNotifyProcessor::getInfoFromId( $key );
 1307+ $updated = false;
 1308+ if ( !isset( $info[$key] ) ) {
 1309+ if ( $i[type] == 0 ) {
 1310+ $tmp_info[$key] = array( 'sem_act' => 0, 'name' => $value[0][name] );
 1311+ } else {
 1312+ $tmp_info[$key] = array( 'sem_act' => 0, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
 1313+ foreach ( $value as $v ) {
 1314+ $tmp_info[$key][del_vals][] = array( 'plain' => $v[value]->getWikiValue(), 'html' => $this->getFullLink( $v[value] ) );
 1315+ }
 1316+ }
 1317+ } else if ( $i[type] == 2 ) {
 1318+ $mvalue = $info[$key];
 1319+ foreach ( $value as $v1 ) {
 1320+ $found = false;
 1321+ foreach ( $mvalue as $v2 ) {
 1322+ if ( $this->isEqual( $v1, $v2 ) ) {
 1323+ $found = true;
 1324+ break;
 1325+ }
 1326+ }
 1327+ if ( !$found ) {
 1328+ if ( !$updated ) {
 1329+ $updated = true;
 1330+ $tmp_info[$key] = array( 'sem_act' => 1, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
 1331+ }
 1332+ $tmp_info[$key][del_vals][] = array( 'plain' => $v1[value]->getWikiValue(), 'html' => $this->getFullLink( $v1[value] ) );
 1333+ }
 1334+ }
 1335+ foreach ( $mvalue as $v1 ) {
 1336+ $found = false;
 1337+ foreach ( $value as $v2 ) {
 1338+ if ( $this->isEqual( $v1, $v2 ) ) {
 1339+ $found = true;
 1340+ break;
 1341+ }
 1342+ }
 1343+ if ( !$found ) {
 1344+ if ( !$updated ) {
 1345+ $updated = true;
 1346+ $tmp_info[$key] = array( 'sem_act' => 1, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
 1347+ }
 1348+ $tmp_info[$key][new_vals][] = array( 'plain' => $v1[value]->getWikiValue(), 'html' => $this->getFullLink( $v1[value] ) );
 1349+ }
 1350+ }
 1351+ }
 1352+ }
 1353+ foreach ( $info as $key => $value ) {
 1354+ $i = SMWNotifyProcessor::getInfoFromId( $key );
 1355+ if ( !isset( $this->m_info[$key] ) ) {
 1356+ if ( $i[type] == 0 ) {
 1357+ $tmp_info[$key] = array( 'sem_act' => 2, 'name' => $value[0][name] );
 1358+ } else {
 1359+ $tmp_info[$key] = array( 'sem_act' => 2, 'name' => $value[0][name], 'del_vals' => array(), 'new_vals' => array() );
 1360+ foreach ( $value as $v ) {
 1361+ $tmp_info[$key][new_vals][] = array( 'plain' => $v[value]->getWikiValue(), 'html' => $this->getFullLink( $v[value] ) );
 1362+ }
 1363+ }
 1364+ }
 1365+ }
 1366+
 1367+ $notifications = $sStore->getMonitoredNotificationsDetail( $page_id );
 1368+ // add semantic info to report all NM
 1369+ foreach ( $notifications as $user_id => $notifies ) {
 1370+ foreach ( $notifies['rep_all'] as $notify_id => $notify_name ) {
 1371+ foreach ( array_keys( $tmp_info ) as $key ) {
 1372+ $notifications[$user_id]['semantic'][$key][$notify_id] = $notify_name;
 1373+ }
 1374+ }
 1375+ }
 1376+ $page_name = $this->m_title->getText() . ' (' . $this->m_title->getFullUrl() . ')';
 1377+
 1378+ $notifyMsgAdded = array();
 1379+ foreach ( $notifications as $user_id => $notifies ) {
 1380+ if ( !isset( $notifies['semantic'] ) ) continue;
 1381+ foreach ( $notifies['semantic'] as $key => $notify ) {
 1382+ if ( isset( $tmp_info[$key] ) ) {
 1383+ $hint = "";
 1384+ if ( !isset( $this->m_userMsgs[$user_id] ) ) {
 1385+ $this->m_userMsgs[$user_id] = wfMsg( 'smw_nm_hint_change', $page_name );
 1386+ $hint = wfMsg( 'smw_nm_hint_change_html', $this->m_title->getFullUrl(), htmlspecialchars( $this->m_title->getText() ) );
 1387+ $this->m_userHtmlNMMsgs[$user_id] .= $hint;
 1388+ }
 1389+
 1390+ $this->m_userMsgs[$user_id] .= $this->getNotifyPlain( $tmp_info[$key], $key ) . ' ( NM: ';
 1391+ $propHint = $this->getNotifyHtml( $tmp_info[$key], $key );
 1392+ $this->m_userHtmlPropMsgs[$user_id] .= $propHint . "<tr><td colspan='5'>" . wfMsg( 'smw_notifyme' ) . ": ";
 1393+ $first = true;
 1394+ foreach ( $notify as $notify_id => $notify_name ) {
 1395+ if ( !$first ) {
 1396+ $this->m_userMsgs[$user_id] .= ', ';
 1397+ $this->m_userHtmlPropMsgs[$user_id] .= ', ';
 1398+ } else {
 1399+ $first = false;
 1400+ }
 1401+ $this->m_userMsgs[$user_id] .= $notify_name;
 1402+ $this->m_userHtmlPropMsgs[$user_id] .= '<b>' . htmlspecialchars( $notify_name ) . '</b>';
 1403+
 1404+ if ( !isset( $notifyMsgAdded[$notify_id] ) ) {
 1405+ $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
 1406+ }
 1407+ if ( !isset( $notifyMsgAdded[$notify_id][$key] ) ) {
 1408+ $this->m_notifyHtmlPropMsgs[$notify_id] .= $propHint;
 1409+ $notifyMsgAdded[$notify_id][$key] = true;
 1410+ }
 1411+
 1412+ $this->m_userNMs[$user_id][] = $notify_id;
 1413+ }
 1414+ $this->m_userMsgs[$user_id] .= ' ).';
 1415+ $this->m_userHtmlPropMsgs[$user_id] .= "</td></tr>";
 1416+ }
 1417+ }
 1418+ }
 1419+ // get possible subquery
 1420+ $this->m_subQueryNotify = array();
 1421+ $queries = $sStore->getPossibleQuery( $this->m_info );
 1422+ if ( is_array( $queries ) ) {
 1423+ foreach ( $queries[1] as $notify_id => $notify ) {
 1424+ $this->m_subQueryNotify[$notify_id] = $notify;
 1425+ }
 1426+ }
 1427+
 1428+ $this->m_info = $info;
 1429+ }
 1430+
 1431+ // this will cost time, think we can update monitor in a single thread, like Job
 1432+ public function updateNotifyMonitor() {
 1433+ $page_id = $this->m_title->getArticleID();
 1434+ if ( ( $page_id == 0 ) || ( $this->m_title->getNamespace() != NS_MAIN ) ) {
 1435+ return;
 1436+ }
 1437+ $sStore = NMStorage::getDatabase();
 1438+ $queries = $sStore->getPossibleQuery( $this->m_info );
 1439+ if ( !is_array( $queries ) ) {
 1440+ return;
 1441+ }
 1442+ // get monitored query
 1443+ $main_queries = $sStore->getMonitoredQuery( $page_id );
 1444+ foreach ( $queries[0] as $notify_id => $notify ) {
 1445+ $main_queries[$notify_id] = $notify;
 1446+ }
 1447+
 1448+ // begin notify query on main query
 1449+ $page_name = $this->m_title->getText() . ' (' . $this->m_title->getFullUrl() . ')';
 1450+ $page_html_name = '<a href="' . $this->m_title->getFullUrl() . '">' . htmlspecialchars( $this->m_title->getText() ) . '</a>';
 1451+
 1452+ foreach ( $main_queries as $notify_id => $notify ) {
 1453+ $sStore->getNotifyInMainQuery( $page_id, $notify_id, $notify['sql'], $notify['hierarchy'], $match, $monitoring );
 1454+ if ( ( !$monitoring ) && $match ) {
 1455+ $hint = wfMsg( 'smw_nm_hint_match_html', $page_html_name, htmlspecialchars( $notify[name] ) );
 1456+ foreach ( $notify['user_ids'] as $uid ) {
 1457+ $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_match', $page_name, $notify[name] );
 1458+ $this->m_userHtmlNMMsgs[$uid] .= $hint;
 1459+ }
 1460+ $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
 1461+ $this->m_newMonitor[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
 1462+ } else if ( ( !$match ) && $monitoring ) {
 1463+ $hint = wfMsg( 'smw_nm_hint_nomatch_html', $page_html_name, htmlspecialchars( $notify[name] ) );
 1464+ foreach ( $notify['user_ids'] as $uid ) {
 1465+ $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_nomatch', $page_name, $notify[name] );
 1466+ $this->m_userHtmlNMMsgs[$uid] .= $hint;
 1467+ }
 1468+ $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
 1469+ $this->m_removeMonitored[] = array( 'notify_id' => $notify_id, 'page_id' => $page_id );
 1470+ }
 1471+ foreach ( $notify['user_ids'] as $uid ) {
 1472+ $this->m_userNMs[$uid][] = $notify_id;
 1473+ }
 1474+ }
 1475+ // begin notify query on sub query, should go through all pages
 1476+ foreach ( $queries[1] as $notify_id => $notify ) {
 1477+ $this->m_subQueryNotify[$notify_id] = $notify;
 1478+ }
 1479+ foreach ( $this->m_subQueryNotify as $notify_id => $notify ) {
 1480+ $res = $sStore->getNotifyInSubquery( $notify_id, $notify['sql'], $notify['hierarchy'] );
 1481+
 1482+ $no_matches = array_diff( $res['monitoring'], $res['match'] );
 1483+ $matches = array_diff( $res['match'], $res['monitoring'] );
 1484+ foreach ( $matches as $pid ) {
 1485+ $pt = $sStore->getPageTitle( $pid );
 1486+ if ( !$pt ) {
 1487+ continue;
 1488+ }
 1489+ $t = Title::makeTitle( NS_MAIN, $pt->page_title );
 1490+ $p_name = $t->getText() . ' (' . $t->getFullUrl() . ')';
 1491+ $p_html_name = '<a href="' . $t->getFullUrl() . '">' . htmlspecialchars( $t->getText() ) . '</a>';
 1492+
 1493+ $hint = wfMsg( 'smw_nm_hint_submatch_html', $page_html_name, $p_html_name, htmlspecialchars( $notify[name] ) );
 1494+ foreach ( $notify['user_ids'] as $uid ) {
 1495+ $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_submatch', $page_name, $p_name, $notify[name] );
 1496+ $this->m_userHtmlNMMsgs[$uid] .= $hint;
 1497+ }
 1498+ $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
 1499+ $this->m_newMonitor[] = array( 'notify_id' => $notify_id, 'page_id' => $pid );
 1500+
 1501+ foreach ( $notify['user_ids'] as $uid ) {
 1502+ $this->m_userNMs[$uid][] = $notify_id;
 1503+ }
 1504+ }
 1505+ foreach ( $no_matches as $pid ) {
 1506+ $pt = $sStore->getPageTitle( $pid );
 1507+ if ( !$pt ) {
 1508+ continue;
 1509+ }
 1510+ $t = Title::makeTitle( NS_MAIN, $pt->page_title );
 1511+ $p_name = $t->getText() . ' (' . $t->getFullUrl() . ')';
 1512+ $p_html_name = '<a href="' . $t->getFullUrl() . '">' . htmlspecialchars( $t->getText() ) . '</a>';
 1513+
 1514+ $hint = wfMsg( 'smw_nm_hint_subnomatch_html', $page_html_name, $p_html_name, htmlspecialchars( $notify[name] ) );
 1515+ foreach ( $notify['user_ids'] as $uid ) {
 1516+ $this->m_userMsgs[$uid] .= wfMsg( 'smw_nm_hint_subnomatch', $page_name, $p_name, $notify[name] );
 1517+ $this->m_userHtmlNMMsgs[$uid] .= $hint;
 1518+ }
 1519+ $this->m_notifyHtmlMsgs[$notify_id] .= $hint;
 1520+ $this->m_removeMonitored[] = array( 'notify_id' => $notify_id, 'page_id' => $pid );
 1521+
 1522+ foreach ( $notify['user_ids'] as $uid ) {
 1523+ $this->m_userNMs[$uid][] = $notify_id;
 1524+ }
 1525+ }
 1526+ }
 1527+
 1528+ $sStore->removeNotifyMonitor( $this->m_removeMonitored );
 1529+ $sStore->addNotifyMonitor( $this->m_newMonitor );
 1530+ }
 1531+ private function getFullLink( $val ) {
 1532+ if ( $val instanceof SMWWikiPageValue ) {
 1533+ return '<a href="' . $val->getTitle()->getFullUrl() . '">' . htmlspecialchars( $val->getTitle()->getText() ) . '</a>';
 1534+ } else if ( $val instanceof SMWPropertyValue ) {
 1535+ $val = $val->getWikiPageValue();
 1536+ return '<a href="' . $val->getTitle()->getFullUrl() . '">' . htmlspecialchars( $val->getTitle()->getText() ) . '</a>';
 1537+ } else {
 1538+ return $val->getShortHTMLText( $this->m_linker );
 1539+ }
 1540+ }
 1541+ private function applyStyle( $html ) {
 1542+ $html = str_replace( "class=\"smwtable\"", "style=\"background-color: #EEEEFF;\"", $html );
 1543+ $html = str_replace( "<th", "<th style=\"background-color: #EEEEFF;text-align: left;\"", $html );
 1544+ $html = str_replace( "<td", "<td style=\"background-color: #FFFFFF;padding: 1px;padding-left: 5px;padding-right: 5px;text-align: left;vertical-align: top;\"", $html );
 1545+ return $html;
 1546+ }
 1547+ public function notifyUsers() {
 1548+ global $wgSitename, $wgSMTP, $wgEmergencyContact, $wgEnotifyMeJob;
 1549+ $sStore = NMStorage::getDatabase();
 1550+
 1551+ $nm_send_jobs = array();
 1552+ $id = 0;
 1553+
 1554+ if ( count( $this->m_notifyHtmlMsgs ) > 0 ) {
 1555+ $notifications = $sStore->getNotifyMe( array_keys( $this->m_notifyHtmlMsgs ) );
 1556+ }
 1557+ $html_style = '';
 1558+ // <style>
 1559+ // table.smwtable{background-color: #EEEEFF;}
 1560+ // table.smwtable th{background-color: #EEEEFF;text-align: left;}
 1561+ // table.smwtable td{background-color: #FFFFFF;padding: 1px;padding-left: 5px;padding-right: 5px;text-align: left;vertical-align: top;}
 1562+ // table.smwtable tr.smwfooter td{font-size: 90%;line-height: 1;background-color: #EEEEFF;padding: 0px;padding-left: 5px;padding-right: 5px;text-align: right;vertical-align: top;}
 1563+ // </style>';
 1564+ $html_showall = array();
 1565+ foreach ( $this->m_notifyHtmlMsgs as $notify_id => $msg ) {
 1566+ $html_msg = $html_style;
 1567+ $showing_all = false;
 1568+ if ( isset( $notifications[$notify_id] ) && $notifications[$notify_id]['show_all'] ) {
 1569+ SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $notifications[$notify_id]['query'] ), $querystring, $params, $printouts );
 1570+
 1571+ $format = 'auto';
 1572+ if ( array_key_exists( 'format', $params ) ) {
 1573+ $format = strtolower( trim( $params['format'] ) );
 1574+ global $smwgResultFormats;
 1575+ if ( !array_key_exists( $format, $smwgResultFormats ) ) {
 1576+ $format = 'auto';
 1577+ }
 1578+ }
 1579+ $query = SMWQueryProcessor::createQuery( $querystring, $params, SMWQueryProcessor::INLINE_QUERY, $format, $printouts );
 1580+ $res = smwfGetStore()->getQueryResult( $query );
 1581+ $printer = SMWQueryProcessor::getResultPrinter( $format, SMWQueryProcessor::INLINE_QUERY, $res );
 1582+ $result = $printer->getResult( $res, $params, SMW_OUTPUT_HTML );
 1583+ $html_msg .= $result . '<br/>';
 1584+ $html_showall[$notify_id] = array ( 'name' => $notifications[$notify_id]['name'], 'html' => $result );
 1585+
 1586+ $showing_all = true;
 1587+ $link = $res->getQueryLink()->getURL();
 1588+ }
 1589+ global $smwgNMHideDiffWhenShowAll;
 1590+ if ( !( $smwgNMHideDiffWhenShowAll && $showing_all ) ) {
 1591+ $html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_notifyHtmlMsgs[$notify_id] );
 1592+ if ( isset( $this->m_notifyHtmlPropMsgs[$notify_id] ) ) {
 1593+ $html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_notifyHtmlPropMsgs[$notify_id] );
 1594+ }
 1595+ }
 1596+ if ( $showing_all ) {
 1597+ $id = $sStore->addNotifyRSS( 'nid', $notify_id, "All current items, " . date( 'Y-m-d H:i:s', time() ), $this->applyStyle( $html_msg ), $link );
 1598+ } else {
 1599+ $id = $sStore->addNotifyRSS( 'nid', $notify_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );
 1600+ }
 1601+ }
 1602+ foreach ( $this->m_userMsgs as $user_id => $msg ) {
 1603+ // generate RSS items
 1604+ $html_msg = $html_style;
 1605+ foreach ( array_unique( $this->m_userNMs[$user_id] ) as $showall_nid ) {
 1606+ if ( isset( $html_showall[$showall_nid] ) ) {
 1607+ $html_msg .= wfMsg( 'smw_nm_hint_item_html', $html_showall[$showall_nid]['name'], $html_showall[$showall_nid]['html'] );
 1608+ }
 1609+ }
 1610+
 1611+ $html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_userHtmlNMMsgs[$user_id] );
 1612+ if ( isset( $this->m_userHtmlPropMsgs[$user_id] ) ) {
 1613+ $html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_userHtmlPropMsgs[$user_id] );
 1614+ }
 1615+
 1616+ global $wgNMReportModifier, $wgUser;
 1617+ if ( $wgNMReportModifier ) {
 1618+ $userText = $wgUser->getName();
 1619+ if ( $wgUser->getId() == 0 ) {
 1620+ $page = SpecialPage::getTitleFor( 'Contributions', $userText );
 1621+ } else {
 1622+ $page = Title::makeTitle( NS_USER, $userText );
 1623+ }
 1624+ $l = '<a href="' . $page->getFullUrl() . '">' . htmlspecialchars( $userText ) . '</a>';
 1625+ $html_msg .= wfMsg( 'smw_nm_hint_modifier_html', $l );
 1626+ $msg .= wfMsg( 'smw_nm_hint_modifier', $wgUser->getName() );
 1627+ }
 1628+
 1629+ $id = $sStore->addNotifyRSS( 'uid', $user_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );
 1630+
 1631+ if ( $wgEnotifyMeJob ) {
 1632+ // send notifications by mail
 1633+ $user_info = $sStore->getUserInfo( $user_id );
 1634+ if ( ( $user_info->user_email != '' ) && $this->getUserNMOption( $user_info->user_options ) ) {
 1635+ $name = ( ( $user_info->user_real_name == '' ) ? $user_info->user_name:$user_info->user_real_name );
 1636+
 1637+ $params = array( 'to' => new MailAddress( $user_info->user_email, $name ),
 1638+ 'from' => new MailAddress( $wgEmergencyContact, 'Admin' ),
 1639+ 'subj' => wfMsg( 'smw_nm_hint_mail_title', $this->m_title->getText(), $wgSitename ),
 1640+ 'body' => wfMsg( 'smw_nm_hint_mail_body', $name, $msg ),
 1641+ 'replyto' => new MailAddress( $wgEmergencyContact, 'Admin' ) );
 1642+
 1643+ $nm_send_jobs[] = new SMW_NMSendMailJob( $this->m_title, $params );
 1644+ }
 1645+ }
 1646+ }
 1647+
 1648+ if ( $wgEnotifyMeJob ) {
 1649+ if ( count( $nm_send_jobs ) ) {
 1650+ Job :: batchInsert( $nm_send_jobs );
 1651+ }
 1652+ } else {
 1653+ global $phpInterpreter;
 1654+ if ( !isset( $phpInterpreter ) ) {
 1655+ // if $phpInterpreter is not set, assume it is in search path
 1656+ // if not, starting of bot will FAIL!
 1657+ $phpInterpreter = "php";
 1658+ }
 1659+ // copy from SMW_GardeningBot.php
 1660+ ob_start();
 1661+ phpinfo();
 1662+ $info = ob_get_contents();
 1663+ ob_end_clean();
 1664+ // Get Systemstring
 1665+ preg_match( '!\nSystem(.*?)\n!is', strip_tags( $info ), $ma );
 1666+ // Check if it consists 'windows' as string
 1667+ preg_match( '/[Ww]indows/', $ma[1], $os );
 1668+ global $smwgNMIP ;
 1669+ if ( $os[0] == '' && $os[0] == null ) {
 1670+
 1671+ // FIXME: $runCommand must allow whitespaces in paths too
 1672+ $runCommand = "$phpInterpreter -q $smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php";
 1673+ // TODO: test async code for linux.
 1674+ // low prio
 1675+ $nullResult = `$runCommand > /dev/null &`;
 1676+ }
 1677+ else // windowze
 1678+ {
 1679+ $runCommand = "\"\"$phpInterpreter\" -q \"$smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php\"\"";
 1680+ $wshShell = new COM( "WScript.Shell" );
 1681+ $runCommand = "cmd /C " . $runCommand;
 1682+
 1683+ $oExec = $wshShell->Run( $runCommand, 7, false );
 1684+ }
 1685+ }
 1686+ }
 1687+ // copy from user class
 1688+ function getUserNMOption( $str ) {
 1689+ $options = array();
 1690+ $a = explode( "\n", $str );
 1691+ foreach ( $a as $s ) {
 1692+ $m = array();
 1693+ if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
 1694+ $options[$m[1]] = $m[2];
 1695+ }
 1696+ }
 1697+ return $options['enotifyme'];
 1698+ }
 1699+}
Property changes on: trunk/extensions/SemanticNotifyMe/includes/SMW_NotifyProcessor.smw15.php
___________________________________________________________________
Added: svn:eol-style
17001700 + native
Index: trunk/extensions/SemanticNotifyMe/includes/storage/SMW_SQLStore2_QueriesNM.smw15.php
@@ -1,943 +1,943 @@
2 -<?php
3 -/**
4 - * Query answering functions for SMWSQLStore2. Separated frmo main code for readability and
5 - * for avoiding twice the amount of code being required on every use of a simple storage function.
6 - *
7 - * based on SMW, SMW_SQLStore2_Queries.php, apply query parser to NotifyMe
8 - *
9 - * @author ning
10 - */
11 -if ( !defined( 'MEDIAWIKI' ) ) {
12 - exit( 1 );
13 -}
14 -
15 -global $smwgIP;
16 -include_once( "$smwgIP/includes/storage/SMW_SQLStore2_Queries.php" );
17 -
18 -/**
19 - * Class that implements query answering for SMWSQLStore2.
20 - */
21 -class SMWSQLStore2QueryEngineNM {
22 -
23 - /** Database slave to be used */
24 - protected $m_dbs; // TODO: should temporary tables be created on the master DB?
25 - /** Parent SMWSQLStore2. */
26 - protected $m_store;
27 - /** Query mode copied from given query. Some submethods act differently when in SMWQuery::MODE_DEBUG. */
28 - protected $m_qmode;
29 - /** Array of generated SMWSQLStore2Query query descriptions (index => object). */
30 - protected $m_queries = array();
31 - /** Array of arrays of executed queries, indexed by the temporary table names results were fed into. */
32 - protected $m_querylog = array();
33 - /**
34 - * Array of sorting requests ("Property_name" => "ASC"/"DESC"). Used during query
35 - * processing (where these property names are searched while compiling the query
36 - * conditions).
37 - */
38 - protected $m_sortkeys;
39 - /** Cache of computed hierarchy queries for reuse ("catetgory/property value string" => "tablename"). */
40 - protected $m_hierarchies = array();
41 - /** Local collection of error strings, passed on to callers if possible. */
42 - protected $m_errors = array();
43 -
44 - public function __construct( &$parentstore, &$dbslave ) {
45 - $this->m_store = $parentstore;
46 - $this->m_dbs = $dbslave;
47 - }
48 -
49 - /**
50 - * Refresh the concept cache for the given concept.
51 - *
52 - * @param $concept Title
53 - */
54 - public function refreshConceptCache( $concept ) {
55 - global $smwgQMaxLimit, $smwgQConceptFeatures, $wgDBtype;
56 -
57 - $cid = $this->m_store->getSMWPageID( $concept->getDBkey(), SMW_NS_CONCEPT, '' );
58 - $cid_c = $this->m_store->getSMWPageID( $concept->getDBkey(), SMW_NS_CONCEPT, '', false );
59 -
60 - if ( $cid != $cid_c ) {
61 - $this->m_errors[] = "Skipping redirect concept.";
62 - return $this->m_errors;
63 - }
64 -
65 - $dv = end( $this->m_store->getPropertyValues( $concept, SMWPropertyValue::makeProperty( '_CONC' ) ) );
66 - $desctxt = ( $dv !== false ) ? $dv->getWikiValue():false;
67 - $this->m_errors = array();
68 -
69 - if ( $desctxt ) { // concept found
70 - $this->m_qmode = SMWQuery::MODE_INSTANCES;
71 - $this->m_queries = array();
72 - $this->m_hierarchies = array();
73 - $this->m_querylog = array();
74 - $this->m_sortkeys = array();
75 - SMWSQLStore2Query::$qnum = 0;
76 -
77 - // Pre-process query:
78 - $qp = new SMWQueryParser( $smwgQConceptFeatures );
79 - $desc = $qp->getQueryDescription( $desctxt );
80 - $qid = $this->compileQueries( $desc );
81 -
82 - $this->executeQueries( $this->m_queries[$qid] ); // execute query tree, resolve all dependencies
83 - $qobj = $this->m_queries[$qid];
84 -
85 - if ( $qobj->joinfield === '' ) {
86 - return;
87 - }
88 -
89 - // Update database:
90 - $this->m_dbs->delete( 'smw_conccache', array( 'o_id' => $cid ), 'SMW::refreshConceptCache' );
91 -
92 - if ( $wgDBtype == 'postgres' ) { // PostgresQL: no INSERT IGNORE, check for duplicates explicitly
93 - $where = $qobj->where . ( $qobj->where ? ' AND ':'' ) .
94 - 'NOT EXISTS (SELECT NULL FROM ' . $this->m_dbs->tableName( 'smw_conccache' ) .
95 - ' WHERE ' . $this->m_dbs->tablename( 'smw_conccache' ) . '.s_id = ' . $qobj->alias . '.s_id ' .
96 - ' AND ' . $this->m_dbs->tablename( 'smw_conccache' ) . '.o_id = ' . $qobj->alias . '.o_id )';
97 - } else { // MySQL just uses INSERT IGNORE, no extra conditions
98 - $where = $qobj->where;
99 - }
100 -
101 - $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? "":"IGNORE " ) . "INTO " . $this->m_dbs->tableName( 'smw_conccache' ) .
102 - " SELECT DISTINCT $qobj->joinfield AS s_id, $cid AS o_id FROM " .
103 - $this->m_dbs->tableName( $qobj->jointable ) . " AS $qobj->alias" . $qobj->from .
104 - ( $where ? " WHERE ":'' ) . $where . " LIMIT $smwgQMaxLimit",
105 - 'SMW::refreshConceptCache' );
106 -
107 - $this->m_dbs->update( 'smw_conc2', array( 'cache_date' => strtotime( "now" ), 'cache_count' => $this->m_dbs->affectedRows() ), array( 's_id' => $cid ), 'SMW::refreshConceptCache' );
108 - } else { // just delete old data if there is any
109 - $this->m_dbs->delete( 'smw_conccache', array( 'o_id' => $cid ), 'SMW::refreshConceptCache' );
110 - $this->m_dbs->update( 'smw_conc2', array( 'cache_date' => null, 'cache_count' => null ), array( 's_id' => $cid ), 'SMW::refreshConceptCache' );
111 - $this->m_errors[] = "No concept description found.";
112 - }
113 -
114 - $this->cleanUp();
115 -
116 - return $this->m_errors;
117 - }
118 -
119 - /**
120 - * Delete the concept cache for the given concept.
121 - *
122 - * @param $concept Title
123 - */
124 - public function deleteConceptCache( $concept ) {
125 - $cid = $this->m_store->getSMWPageID( $concept->getDBkey(), SMW_NS_CONCEPT, '', false );
126 - $this->m_dbs->delete( 'smw_conccache', array( 'o_id' => $cid ), 'SMW::refreshConceptCache' );
127 - $this->m_dbs->update( 'smw_conc2', array( 'cache_date' => null, 'cache_count' => null ), array( 's_id' => $cid ), 'SMW::refreshConceptCache' );
128 - }
129 -
130 - /**
131 - * The new SQL store's implementation of query answering. This function
132 - * works in two stages: First, the nested conditions of the given query
133 - * object are preprocessed to compute an abstract representation of the
134 - * SQL query that is to be executed. Since query conditions correspond to
135 - * joins with property tables in most cases, this abstract representation
136 - * is essentially graph-like description of how property tables are joined.
137 - * Moreover, this graph is tree-shaped, since all query conditions are
138 - * tree-shaped. Each part of this abstract query structure is represented
139 - * by an SMWSQLStore2Query object in the array m_queries.
140 - *
141 - * As a second stage of processing, the thus prepared SQL query is actually
142 - * executed. Typically, this means that the joins are collapsed into one
143 - * SQL query to retrieve results. In some cases, such as in dbug mode, the
144 - * execution might be restricted and not actually perform the whole query.
145 - *
146 - * The two-stage process helps to separate tasks, and it also allows for
147 - * better optimisations: it is left to the execution engine how exactly the
148 - * query result is to be obtained. For example, one could pre-compute
149 - * partial suib-results in temporary tables (or even cache them somewhere),
150 - * instead of passing one large join query to the DB (of course, it might
151 - * be large only if the configuration of SMW allows it). For some DBMS, a
152 - * step-wise execution of the query might lead to better performance, since
153 - * it exploits the tree-structure of the joins, which is important for fast
154 - * processing -- not all DBMS might be able in seeing this by themselves.
155 - *
156 - * @param SMWQuery $query
157 - */
158 - public function getQueryResult( SMWQuery $query ) {
159 - global $smwgIgnoreQueryErrors, $smwgQSortingSupport;
160 -
161 - if ( !$smwgIgnoreQueryErrors && ( $query->querymode != SMWQuery::MODE_DEBUG ) && ( count( $query->getErrors() ) > 0 ) ) {
162 - return new SMWQueryResult( $query->getDescription()->getPrintrequests(), $query, array(), $this->m_store, false );
163 - // NOTE: we check this here to prevent unnecessary work, but we check it after query processing below again in case more errors occurred
164 - } elseif ( $query->querymode == SMWQuery::MODE_NONE ) { // don't query, but return something to printer
165 - return new SMWQueryResult( $query->getDescription()->getPrintrequests(), $query, array(), $this->m_store, true );
166 - }
167 -
168 - $this->m_qmode = $query->querymode;
169 - $this->m_queries = array();
170 - $this->m_hierarchies = array();
171 - $this->m_querylog = array();
172 - $this->m_errors = array();
173 - SMWSQLStore2Query::$qnum = 0;
174 - $this->m_sortkeys = $query->sortkeys;
175 -
176 - // *** First compute abstract representation of the query (compilation) ***//
177 - wfProfileIn( 'SMWSQLStore2Queries::compileMainQuery (SMW)' );
178 - $qid = $this->compileQueries( $query->getDescription() ); // compile query, build query "plan"
179 - wfProfileOut( 'SMWSQLStore2Queries::compileMainQuery (SMW)' );
180 -
181 - if ( $qid < 0 ) { // no valid/supported condition; ensure that at least only proper pages are delivered
182 - $qid = SMWSQLStore2Query::$qnum;
183 - $q = new SMWSQLStore2Query();
184 - $q->jointable = 'smw_ids';
185 - $q->joinfield = "$q->alias.smw_id";
186 - $q->where = "$q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWIW ) . " AND $q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWREDIIW ) . " AND $q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWBORDERIW ) . " AND $q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWINTDEFIW );
187 - $this->m_queries[$qid] = $q;
188 - }
189 -
190 - if ( $this->m_queries[$qid]->jointable != 'smw_ids' ) {
191 - // manually make final root query (to retrieve namespace,title):
192 - $rootid = SMWSQLStore2Query::$qnum;
193 - $qobj = new SMWSQLStore2Query();
194 - $qobj->jointable = 'smw_ids';
195 - $qobj->joinfield = "$qobj->alias.smw_id";
196 - $qobj->components = array( $qid => "$qobj->alias.smw_id" );
197 - $qobj->sortfields = $this->m_queries[$qid]->sortfields;
198 - $this->m_queries[$rootid] = $qobj;
199 - } else { // not such a common case, but worth avoiding the additional inner join:
200 - $rootid = $qid;
201 - }
202 -
203 - // commented by ning, no need to sort
204 -// // Include order conditions (may extend query if needed for sorting):
205 -// if ( $smwgQSortingSupport ) {
206 -// $this->applyOrderConditions( $rootid );
207 -// }
208 -
209 - if ( !$smwgIgnoreQueryErrors && ( $query->querymode != SMWQuery::MODE_DEBUG ) && ( count( $this->m_errors ) > 0 ) ) { // stop here if new errors happened
210 - $query->addErrors( $this->m_errors );
211 - return new SMWQueryResult( $query->getDescription()->getPrintrequests(), $query, array(), $this->m_store, false );
212 - }
213 -
214 - // *** Now execute the computed query ***//
215 - wfProfileIn( 'SMWSQLStore2Queries::executeMainQuery (SMW)' );
216 - $this->executeQueries( $this->m_queries[$rootid] ); // execute query tree, resolve all dependencies
217 - wfProfileOut( 'SMWSQLStore2Queries::executeMainQuery (SMW)' );
218 -
219 - $result = $this->getNMQueryResult( $query, $rootid );
220 -
221 - $this->cleanUp();
222 - $query->addErrors( $this->m_errors );
223 -
224 - return $result;
225 - }
226 -
227 - /**
228 - * Using a preprocessed internal query description referenced by $rootid, compute
229 - * the proper debug output for the given query.
230 - *
231 - * @param SMWQuery $query
232 - * @param integer $rootid
233 - */
234 - // modified by ning, based on getDebugQueryResult, getInstanceQueryResult
235 - protected function getNMQueryResult( SMWQuery $query, $rootid ) {
236 - wfProfileIn( 'SMWSQLStore2Queries::getNMQueryResult (SMW)' );
237 - $qobj = $this->m_queries[$rootid];
238 -
239 - if ( $qobj->joinfield !== '' ) {
240 - $sql = "SELECT DISTINCT $qobj->alias.smw_title AS t,$qobj->alias.smw_namespace AS ns FROM " .
241 - $this->m_dbs->tableName( $qobj->jointable ) . " AS $qobj->alias" . $qobj->from .
242 - ( ( $qobj->where == '' ) ? '':' WHERE ' ) . $qobj->where;
243 - } else { // empty result, no query needed
244 - wfProfileOut( 'SMWSQLStore2Queries::getNMQueryResult (SMW)' );
245 - return false;
246 - }
247 -
248 - $tmp = '';
249 - foreach ( $this->m_querylog as $table => $log ) {
250 - foreach ( $log as $l => $v ) {
251 - $tmp .= ( $tmp != '' ? ';':'' ) . "$table:$l";
252 - }
253 - }
254 - $result = array( 'sql' => $sql, 'tmp_hierarchy' => $tmp, 'page_ids' => array() );
255 -
256 - $res = $this->m_dbs->select( $this->m_dbs->tableName( $qobj->jointable ) . " AS $qobj->alias" . $qobj->from, "DISTINCT $qobj->alias.smw_title AS t,$qobj->alias.smw_namespace AS ns", $qobj->where, 'SMW::getNMQueryResult' );
257 - while ( $row = $this->m_dbs->fetchObject( $res ) ) {
258 - if ( $row->ns != NS_MAIN ) continue;
259 -
260 - $title = Title::makeTitle( $row->ns, $row->t );
261 - $result['page_ids'][] = $title->getArticleID();
262 - }
263 - $this->m_dbs->freeResult( $res );
264 -
265 - wfProfileOut( 'SMWSQLStore2Queries::getNMQueryResult (SMW)' );
266 - return $result;
267 - }
268 -
269 - /**
270 - * Create a new SMWSQLStore2Query object that can be used to obtain results
271 - * for the given description. The result is stored in $this->m_queries
272 - * using a numeric key that is returned as a result of the function.
273 - * Returns -1 if no query was created.
274 - * @todo The case of nominal classes (top-level SMWValueDescription) still
275 - * makes some assumptions about the table structure, especially about the
276 - * name of the joinfield (o_id). Better extend compileAttributeWhere to
277 - * deal with this case.
278 - *
279 - * @param SMWDescription $description
280 - *
281 - * @return integer
282 - */
283 - protected function compileQueries( SMWDescription $description ) {
284 - $qid = SMWSQLStore2Query::$qnum;
285 - $query = new SMWSQLStore2Query();
286 -
287 - if ( $description instanceof SMWSomeProperty ) {
288 - $this->compilePropertyCondition( $query, $description->getProperty(), $description->getDescription() );
289 - // Compilation has set type to NOQUERY: drop condition.
290 - if ( $query->type == SMW_SQL2_NOQUERY ) $qid = - 1;
291 - } elseif ( $description instanceof SMWNamespaceDescription ) {
292 - // TODO: One instance of smw_ids on s_id always suffices (swm_id is KEY)! Doable in execution ... (PERFORMANCE)
293 - $query->jointable = 'smw_ids';
294 - $query->joinfield = "$query->alias.smw_id";
295 - $query->where = "$query->alias.smw_namespace=" . $this->m_dbs->addQuotes( $description->getNamespace() );
296 - } elseif ( ( $description instanceof SMWConjunction ) || ( $description instanceof SMWDisjunction ) ) {
297 - $query->type = ( $description instanceof SMWConjunction ) ? SMW_SQL2_CONJUNCTION:SMW_SQL2_DISJUNCTION;
298 -
299 - foreach ( $description->getDescriptions() as $subdesc ) {
300 - $sub = $this->compileQueries( $subdesc );
301 - if ( $sub >= 0 ) {
302 - $query->components[$sub] = true;
303 - }
304 - }
305 -
306 - // All subconditions failed, drop this as well.
307 - if ( count( $query->components ) == 0 ) $qid = - 1;
308 - } elseif ( $description instanceof SMWClassDescription ) {
309 - $cqid = SMWSQLStore2Query::$qnum;
310 - $cquery = new SMWSQLStore2Query();
311 - $cquery->type = SMW_SQL2_CLASS_HIERARCHY;
312 - $cquery->joinfield = array();
313 -
314 - foreach ( $description->getCategories() as $cat ) {
315 - $cid = $this->m_store->getSMWPageID( $cat->getDBkey(), NS_CATEGORY, $cat->getInterwiki() );
316 - if ( $cid != 0 ) {
317 - $cquery->joinfield[] = $cid;
318 - }
319 - }
320 -
321 - if ( count( $cquery->joinfield ) == 0 ) { // Empty result.
322 - $query->type = SMW_SQL2_VALUE;
323 - $query->jointable = '';
324 - $query->joinfield = '';
325 - } else { // Instance query with dicjunction of classes (categories)
326 - $query->jointable = 'smw_inst2';
327 - $query->joinfield = "$query->alias.s_id";
328 - $query->components[$cqid] = "$query->alias.o_id";
329 - $this->m_queries[$cqid] = $cquery;
330 - }
331 - } elseif ( $description instanceof SMWValueDescription ) { // Only type '_wpg' objects can appear on query level (essentially as nominal classes).
332 - if ( $description->getDatavalue()->getTypeID() == '_wpg' ) {
333 - if ( $description->getComparator() == SMW_CMP_EQ ) {
334 - $query->type = SMW_SQL2_VALUE;
335 - $oid = $this->m_store->getSMWPageID( $description->getDatavalue()->getDBkey(), $description->getDatavalue()->getNamespace(), $description->getDatavalue()->getInterwiki() );
336 - $query->joinfield = array( $oid );
337 - } else { // Join with smw_ids needed for other comparators (apply to title string).
338 - $query->jointable = 'smw_ids';
339 - $query->joinfield = "$query->alias.smw_id";
340 - $value = $description->getDatavalue()->getSortkey();
341 -
342 - switch ( $description->getComparator() ) {
343 - case SMW_CMP_LEQ: $comp = '<='; break;
344 - case SMW_CMP_GEQ: $comp = '>='; break;
345 - case SMW_CMP_NEQ: $comp = '!='; break;
346 - case SMW_CMP_LIKE: case SMW_CMP_NLKE:
347 - $comp = ' LIKE ';
348 - if ( $description->getComparator() == SMW_CMP_NLKE ) $comp = " NOT{$comp}";
349 - $value = str_replace( array( '%', '_', '*', '?' ), array( '\%', '\_', '%', '_' ), $value );
350 - break;
351 - }
352 -
353 - $query->where = "$query->alias.smw_sortkey$comp" . $this->m_dbs->addQuotes( $value );
354 - }
355 - }
356 - } elseif ( $description instanceof SMWConceptDescription ) { // fetch concept definition and insert it here
357 - $cid = $this->m_store->getSMWPageID( $description->getConcept()->getDBkey(), SMW_NS_CONCEPT, '' );
358 - $row = $this->m_dbs->selectRow(
359 - 'smw_conc2',
360 - array( 'concept_txt', 'concept_features', 'concept_size', 'concept_depth', 'cache_date' ),
361 - array( 's_id' => $cid ),
362 - 'SMWSQLStore2Queries::compileQueries'
363 - );
364 -
365 - if ( $row === false ) { // No description found, concept does not exist.
366 - // keep the above query object, it yields an empty result
367 - // TODO: announce an error here? (maybe not, since the query processor can check for
368 - // non-existing concept pages which is probably the main reason for finding nothing here)
369 - } else {
370 - global $smwgQConceptCaching, $smwgQMaxSize, $smwgQMaxDepth, $smwgQFeatures, $smwgQConceptCacheLifetime;
371 -
372 - $may_be_computed = ( $smwgQConceptCaching == CONCEPT_CACHE_NONE ) ||
373 - ( ( $smwgQConceptCaching == CONCEPT_CACHE_HARD ) && ( ( ~( ~( $row->concept_features + 0 ) | $smwgQFeatures ) ) == 0 ) &&
374 - ( $smwgQMaxSize >= $row->concept_size ) && ( $smwgQMaxDepth >= $row->concept_depth ) );
375 -
376 - if ( $row->cache_date &&
377 - ( ( $row->cache_date > ( strtotime( "now" ) - $smwgQConceptCacheLifetime * 60 ) ) ||
378 - !$may_be_computed ) ) { // Cached concept, use cache unless it is dead and can be revived.
379 -
380 - $query->jointable = 'smw_conccache';
381 - $query->joinfield = "$query->alias.s_id";
382 - $query->where = "$query->alias.o_id=" . $this->m_dbs->addQuotes( $cid );
383 - } elseif ( $row->concept_txt ) { // Parse description and process it recursively.
384 - if ( $may_be_computed ) {
385 - $qp = new SMWQueryParser();
386 -
387 - // No defaultnamespaces here; If any, these are already in the concept.
388 - $desc = $qp->getQueryDescription( $row->concept_txt );
389 - $qid = $this->compileQueries( $desc );
390 - if ( $qid != -1 ) {
391 - $query = $this->m_queries[$qid];
392 - } else { // somehow the concept query is no longer valid; maybe some syntax changed (upgrade) or global settings were modified since storing it
393 - smwfLoadExtensionMessages( 'SemanticMediaWiki' );
394 - $this->m_errors[] = wfMsg( 'smw_emptysubquery' ); // not quite the right message, but this case is very rare; let us not make detailed messages for this
395 - }
396 - } else {
397 - smwfLoadExtensionMessages( 'SemanticMediaWiki' );
398 - $this->m_errors[] = wfMsg( 'smw_concept_cache_miss', $description->getConcept()->getText() );
399 - }
400 - } // else: no cache, no description (this may happen); treat like empty concept
401 - }
402 - } else { // (e.g. SMWThingDescription)
403 - $qid = - 1; // no condition
404 - }
405 -
406 - if ( $qid >= 0 ) { // Success, keep query object, propagate sortkeys from subqueries.
407 - $this->m_queries[$qid] = $query;
408 -
409 - if ( $query->type != SMW_SQL2_DISJUNCTION ) { // Sortkeys are killed by disjunctions (not all parts may have them),
410 - // NOTE: preprocessing might try to push disjunctions downwards to safe sortkey, but this seems to be minor
411 - foreach ( $query->components as $cid => $field ) {
412 - $query->sortfields = array_merge( $this->m_queries[$cid]->sortfields, $query->sortfields );
413 - }
414 - }
415 - }
416 -
417 - return $qid;
418 - }
419 -
420 - /**
421 - * Modify the given query object to account for some property condition for
422 - * the given property. If it is not possible to generate a query for the
423 - * given data, the query type is changed to SMW_SQL2_NOQUERY. Callers need
424 - * to check for this and discard the query in this case.
425 - * @todo Check if hierarchy queries work as expected.
426 - */
427 - protected function compilePropertyCondition( SMWSQLStore2Query $query, $property, SMWDescription $valuedesc ) {
428 - $tableid = SMWSQLStore2::findPropertyTableID( $property );
429 -
430 - if ( $tableid == '' ) { // probably a type-polymorphic property
431 - $typeid = $valuedesc->getTypeID();
432 - $tableid = SMWSQLStore2::findTypeTableID( $typeid );
433 - } else { // normal property
434 - $typeid = $property->getPropertyTypeID();
435 - }
436 -
437 - if ( $tableid == '' ) { // Still no table to query? Give up.
438 - $query->type = SMW_SQL2_NOQUERY;
439 - return;
440 - }
441 -
442 - $proptables = SMWSQLStore2::getPropertyTables();
443 - $proptable = $proptables[$tableid];
444 -
445 - if ( !$proptable->idsubject ) { // no queries with such tables (there is really no demand, as only redirects are affected)
446 - $query->type = SMW_SQL2_NOQUERY;
447 - return;
448 - }
449 -
450 - list( $sig, $valueindex, $labelindex ) = SMWSQLStore2::getTypeSignature( $typeid );
451 - $sortkey = $property->getDBkey(); // TODO: strictly speaking, the DB key is not what we want here, since sortkey is based on a "wiki value"
452 -
453 - // *** Basic settings: table, joinfield, and objectfields ***//
454 - $query->jointable = $proptable->name;
455 -
456 - if ( $property->isInverse() ) { // see if we can support inverses by inverting the proptable data
457 - if ( ( count( $proptable->objectfields ) == 1 ) && ( reset( $proptable->objectfields ) == 'p' ) ) {
458 - $query->joinfield = $query->alias . '.' . reset( array_keys( $proptable->objectfields ) );
459 - $objectfields = array( 's_id' => 'p' );
460 - $valueindex = $labelindex = 3; // should normally not change, but let's be strict
461 - } else { // no inverses supported for this property, stop here
462 - $query->type = SMW_SQL2_NOQUERY;
463 - return;
464 - }
465 - } else { // normal forward property
466 - $query->joinfield = "{$query->alias}.s_id";
467 - $objectfields = $proptable->objectfields;
468 - }
469 -
470 - // *** Add conditions for selecting rows for this property, maybe with a hierarchy ***//
471 - if ( $proptable->fixedproperty == false ) {
472 - $pid = $this->m_store->getSMWPropertyID( $property );
473 -
474 - if ( !$property->getPropertyID() || ( $property->getPropertyTypeID() != '__err' ) ) {
475 - // also make property hierarchy (may or may not be executed later on)
476 - // exclude type-polymorphic properties _1, _2, ... (2nd check above suffices, but 1st is faster to check)
477 - // we could also exclude other cases here, if desired
478 - $pqid = SMWSQLStore2Query::$qnum;
479 - $pquery = new SMWSQLStore2Query();
480 - $pquery->type = SMW_SQL2_PROP_HIERARCHY;
481 - $pquery->joinfield = array( $pid );
482 - $query->components[$pqid] = "{$query->alias}.p_id";
483 - $this->m_queries[$pqid] = $pquery;
484 - } else {
485 - $query->where = "{$query->alias}.p_id=" . $this->m_dbs->addQuotes( $pid );
486 - }
487 - } // else: no property column, no hierarchy queries
488 -
489 - // *** Add conditions on the value of the property ***//
490 - if ( ( count( $objectfields ) == 1 ) && ( reset( $objectfields ) == 'p' ) ) { // page description, process like main query
491 - $sub = $this->compileQueries( $valuedesc );
492 - $objectfield = reset( array_keys( $objectfields ) );
493 -
494 - if ( $sub >= 0 ) {
495 - $query->components[$sub] = "{$query->alias}.{$objectfield}";
496 - }
497 - } else { // non-page value description; expressive features mainly based on value
498 - $this->compileAttributeWhere( $query, $valuedesc, $proptable, $valueindex );
499 - // (no need to pass on $objectfields since they are just as in $proptable in this case)
500 - }
501 -
502 - // *** Incorporate ordering if desired ***//
503 - if ( ( $valueindex >= 0 ) && array_key_exists( $sortkey, $this->m_sortkeys ) ) {
504 - // This code might be overly general: it supports datatypes of arbitrary signatures
505 - // and valueindex (sortkeys). It can even order pages by something other than their
506 - // sortkey (e.g. by their namespace?!), and it can handle values consisting of a page
507 - // and some more data fields before or after. Supporting pages in this way requires us
508 - // to iterate over the table fields since one page corresponds to four values in a
509 - // type's signature. Thankfully, signatures are short so this iteration is not notable.
510 - $smwidjoinfield = false;
511 - $fieldName = $this->getDBFieldsForDVIndex( $objectfields, $valueindex, $smwidjoinfield );
512 -
513 - if ( $fieldName ) {
514 - if ( $smwidjoinfield ) {
515 - // TODO: is this smw_ids possibly duplicated in the query? Can we prevent that? (PERFORMANCE)
516 - $query->from = ' INNER JOIN ' . $this->m_dbs->tableName( 'smw_ids' ) .
517 - " AS ids{$query->alias} ON ids{$query->alias}.smw_id={$query->alias}.{$smwidjoinfield}";
518 - $query->sortfields[$sortkey] = "ids{$query->alias}.{$fieldName}";
519 - } else {
520 - $query->sortfields[$sortkey] = "{$query->alias}.{$fieldName}";
521 - }
522 - }
523 - }
524 - }
525 -
526 - /**
527 - * Helper function for matching an index that refers to the DB keys (and
528 - * thus signature) of a datatype to the database fields of a fitting
529 - * property table (the objectfields array of which is given).
530 - * The $fieldname is set call-by-ref, where the parameter $smwidjoinfield
531 - * is set to the field of $objectfields on which smw_ids.smw_id needs to
532 - * be joined if $smwidjoinfield refers to a field in smw_ids. This might
533 - * be needed for page-type values. If the value is not in smw_ids, then
534 - * $fieldname refers to $objectfields and $smwidjoinfield is false. If the
535 - * given index could not be matched, $fieldname is false.
536 - *
537 - * @param array $objectFields
538 - * @param integer $index
539 - * @param $smwidjoinfield
540 - *
541 - * @return array with at least one element or false
542 - */
543 - protected function getDBFieldsForDVIndex( array $objectFields, $index, &$smwidjoinfield ) {
544 - $fieldName = false;
545 -
546 - $curindex = 0;
547 - foreach ( $objectFields as $fname => $ftype ) {
548 - if ( $ftype == 'p' ) { // special treatment since "p" consists of 4 fields that are kept in smw_ids
549 - if ( $curindex + 4 >= $index ) {
550 - $idfieldnames = array( 'smw_title', 'smw_namespace', 'smw_iw', 'smw_sortkey' );
551 - $smwidjoinfield = $fname;
552 - $fieldName = $idfieldnames[$index - $curindex];
553 - break;
554 - }
555 - $curindex += 3;
556 - } elseif ( $curindex == $index ) {
557 - $smwidjoinfield = false;
558 - $fieldName = $fname;
559 - break;
560 - }
561 - $curindex++;
562 - }
563 -
564 - return $fieldName;
565 - }
566 -
567 - /**
568 - * Given an SMWDescription that is just a conjunction or disjunction of
569 - * SMWValueDescription objects, create and return a plain WHERE condition
570 - * string for it.
571 - *
572 - * @param $query
573 - * @param SMWDescription $description
574 - * @param SMWSQLStore2Table $proptable
575 - * @param integer $valueIndex
576 - * @param string $operator
577 - */
578 - protected function compileAttributeWhere(
579 - $query, SMWDescription $description, SMWSQLStore2Table $proptable, $valueIndex, $operator = 'AND' ) {
580 -
581 - $where = '';
582 -
583 - if ( $description instanceof SMWValueDescription ) {
584 - $dv = $description->getDatavalue();
585 - $keys = $dv->getDBkeys();
586 -
587 - // Try comparison based on value field and comparator.
588 - if ( $valueIndex >= 0 ) {
589 - // Find field name for comparison.
590 - $smwidjoinfield = false;
591 - $fieldName = $this->getDBFieldsForDVIndex( $proptable->objectfields, $valueIndex, $smwidjoinfield );
592 -
593 - // Do not support smw_id joined data for now.
594 - if ( $fieldName && !$smwidjoinfield ) {
595 - $comparator = false;
596 - $customSQL = false;
597 -
598 - // See if the getSQLCondition method exists and call it if this is the case.
599 - if ( method_exists( $description, 'getSQLCondition' ) ) {
600 - $customSQL = $description->getSQLCondition( $query->alias, array_keys( $proptable->objectfields ), $this->m_dbs );
601 - }
602 -
603 - if ( $customSQL ) {
604 - $where = $customSQL;
605 - } else {
606 - $value = $keys[$valueIndex];
607 -
608 - switch ( $description->getComparator() ) {
609 - case SMW_CMP_EQ: $comparator = '='; break;
610 - case SMW_CMP_LEQ: $comparator = '<='; break;
611 - case SMW_CMP_GEQ: $comparator = '>='; break;
612 - case SMW_CMP_NEQ: $comparator = '!='; break;
613 - case SMW_CMP_LIKE: case SMW_CMP_NLKE:
614 - $comparator = ' LIKE ';
615 - if ( $description->getComparator() == SMW_CMP_NLKE ) $comparator = " NOT{$comparator}";
616 - $value = str_replace( array( '%', '_', '*', '?' ), array( '\%', '\_', '%', '_' ), $value );
617 - }
618 -
619 - if ( $comparator ) {
620 - $where = "$query->alias.{$fieldName}{$comparator}" . $this->m_dbs->addQuotes( $value );
621 - }
622 - }
623 - }
624 - }
625 -
626 - if ( $where == '' ) { // comparators did not apply; match all fields
627 - $i = 0;
628 -
629 - foreach ( $proptable->objectfields as $fname => $ftype ) {
630 - if ( $i >= count( $keys ) ) break;
631 -
632 - if ( $ftype == 'p' ) { // Special case: page id, resolve this in advance
633 - $oid = $this->getSMWPageID( $keys[$i], $keys[$i + 1], $keys[$i + 2] );
634 - $i += 3; // skip these additional values (sortkey not needed here)
635 - $where .= ( $where ? ' AND ' : '' ) . "{$query->alias}.$fname=" . $this->m_dbs->addQuotes( $oid );
636 - } elseif ( $ftype != 'l' ) { // plain value, but not a text blob
637 - $where .= ( $where ? ' AND ' : '' ) . "{$query->alias}.$fname=" . $this->m_dbs->addQuotes( $keys[$i] );
638 - }
639 -
640 - $i++;
641 - }
642 - }
643 -
644 - } elseif ( ( $description instanceof SMWConjunction ) || ( $description instanceof SMWDisjunction ) ) {
645 - $op = ( $description instanceof SMWConjunction ) ? 'AND' : 'OR';
646 -
647 - foreach ( $description->getDescriptions() as $subdesc ) {
648 - $this->compileAttributeWhere( $query, $subdesc, $proptable, $valueIndex, $op );
649 - }
650 - }
651 -
652 - if ( $where != '' ) $query->where .= ( $query->where ? " $operator " : '' ) . "($where)";
653 - }
654 -
655 - /**
656 - * Process stored queries and change store accordingly. The query obj is modified
657 - * so that it contains non-recursive description of a select to execute for getting
658 - * the actual result.
659 - *
660 - * @param SMWSQLStore2Query $query
661 - */
662 - protected function executeQueries( SMWSQLStore2Query &$query ) {
663 - global $wgDBtype;
664 -
665 - switch ( $query->type ) {
666 - case SMW_SQL2_TABLE: // Normal query with conjunctive subcondition.
667 - foreach ( $query->components as $qid => $joinfield ) {
668 - $subquery = $this->m_queries[$qid];
669 - $this->executeQueries( $subquery );
670 -
671 - if ( $subquery->jointable != '' ) { // Join with jointable.joinfield
672 - $query->from .= ' INNER JOIN ' . $this->m_dbs->tableName( $subquery->jointable ) . " AS $subquery->alias ON $joinfield=" . $subquery->joinfield;
673 - } elseif ( $subquery->joinfield !== '' ) { // Require joinfield as "value" via WHERE.
674 - $condition = '';
675 -
676 - foreach ( $subquery->joinfield as $value ) {
677 - $condition .= ( $condition ? ' OR ':'' ) . "$joinfield=" . $this->m_dbs->addQuotes( $value );
678 - }
679 -
680 - if ( count( $subquery->joinfield ) > 1 ) {
681 - $condition = "($condition)";
682 - }
683 -
684 - $query->where .= ( ( $query->where == '' ) ? '':' AND ' ) . $condition;
685 - } else { // interpret empty joinfields as impossible condition (empty result)
686 - $query->joinfield = ''; // make whole query false
687 - $query->jointable = '';
688 - $query->where = '';
689 - $query->from = '';
690 - break;
691 - }
692 -
693 - if ( $subquery->where != '' ) {
694 - $query->where .= ( ( $query->where == '' ) ? '':' AND ' ) . '(' . $subquery->where . ')';
695 - }
696 -
697 - $query->from .= $subquery->from;
698 - }
699 -
700 - $query->components = array();
701 - break;
702 - case SMW_SQL2_CONJUNCTION:
703 - // pick one subquery with jointable as anchor point ...
704 - reset( $query->components );
705 - $key = false;
706 -
707 - foreach ( $query->components as $qkey => $qid ) {
708 - if ( $this->m_queries[$qkey]->jointable != '' ) {
709 - $key = $qkey;
710 - break;
711 - }
712 - }
713 -
714 - if ( $key !== false ) {
715 - $result = $this->m_queries[$key];
716 - unset( $query->components[$key] );
717 -
718 - // Execute it first (may change jointable and joinfield, e.g. when making temporary tables)
719 - $this->executeQueries( $result );
720 -
721 - // ... and append to this query the remaining queries.
722 - foreach ( $query->components as $qid => $joinfield ) {
723 - $result->components[$qid] = $result->joinfield;
724 - }
725 -
726 - // Second execute, now incorporating remaining conditions.
727 - $this->executeQueries( $result );
728 - } else { // Only fixed values in conjunction, make a new value without joining.
729 - $key = $qkey;
730 - $result = $this->m_queries[$key];
731 - unset( $query->components[$key] );
732 -
733 - foreach ( $query->components as $qid => $joinfield ) {
734 - if ( $result->joinfield != $this->m_queries[$qid]->joinfield ) {
735 - $result->joinfield = ''; // all other values should already be ''
736 - break;
737 - }
738 - }
739 - }
740 - $query = $result;
741 - break;
742 - case SMW_SQL2_DISJUNCTION:
743 - // modified by ning, disable TEMPORARY tables
744 -// if ( $this->m_qmode !== SMWQuery::MODE_DEBUG ) {
745 -// $this->m_dbs->query( $this->getCreateTempIDTableSQL( $this->m_dbs->tableName( $query->alias ) ), 'SMW::executeQueries' );
746 -// }
747 -//
748 -// $this->m_querylog[$query->alias] = array();
749 -
750 - $sql = array();
751 - foreach ( $query->components as $qid => $joinfield ) {
752 - $subquery = $this->m_queries[$qid];
753 - $this->executeQueries( $subquery );
754 -// $sql = '';
755 -
756 - if ( $subquery->jointable != '' ) {
757 -// $sql = 'INSERT ' . ( ( $wgDBtype == 'postgres' ) ? '':'IGNORE ' ) . 'INTO ' .
758 -// $this->m_dbs->tableName( $query->alias ) .
759 -// " SELECT $subquery->joinfield FROM " . $this->m_dbs->tableName( $subquery->jointable ) .
760 -// " AS $subquery->alias $subquery->from" . ( $subquery->where ? " WHERE $subquery->where":'' );
761 - $sql[] = "(SELECT $subquery->joinfield AS id FROM " . $this->m_dbs->tableName( $subquery->jointable ) .
762 - " AS $subquery->alias $subquery->from" . ( $subquery->where ? " WHERE $subquery->where":'' ) . ")";
763 - } elseif ( $subquery->joinfield !== '' ) {
764 - // NOTE: this works only for single "unconditional" values without further
765 - // WHERE or FROM. The execution must take care of not creating any others.
766 - $values = '';
767 -
768 - foreach ( $subquery->joinfield as $value ) {
769 - $values .= ( $values ? ',' : '' ) . '(' . $this->m_dbs->addQuotes( $value ) . ')';
770 - }
771 -
772 -// $sql = 'INSERT ' . ( ( $wgDBtype == 'postgres' ) ? '':'IGNORE ' ) . 'INTO ' . $this->m_dbs->tableName( $query->alias ) . " (id) VALUES $values";
773 - $sql[] = "(SELECT smw_id AS id FROM " . $this->m_dbs->tableName( 'smw_ids' ) . " WHERE smw_id IN ($values))";
774 - } // else: // interpret empty joinfields as impossible condition (empty result), ignore
775 -// if ( $sql ) {
776 -// $this->m_querylog[$query->alias][] = $sql;
777 -//
778 -// if ( $this->m_qmode !== SMWQuery::MODE_DEBUG ) {
779 -// $this->m_dbs->query( $sql , 'SMW::executeQueries' );
780 -// }
781 -// }
782 - }
783 -
784 -// $query->jointable = $query->alias;
785 - $query->jointable = "(" . implode( " UNION ", $sql ) . ")";
786 - $query->joinfield = "$query->alias.id";
787 - $query->sortfields = array(); // Make sure we got no sortfields.
788 - // TODO: currently this eliminates sortkeys, possibly keep them (needs different temp table format though, maybe not such a good thing to do)
789 - break;
790 - case SMW_SQL2_PROP_HIERARCHY: case SMW_SQL2_CLASS_HIERARCHY: // make a saturated hierarchy
791 - $this->executeHierarchyQuery( $query );
792 - break;
793 - case SMW_SQL2_VALUE: break; // nothing to do
794 - }
795 - }
796 -
797 - /**
798 - * Find subproperties or subcategories. This may require iterative computation,
799 - * and temporary tables are used in many cases.
800 - *
801 - * @param SMWSQLStore2Query $query
802 - */
803 - protected function executeHierarchyQuery( SMWSQLStore2Query &$query ) {
804 - global $wgDBtype;
805 - global $smwgQSubpropertyDepth, $smwgQSubcategoryDepth;
806 -
807 - $fname = "SMWSQLStore2Queries::executeQueries-hierarchy-$query->type (SMW)";
808 - wfProfileIn( $fname );
809 -
810 - $depth = ( $query->type == SMW_SQL2_PROP_HIERARCHY ) ? $smwgQSubpropertyDepth : $smwgQSubcategoryDepth;
811 -
812 - if ( $depth <= 0 ) { // treat as value, no recursion
813 - $query->type = SMW_SQL2_VALUE;
814 - wfProfileOut( $fname );
815 - return;
816 - }
817 -
818 - $values = '';
819 - $valuecond = '';
820 -
821 - foreach ( $query->joinfield as $value ) {
822 - $values .= ( $values ? ',':'' ) . '(' . $this->m_dbs->addQuotes( $value ) . ')';
823 - $valuecond .= ( $valuecond ? ' OR ':'' ) . 'o_id=' . $this->m_dbs->addQuotes( $value );
824 - }
825 -
826 - $smwtable = $this->m_dbs->tableName( ( $query->type == SMW_SQL2_PROP_HIERARCHY ) ? 'smw_subp2':'smw_subs2' );
827 -
828 - // Try to safe time (SELECT is cheaper than creating/dropping 3 temp tables):
829 - $res = $this->m_dbs->select( $smwtable, 's_id', $valuecond, array( 'LIMIT' => 1 ) );
830 -
831 - if ( !$this->m_dbs->fetchObject( $res ) ) { // no subobjects, we are done!
832 - $this->m_dbs->freeResult( $res );
833 - $query->type = SMW_SQL2_VALUE;
834 - wfProfileOut( $fname );
835 - return;
836 - }
837 -
838 - $this->m_dbs->freeResult( $res );
839 - $tablename = $this->m_dbs->tableName( $query->alias );
840 - // modified by ning
841 -// $this->m_querylog[$query->alias] = array( "Recursively computed hierarchy for element(s) $values." );
842 - $this->m_querylog[$query->alias]["$depth:$values"] = "Recursively computed hierarchy for element(s) $values.";
843 - $query->jointable = $query->alias;
844 - $query->joinfield = "$query->alias.id";
845 -
846 - if ( $this->m_qmode == SMWQuery::MODE_DEBUG ) {
847 - wfProfileOut( $fname );
848 - return; // No real queries in debug mode.
849 - }
850 -
851 - $this->m_dbs->query( $this->getCreateTempIDTableSQL( $tablename ), 'SMW::executeHierarchyQuery' );
852 -
853 - if ( array_key_exists( $values, $this->m_hierarchies ) ) { // Just copy known result.
854 - $this->m_dbs->query( "INSERT INTO $tablename (id) SELECT id" .
855 - ' FROM ' . $this->m_hierarchies[$values],
856 - 'SMW::executeHierarchyQuery' );
857 - wfProfileOut( $fname );
858 - return;
859 - }
860 -
861 - // NOTE: we use two helper tables. One holds the results of each new iteration, one holds the
862 - // results of the previous iteration. One could of course do with only the above result table,
863 - // but then every iteration would use all elements of this table, while only the new ones
864 - // obtained in the previous step are relevant. So this is a performance measure.
865 - $tmpnew = 'smw_new';
866 - $tmpres = 'smw_res';
867 - $this->m_dbs->query( $this->getCreateTempIDTableSQL( $tmpnew ), 'SMW::executeQueries' );
868 - $this->m_dbs->query( $this->getCreateTempIDTableSQL( $tmpres ), 'SMW::executeQueries' );
869 - $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? "" : "IGNORE" ) . " INTO $tablename (id) VALUES $values", 'SMW::executeHierarchyQuery' );
870 - $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? "" : "IGNORE" ) . " INTO $tmpnew (id) VALUES $values", 'SMW::executeHierarchyQuery' );
871 -
872 - for ( $i = 0; $i < $depth; $i++ ) {
873 - $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? '' : 'IGNORE ' ) . "INTO $tmpres (id) SELECT s_id" . ( $wgDBtype == 'postgres' ? '::integer':'' ) . " FROM $smwtable, $tmpnew WHERE o_id=id",
874 - 'SMW::executeHierarchyQuery' );
875 - if ( $this->m_dbs->affectedRows() == 0 ) { // no change, exit loop
876 - break;
877 - }
878 -
879 - $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? '' : 'IGNORE ' ) . "INTO $tablename (id) SELECT $tmpres.id FROM $tmpres",
880 - 'SMW::executeHierarchyQuery' );
881 -
882 - if ( $this->m_dbs->affectedRows() == 0 ) { // no change, exit loop
883 - break;
884 - }
885 -
886 - $this->m_dbs->query( 'TRUNCATE TABLE ' . $tmpnew, 'SMW::executeHierarchyQuery' ); // empty "new" table
887 - $tmpname = $tmpnew;
888 - $tmpnew = $tmpres;
889 - $tmpres = $tmpname;
890 - }
891 -
892 - $this->m_hierarchies[$values] = $tablename;
893 - $this->m_dbs->query( ( ( $wgDBtype == 'postgres' ) ? 'DROP TABLE IF EXISTS smw_new' : 'DROP TEMPORARY TABLE smw_new' ), 'SMW::executeHierarchyQuery' );
894 - $this->m_dbs->query( ( ( $wgDBtype == 'postgres' ) ? 'DROP TABLE IF EXISTS smw_res' : 'DROP TEMPORARY TABLE smw_res' ), 'SMW::executeHierarchyQuery' );
895 -
896 - wfProfileOut( $fname );
897 - }
898 -
899 - /**
900 - * After querying, make sure no temporary database tables are left.
901 - * @todo I might be better to keep the tables and possibly reuse them later
902 - * on. Being temporary, the tables will vanish with the session anyway.
903 - */
904 - protected function cleanUp() {
905 - global $wgDBtype;
906 - if ( $this->m_qmode !== SMWQuery::MODE_DEBUG ) {
907 - foreach ( $this->m_querylog as $table => $log ) {
908 - $this->m_dbs->query( ( ( $wgDBtype == 'postgres' ) ? "DROP TABLE IF EXISTS ":"DROP TEMPORARY TABLE " ) . $this->m_dbs->tableName( $table ), 'SMW::getQueryResult' );
909 - }
910 - }
911 - }
912 -
913 - /**
914 - * Get SQL code suitable to create a temporary table of the given name, used to store ids.
915 - * MySQL can do that simply by creating new temporary tables. PostgreSQL first checks if such
916 - * a table exists, so the code is ready to reuse existing tables if the code was modified to
917 - * keep them after query answering. Also, PostgreSQL tables will use a RULE to achieve built-in
918 - * duplicate elimination. The latter is done using INSERT IGNORE in MySQL.
919 - *
920 - * @param string $tablename
921 - */
922 - protected function getCreateTempIDTableSQL( $tablename ) {
923 - global $wgDBtype;
924 -
925 - if ( $wgDBtype == 'postgres' ) { // PostgreSQL: no memory tables, use RULE to emulate INSERT IGNORE
926 - return "CREATE OR REPLACE FUNCTION create_" . $tablename . "() RETURNS void AS "
927 - . "$$ "
928 - . "BEGIN "
929 - . " IF EXISTS(SELECT NULL FROM pg_tables WHERE tablename='" . $tablename . "' AND schemaname = ANY (current_schemas(true))) "
930 - . " THEN DELETE FROM " . $tablename . "; "
931 - . " ELSE "
932 - . " CREATE TEMPORARY TABLE " . $tablename . " (id INTEGER PRIMARY KEY); "
933 - . " CREATE RULE " . $tablename . "_ignore AS ON INSERT TO " . $tablename . " WHERE (EXISTS (SELECT NULL FROM " . $tablename
934 - . " WHERE (" . $tablename . ".id = new.id))) DO INSTEAD NOTHING; "
935 - . " END IF; "
936 - . "END; "
937 - . "$$ "
938 - . "LANGUAGE 'plpgsql'; "
939 - . "SELECT create_" . $tablename . "(); ";
940 - } else { // MySQL_ just a temporary table, use INSERT IGNORE later
941 - return "CREATE TEMPORARY TABLE " . $tablename . "( id INT UNSIGNED KEY ) TYPE=MEMORY";
942 - }
943 - }
944 -}
 2+<?php
 3+/**
 4+ * Query answering functions for SMWSQLStore2. Separated frmo main code for readability and
 5+ * for avoiding twice the amount of code being required on every use of a simple storage function.
 6+ *
 7+ * based on SMW, SMW_SQLStore2_Queries.php, apply query parser to NotifyMe
 8+ *
 9+ * @author ning
 10+ */
 11+if ( !defined( 'MEDIAWIKI' ) ) {
 12+ exit( 1 );
 13+}
 14+
 15+global $smwgIP;
 16+include_once( "$smwgIP/includes/storage/SMW_SQLStore2_Queries.php" );
 17+
 18+/**
 19+ * Class that implements query answering for SMWSQLStore2.
 20+ */
 21+class SMWSQLStore2QueryEngineNM {
 22+
 23+ /** Database slave to be used */
 24+ protected $m_dbs; // TODO: should temporary tables be created on the master DB?
 25+ /** Parent SMWSQLStore2. */
 26+ protected $m_store;
 27+ /** Query mode copied from given query. Some submethods act differently when in SMWQuery::MODE_DEBUG. */
 28+ protected $m_qmode;
 29+ /** Array of generated SMWSQLStore2Query query descriptions (index => object). */
 30+ protected $m_queries = array();
 31+ /** Array of arrays of executed queries, indexed by the temporary table names results were fed into. */
 32+ protected $m_querylog = array();
 33+ /**
 34+ * Array of sorting requests ("Property_name" => "ASC"/"DESC"). Used during query
 35+ * processing (where these property names are searched while compiling the query
 36+ * conditions).
 37+ */
 38+ protected $m_sortkeys;
 39+ /** Cache of computed hierarchy queries for reuse ("catetgory/property value string" => "tablename"). */
 40+ protected $m_hierarchies = array();
 41+ /** Local collection of error strings, passed on to callers if possible. */
 42+ protected $m_errors = array();
 43+
 44+ public function __construct( &$parentstore, &$dbslave ) {
 45+ $this->m_store = $parentstore;
 46+ $this->m_dbs = $dbslave;
 47+ }
 48+
 49+ /**
 50+ * Refresh the concept cache for the given concept.
 51+ *
 52+ * @param $concept Title
 53+ */
 54+ public function refreshConceptCache( $concept ) {
 55+ global $smwgQMaxLimit, $smwgQConceptFeatures, $wgDBtype;
 56+
 57+ $cid = $this->m_store->getSMWPageID( $concept->getDBkey(), SMW_NS_CONCEPT, '' );
 58+ $cid_c = $this->m_store->getSMWPageID( $concept->getDBkey(), SMW_NS_CONCEPT, '', false );
 59+
 60+ if ( $cid != $cid_c ) {
 61+ $this->m_errors[] = "Skipping redirect concept.";
 62+ return $this->m_errors;
 63+ }
 64+
 65+ $dv = end( $this->m_store->getPropertyValues( $concept, SMWPropertyValue::makeProperty( '_CONC' ) ) );
 66+ $desctxt = ( $dv !== false ) ? $dv->getWikiValue():false;
 67+ $this->m_errors = array();
 68+
 69+ if ( $desctxt ) { // concept found
 70+ $this->m_qmode = SMWQuery::MODE_INSTANCES;
 71+ $this->m_queries = array();
 72+ $this->m_hierarchies = array();
 73+ $this->m_querylog = array();
 74+ $this->m_sortkeys = array();
 75+ SMWSQLStore2Query::$qnum = 0;
 76+
 77+ // Pre-process query:
 78+ $qp = new SMWQueryParser( $smwgQConceptFeatures );
 79+ $desc = $qp->getQueryDescription( $desctxt );
 80+ $qid = $this->compileQueries( $desc );
 81+
 82+ $this->executeQueries( $this->m_queries[$qid] ); // execute query tree, resolve all dependencies
 83+ $qobj = $this->m_queries[$qid];
 84+
 85+ if ( $qobj->joinfield === '' ) {
 86+ return;
 87+ }
 88+
 89+ // Update database:
 90+ $this->m_dbs->delete( 'smw_conccache', array( 'o_id' => $cid ), 'SMW::refreshConceptCache' );
 91+
 92+ if ( $wgDBtype == 'postgres' ) { // PostgresQL: no INSERT IGNORE, check for duplicates explicitly
 93+ $where = $qobj->where . ( $qobj->where ? ' AND ':'' ) .
 94+ 'NOT EXISTS (SELECT NULL FROM ' . $this->m_dbs->tableName( 'smw_conccache' ) .
 95+ ' WHERE ' . $this->m_dbs->tablename( 'smw_conccache' ) . '.s_id = ' . $qobj->alias . '.s_id ' .
 96+ ' AND ' . $this->m_dbs->tablename( 'smw_conccache' ) . '.o_id = ' . $qobj->alias . '.o_id )';
 97+ } else { // MySQL just uses INSERT IGNORE, no extra conditions
 98+ $where = $qobj->where;
 99+ }
 100+
 101+ $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? "":"IGNORE " ) . "INTO " . $this->m_dbs->tableName( 'smw_conccache' ) .
 102+ " SELECT DISTINCT $qobj->joinfield AS s_id, $cid AS o_id FROM " .
 103+ $this->m_dbs->tableName( $qobj->jointable ) . " AS $qobj->alias" . $qobj->from .
 104+ ( $where ? " WHERE ":'' ) . $where . " LIMIT $smwgQMaxLimit",
 105+ 'SMW::refreshConceptCache' );
 106+
 107+ $this->m_dbs->update( 'smw_conc2', array( 'cache_date' => strtotime( "now" ), 'cache_count' => $this->m_dbs->affectedRows() ), array( 's_id' => $cid ), 'SMW::refreshConceptCache' );
 108+ } else { // just delete old data if there is any
 109+ $this->m_dbs->delete( 'smw_conccache', array( 'o_id' => $cid ), 'SMW::refreshConceptCache' );
 110+ $this->m_dbs->update( 'smw_conc2', array( 'cache_date' => null, 'cache_count' => null ), array( 's_id' => $cid ), 'SMW::refreshConceptCache' );
 111+ $this->m_errors[] = "No concept description found.";
 112+ }
 113+
 114+ $this->cleanUp();
 115+
 116+ return $this->m_errors;
 117+ }
 118+
 119+ /**
 120+ * Delete the concept cache for the given concept.
 121+ *
 122+ * @param $concept Title
 123+ */
 124+ public function deleteConceptCache( $concept ) {
 125+ $cid = $this->m_store->getSMWPageID( $concept->getDBkey(), SMW_NS_CONCEPT, '', false );
 126+ $this->m_dbs->delete( 'smw_conccache', array( 'o_id' => $cid ), 'SMW::refreshConceptCache' );
 127+ $this->m_dbs->update( 'smw_conc2', array( 'cache_date' => null, 'cache_count' => null ), array( 's_id' => $cid ), 'SMW::refreshConceptCache' );
 128+ }
 129+
 130+ /**
 131+ * The new SQL store's implementation of query answering. This function
 132+ * works in two stages: First, the nested conditions of the given query
 133+ * object are preprocessed to compute an abstract representation of the
 134+ * SQL query that is to be executed. Since query conditions correspond to
 135+ * joins with property tables in most cases, this abstract representation
 136+ * is essentially graph-like description of how property tables are joined.
 137+ * Moreover, this graph is tree-shaped, since all query conditions are
 138+ * tree-shaped. Each part of this abstract query structure is represented
 139+ * by an SMWSQLStore2Query object in the array m_queries.
 140+ *
 141+ * As a second stage of processing, the thus prepared SQL query is actually
 142+ * executed. Typically, this means that the joins are collapsed into one
 143+ * SQL query to retrieve results. In some cases, such as in dbug mode, the
 144+ * execution might be restricted and not actually perform the whole query.
 145+ *
 146+ * The two-stage process helps to separate tasks, and it also allows for
 147+ * better optimisations: it is left to the execution engine how exactly the
 148+ * query result is to be obtained. For example, one could pre-compute
 149+ * partial suib-results in temporary tables (or even cache them somewhere),
 150+ * instead of passing one large join query to the DB (of course, it might
 151+ * be large only if the configuration of SMW allows it). For some DBMS, a
 152+ * step-wise execution of the query might lead to better performance, since
 153+ * it exploits the tree-structure of the joins, which is important for fast
 154+ * processing -- not all DBMS might be able in seeing this by themselves.
 155+ *
 156+ * @param SMWQuery $query
 157+ */
 158+ public function getQueryResult( SMWQuery $query ) {
 159+ global $smwgIgnoreQueryErrors, $smwgQSortingSupport;
 160+
 161+ if ( !$smwgIgnoreQueryErrors && ( $query->querymode != SMWQuery::MODE_DEBUG ) && ( count( $query->getErrors() ) > 0 ) ) {
 162+ return new SMWQueryResult( $query->getDescription()->getPrintrequests(), $query, array(), $this->m_store, false );
 163+ // NOTE: we check this here to prevent unnecessary work, but we check it after query processing below again in case more errors occurred
 164+ } elseif ( $query->querymode == SMWQuery::MODE_NONE ) { // don't query, but return something to printer
 165+ return new SMWQueryResult( $query->getDescription()->getPrintrequests(), $query, array(), $this->m_store, true );
 166+ }
 167+
 168+ $this->m_qmode = $query->querymode;
 169+ $this->m_queries = array();
 170+ $this->m_hierarchies = array();
 171+ $this->m_querylog = array();
 172+ $this->m_errors = array();
 173+ SMWSQLStore2Query::$qnum = 0;
 174+ $this->m_sortkeys = $query->sortkeys;
 175+
 176+ // *** First compute abstract representation of the query (compilation) ***//
 177+ wfProfileIn( 'SMWSQLStore2Queries::compileMainQuery (SMW)' );
 178+ $qid = $this->compileQueries( $query->getDescription() ); // compile query, build query "plan"
 179+ wfProfileOut( 'SMWSQLStore2Queries::compileMainQuery (SMW)' );
 180+
 181+ if ( $qid < 0 ) { // no valid/supported condition; ensure that at least only proper pages are delivered
 182+ $qid = SMWSQLStore2Query::$qnum;
 183+ $q = new SMWSQLStore2Query();
 184+ $q->jointable = 'smw_ids';
 185+ $q->joinfield = "$q->alias.smw_id";
 186+ $q->where = "$q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWIW ) . " AND $q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWREDIIW ) . " AND $q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWBORDERIW ) . " AND $q->alias.smw_iw!=" . $this->m_dbs->addQuotes( SMW_SQL2_SMWINTDEFIW );
 187+ $this->m_queries[$qid] = $q;
 188+ }
 189+
 190+ if ( $this->m_queries[$qid]->jointable != 'smw_ids' ) {
 191+ // manually make final root query (to retrieve namespace,title):
 192+ $rootid = SMWSQLStore2Query::$qnum;
 193+ $qobj = new SMWSQLStore2Query();
 194+ $qobj->jointable = 'smw_ids';
 195+ $qobj->joinfield = "$qobj->alias.smw_id";
 196+ $qobj->components = array( $qid => "$qobj->alias.smw_id" );
 197+ $qobj->sortfields = $this->m_queries[$qid]->sortfields;
 198+ $this->m_queries[$rootid] = $qobj;
 199+ } else { // not such a common case, but worth avoiding the additional inner join:
 200+ $rootid = $qid;
 201+ }
 202+
 203+ // commented by ning, no need to sort
 204+// // Include order conditions (may extend query if needed for sorting):
 205+// if ( $smwgQSortingSupport ) {
 206+// $this->applyOrderConditions( $rootid );
 207+// }
 208+
 209+ if ( !$smwgIgnoreQueryErrors && ( $query->querymode != SMWQuery::MODE_DEBUG ) && ( count( $this->m_errors ) > 0 ) ) { // stop here if new errors happened
 210+ $query->addErrors( $this->m_errors );
 211+ return new SMWQueryResult( $query->getDescription()->getPrintrequests(), $query, array(), $this->m_store, false );
 212+ }
 213+
 214+ // *** Now execute the computed query ***//
 215+ wfProfileIn( 'SMWSQLStore2Queries::executeMainQuery (SMW)' );
 216+ $this->executeQueries( $this->m_queries[$rootid] ); // execute query tree, resolve all dependencies
 217+ wfProfileOut( 'SMWSQLStore2Queries::executeMainQuery (SMW)' );
 218+
 219+ $result = $this->getNMQueryResult( $query, $rootid );
 220+
 221+ $this->cleanUp();
 222+ $query->addErrors( $this->m_errors );
 223+
 224+ return $result;
 225+ }
 226+
 227+ /**
 228+ * Using a preprocessed internal query description referenced by $rootid, compute
 229+ * the proper debug output for the given query.
 230+ *
 231+ * @param SMWQuery $query
 232+ * @param integer $rootid
 233+ */
 234+ // modified by ning, based on getDebugQueryResult, getInstanceQueryResult
 235+ protected function getNMQueryResult( SMWQuery $query, $rootid ) {
 236+ wfProfileIn( 'SMWSQLStore2Queries::getNMQueryResult (SMW)' );
 237+ $qobj = $this->m_queries[$rootid];
 238+
 239+ if ( $qobj->joinfield !== '' ) {
 240+ $sql = "SELECT DISTINCT $qobj->alias.smw_title AS t,$qobj->alias.smw_namespace AS ns FROM " .
 241+ $this->m_dbs->tableName( $qobj->jointable ) . " AS $qobj->alias" . $qobj->from .
 242+ ( ( $qobj->where == '' ) ? '':' WHERE ' ) . $qobj->where;
 243+ } else { // empty result, no query needed
 244+ wfProfileOut( 'SMWSQLStore2Queries::getNMQueryResult (SMW)' );
 245+ return false;
 246+ }
 247+
 248+ $tmp = '';
 249+ foreach ( $this->m_querylog as $table => $log ) {
 250+ foreach ( $log as $l => $v ) {
 251+ $tmp .= ( $tmp != '' ? ';':'' ) . "$table:$l";
 252+ }
 253+ }
 254+ $result = array( 'sql' => $sql, 'tmp_hierarchy' => $tmp, 'page_ids' => array() );
 255+
 256+ $res = $this->m_dbs->select( $this->m_dbs->tableName( $qobj->jointable ) . " AS $qobj->alias" . $qobj->from, "DISTINCT $qobj->alias.smw_title AS t,$qobj->alias.smw_namespace AS ns", $qobj->where, 'SMW::getNMQueryResult' );
 257+ while ( $row = $this->m_dbs->fetchObject( $res ) ) {
 258+ if ( $row->ns != NS_MAIN ) continue;
 259+
 260+ $title = Title::makeTitle( $row->ns, $row->t );
 261+ $result['page_ids'][] = $title->getArticleID();
 262+ }
 263+ $this->m_dbs->freeResult( $res );
 264+
 265+ wfProfileOut( 'SMWSQLStore2Queries::getNMQueryResult (SMW)' );
 266+ return $result;
 267+ }
 268+
 269+ /**
 270+ * Create a new SMWSQLStore2Query object that can be used to obtain results
 271+ * for the given description. The result is stored in $this->m_queries
 272+ * using a numeric key that is returned as a result of the function.
 273+ * Returns -1 if no query was created.
 274+ * @todo The case of nominal classes (top-level SMWValueDescription) still
 275+ * makes some assumptions about the table structure, especially about the
 276+ * name of the joinfield (o_id). Better extend compileAttributeWhere to
 277+ * deal with this case.
 278+ *
 279+ * @param SMWDescription $description
 280+ *
 281+ * @return integer
 282+ */
 283+ protected function compileQueries( SMWDescription $description ) {
 284+ $qid = SMWSQLStore2Query::$qnum;
 285+ $query = new SMWSQLStore2Query();
 286+
 287+ if ( $description instanceof SMWSomeProperty ) {
 288+ $this->compilePropertyCondition( $query, $description->getProperty(), $description->getDescription() );
 289+ // Compilation has set type to NOQUERY: drop condition.
 290+ if ( $query->type == SMW_SQL2_NOQUERY ) $qid = - 1;
 291+ } elseif ( $description instanceof SMWNamespaceDescription ) {
 292+ // TODO: One instance of smw_ids on s_id always suffices (swm_id is KEY)! Doable in execution ... (PERFORMANCE)
 293+ $query->jointable = 'smw_ids';
 294+ $query->joinfield = "$query->alias.smw_id";
 295+ $query->where = "$query->alias.smw_namespace=" . $this->m_dbs->addQuotes( $description->getNamespace() );
 296+ } elseif ( ( $description instanceof SMWConjunction ) || ( $description instanceof SMWDisjunction ) ) {
 297+ $query->type = ( $description instanceof SMWConjunction ) ? SMW_SQL2_CONJUNCTION:SMW_SQL2_DISJUNCTION;
 298+
 299+ foreach ( $description->getDescriptions() as $subdesc ) {
 300+ $sub = $this->compileQueries( $subdesc );
 301+ if ( $sub >= 0 ) {
 302+ $query->components[$sub] = true;
 303+ }
 304+ }
 305+
 306+ // All subconditions failed, drop this as well.
 307+ if ( count( $query->components ) == 0 ) $qid = - 1;
 308+ } elseif ( $description instanceof SMWClassDescription ) {
 309+ $cqid = SMWSQLStore2Query::$qnum;
 310+ $cquery = new SMWSQLStore2Query();
 311+ $cquery->type = SMW_SQL2_CLASS_HIERARCHY;
 312+ $cquery->joinfield = array();
 313+
 314+ foreach ( $description->getCategories() as $cat ) {
 315+ $cid = $this->m_store->getSMWPageID( $cat->getDBkey(), NS_CATEGORY, $cat->getInterwiki() );
 316+ if ( $cid != 0 ) {
 317+ $cquery->joinfield[] = $cid;
 318+ }
 319+ }
 320+
 321+ if ( count( $cquery->joinfield ) == 0 ) { // Empty result.
 322+ $query->type = SMW_SQL2_VALUE;
 323+ $query->jointable = '';
 324+ $query->joinfield = '';
 325+ } else { // Instance query with dicjunction of classes (categories)
 326+ $query->jointable = 'smw_inst2';
 327+ $query->joinfield = "$query->alias.s_id";
 328+ $query->components[$cqid] = "$query->alias.o_id";
 329+ $this->m_queries[$cqid] = $cquery;
 330+ }
 331+ } elseif ( $description instanceof SMWValueDescription ) { // Only type '_wpg' objects can appear on query level (essentially as nominal classes).
 332+ if ( $description->getDatavalue()->getTypeID() == '_wpg' ) {
 333+ if ( $description->getComparator() == SMW_CMP_EQ ) {
 334+ $query->type = SMW_SQL2_VALUE;
 335+ $oid = $this->m_store->getSMWPageID( $description->getDatavalue()->getDBkey(), $description->getDatavalue()->getNamespace(), $description->getDatavalue()->getInterwiki() );
 336+ $query->joinfield = array( $oid );
 337+ } else { // Join with smw_ids needed for other comparators (apply to title string).
 338+ $query->jointable = 'smw_ids';
 339+ $query->joinfield = "$query->alias.smw_id";
 340+ $value = $description->getDatavalue()->getSortkey();
 341+
 342+ switch ( $description->getComparator() ) {
 343+ case SMW_CMP_LEQ: $comp = '<='; break;
 344+ case SMW_CMP_GEQ: $comp = '>='; break;
 345+ case SMW_CMP_NEQ: $comp = '!='; break;
 346+ case SMW_CMP_LIKE: case SMW_CMP_NLKE:
 347+ $comp = ' LIKE ';
 348+ if ( $description->getComparator() == SMW_CMP_NLKE ) $comp = " NOT{$comp}";
 349+ $value = str_replace( array( '%', '_', '*', '?' ), array( '\%', '\_', '%', '_' ), $value );
 350+ break;
 351+ }
 352+
 353+ $query->where = "$query->alias.smw_sortkey$comp" . $this->m_dbs->addQuotes( $value );
 354+ }
 355+ }
 356+ } elseif ( $description instanceof SMWConceptDescription ) { // fetch concept definition and insert it here
 357+ $cid = $this->m_store->getSMWPageID( $description->getConcept()->getDBkey(), SMW_NS_CONCEPT, '' );
 358+ $row = $this->m_dbs->selectRow(
 359+ 'smw_conc2',
 360+ array( 'concept_txt', 'concept_features', 'concept_size', 'concept_depth', 'cache_date' ),
 361+ array( 's_id' => $cid ),
 362+ 'SMWSQLStore2Queries::compileQueries'
 363+ );
 364+
 365+ if ( $row === false ) { // No description found, concept does not exist.
 366+ // keep the above query object, it yields an empty result
 367+ // TODO: announce an error here? (maybe not, since the query processor can check for
 368+ // non-existing concept pages which is probably the main reason for finding nothing here)
 369+ } else {
 370+ global $smwgQConceptCaching, $smwgQMaxSize, $smwgQMaxDepth, $smwgQFeatures, $smwgQConceptCacheLifetime;
 371+
 372+ $may_be_computed = ( $smwgQConceptCaching == CONCEPT_CACHE_NONE ) ||
 373+ ( ( $smwgQConceptCaching == CONCEPT_CACHE_HARD ) && ( ( ~( ~( $row->concept_features + 0 ) | $smwgQFeatures ) ) == 0 ) &&
 374+ ( $smwgQMaxSize >= $row->concept_size ) && ( $smwgQMaxDepth >= $row->concept_depth ) );
 375+
 376+ if ( $row->cache_date &&
 377+ ( ( $row->cache_date > ( strtotime( "now" ) - $smwgQConceptCacheLifetime * 60 ) ) ||
 378+ !$may_be_computed ) ) { // Cached concept, use cache unless it is dead and can be revived.
 379+
 380+ $query->jointable = 'smw_conccache';
 381+ $query->joinfield = "$query->alias.s_id";
 382+ $query->where = "$query->alias.o_id=" . $this->m_dbs->addQuotes( $cid );
 383+ } elseif ( $row->concept_txt ) { // Parse description and process it recursively.
 384+ if ( $may_be_computed ) {
 385+ $qp = new SMWQueryParser();
 386+
 387+ // No defaultnamespaces here; If any, these are already in the concept.
 388+ $desc = $qp->getQueryDescription( $row->concept_txt );
 389+ $qid = $this->compileQueries( $desc );
 390+ if ( $qid != -1 ) {
 391+ $query = $this->m_queries[$qid];
 392+ } else { // somehow the concept query is no longer valid; maybe some syntax changed (upgrade) or global settings were modified since storing it
 393+ smwfLoadExtensionMessages( 'SemanticMediaWiki' );
 394+ $this->m_errors[] = wfMsg( 'smw_emptysubquery' ); // not quite the right message, but this case is very rare; let us not make detailed messages for this
 395+ }
 396+ } else {
 397+ smwfLoadExtensionMessages( 'SemanticMediaWiki' );
 398+ $this->m_errors[] = wfMsg( 'smw_concept_cache_miss', $description->getConcept()->getText() );
 399+ }
 400+ } // else: no cache, no description (this may happen); treat like empty concept
 401+ }
 402+ } else { // (e.g. SMWThingDescription)
 403+ $qid = - 1; // no condition
 404+ }
 405+
 406+ if ( $qid >= 0 ) { // Success, keep query object, propagate sortkeys from subqueries.
 407+ $this->m_queries[$qid] = $query;
 408+
 409+ if ( $query->type != SMW_SQL2_DISJUNCTION ) { // Sortkeys are killed by disjunctions (not all parts may have them),
 410+ // NOTE: preprocessing might try to push disjunctions downwards to safe sortkey, but this seems to be minor
 411+ foreach ( $query->components as $cid => $field ) {
 412+ $query->sortfields = array_merge( $this->m_queries[$cid]->sortfields, $query->sortfields );
 413+ }
 414+ }
 415+ }
 416+
 417+ return $qid;
 418+ }
 419+
 420+ /**
 421+ * Modify the given query object to account for some property condition for
 422+ * the given property. If it is not possible to generate a query for the
 423+ * given data, the query type is changed to SMW_SQL2_NOQUERY. Callers need
 424+ * to check for this and discard the query in this case.
 425+ * @todo Check if hierarchy queries work as expected.
 426+ */
 427+ protected function compilePropertyCondition( SMWSQLStore2Query $query, $property, SMWDescription $valuedesc ) {
 428+ $tableid = SMWSQLStore2::findPropertyTableID( $property );
 429+
 430+ if ( $tableid == '' ) { // probably a type-polymorphic property
 431+ $typeid = $valuedesc->getTypeID();
 432+ $tableid = SMWSQLStore2::findTypeTableID( $typeid );
 433+ } else { // normal property
 434+ $typeid = $property->getPropertyTypeID();
 435+ }
 436+
 437+ if ( $tableid == '' ) { // Still no table to query? Give up.
 438+ $query->type = SMW_SQL2_NOQUERY;
 439+ return;
 440+ }
 441+
 442+ $proptables = SMWSQLStore2::getPropertyTables();
 443+ $proptable = $proptables[$tableid];
 444+
 445+ if ( !$proptable->idsubject ) { // no queries with such tables (there is really no demand, as only redirects are affected)
 446+ $query->type = SMW_SQL2_NOQUERY;
 447+ return;
 448+ }
 449+
 450+ list( $sig, $valueindex, $labelindex ) = SMWSQLStore2::getTypeSignature( $typeid );
 451+ $sortkey = $property->getDBkey(); // TODO: strictly speaking, the DB key is not what we want here, since sortkey is based on a "wiki value"
 452+
 453+ // *** Basic settings: table, joinfield, and objectfields ***//
 454+ $query->jointable = $proptable->name;
 455+
 456+ if ( $property->isInverse() ) { // see if we can support inverses by inverting the proptable data
 457+ if ( ( count( $proptable->objectfields ) == 1 ) && ( reset( $proptable->objectfields ) == 'p' ) ) {
 458+ $query->joinfield = $query->alias . '.' . reset( array_keys( $proptable->objectfields ) );
 459+ $objectfields = array( 's_id' => 'p' );
 460+ $valueindex = $labelindex = 3; // should normally not change, but let's be strict
 461+ } else { // no inverses supported for this property, stop here
 462+ $query->type = SMW_SQL2_NOQUERY;
 463+ return;
 464+ }
 465+ } else { // normal forward property
 466+ $query->joinfield = "{$query->alias}.s_id";
 467+ $objectfields = $proptable->objectfields;
 468+ }
 469+
 470+ // *** Add conditions for selecting rows for this property, maybe with a hierarchy ***//
 471+ if ( $proptable->fixedproperty == false ) {
 472+ $pid = $this->m_store->getSMWPropertyID( $property );
 473+
 474+ if ( !$property->getPropertyID() || ( $property->getPropertyTypeID() != '__err' ) ) {
 475+ // also make property hierarchy (may or may not be executed later on)
 476+ // exclude type-polymorphic properties _1, _2, ... (2nd check above suffices, but 1st is faster to check)
 477+ // we could also exclude other cases here, if desired
 478+ $pqid = SMWSQLStore2Query::$qnum;
 479+ $pquery = new SMWSQLStore2Query();
 480+ $pquery->type = SMW_SQL2_PROP_HIERARCHY;
 481+ $pquery->joinfield = array( $pid );
 482+ $query->components[$pqid] = "{$query->alias}.p_id";
 483+ $this->m_queries[$pqid] = $pquery;
 484+ } else {
 485+ $query->where = "{$query->alias}.p_id=" . $this->m_dbs->addQuotes( $pid );
 486+ }
 487+ } // else: no property column, no hierarchy queries
 488+
 489+ // *** Add conditions on the value of the property ***//
 490+ if ( ( count( $objectfields ) == 1 ) && ( reset( $objectfields ) == 'p' ) ) { // page description, process like main query
 491+ $sub = $this->compileQueries( $valuedesc );
 492+ $objectfield = reset( array_keys( $objectfields ) );
 493+
 494+ if ( $sub >= 0 ) {
 495+ $query->components[$sub] = "{$query->alias}.{$objectfield}";
 496+ }
 497+ } else { // non-page value description; expressive features mainly based on value
 498+ $this->compileAttributeWhere( $query, $valuedesc, $proptable, $valueindex );
 499+ // (no need to pass on $objectfields since they are just as in $proptable in this case)
 500+ }
 501+
 502+ // *** Incorporate ordering if desired ***//
 503+ if ( ( $valueindex >= 0 ) && array_key_exists( $sortkey, $this->m_sortkeys ) ) {
 504+ // This code might be overly general: it supports datatypes of arbitrary signatures
 505+ // and valueindex (sortkeys). It can even order pages by something other than their
 506+ // sortkey (e.g. by their namespace?!), and it can handle values consisting of a page
 507+ // and some more data fields before or after. Supporting pages in this way requires us
 508+ // to iterate over the table fields since one page corresponds to four values in a
 509+ // type's signature. Thankfully, signatures are short so this iteration is not notable.
 510+ $smwidjoinfield = false;
 511+ $fieldName = $this->getDBFieldsForDVIndex( $objectfields, $valueindex, $smwidjoinfield );
 512+
 513+ if ( $fieldName ) {
 514+ if ( $smwidjoinfield ) {
 515+ // TODO: is this smw_ids possibly duplicated in the query? Can we prevent that? (PERFORMANCE)
 516+ $query->from = ' INNER JOIN ' . $this->m_dbs->tableName( 'smw_ids' ) .
 517+ " AS ids{$query->alias} ON ids{$query->alias}.smw_id={$query->alias}.{$smwidjoinfield}";
 518+ $query->sortfields[$sortkey] = "ids{$query->alias}.{$fieldName}";
 519+ } else {
 520+ $query->sortfields[$sortkey] = "{$query->alias}.{$fieldName}";
 521+ }
 522+ }
 523+ }
 524+ }
 525+
 526+ /**
 527+ * Helper function for matching an index that refers to the DB keys (and
 528+ * thus signature) of a datatype to the database fields of a fitting
 529+ * property table (the objectfields array of which is given).
 530+ * The $fieldname is set call-by-ref, where the parameter $smwidjoinfield
 531+ * is set to the field of $objectfields on which smw_ids.smw_id needs to
 532+ * be joined if $smwidjoinfield refers to a field in smw_ids. This might
 533+ * be needed for page-type values. If the value is not in smw_ids, then
 534+ * $fieldname refers to $objectfields and $smwidjoinfield is false. If the
 535+ * given index could not be matched, $fieldname is false.
 536+ *
 537+ * @param array $objectFields
 538+ * @param integer $index
 539+ * @param $smwidjoinfield
 540+ *
 541+ * @return array with at least one element or false
 542+ */
 543+ protected function getDBFieldsForDVIndex( array $objectFields, $index, &$smwidjoinfield ) {
 544+ $fieldName = false;
 545+
 546+ $curindex = 0;
 547+ foreach ( $objectFields as $fname => $ftype ) {
 548+ if ( $ftype == 'p' ) { // special treatment since "p" consists of 4 fields that are kept in smw_ids
 549+ if ( $curindex + 4 >= $index ) {
 550+ $idfieldnames = array( 'smw_title', 'smw_namespace', 'smw_iw', 'smw_sortkey' );
 551+ $smwidjoinfield = $fname;
 552+ $fieldName = $idfieldnames[$index - $curindex];
 553+ break;
 554+ }
 555+ $curindex += 3;
 556+ } elseif ( $curindex == $index ) {
 557+ $smwidjoinfield = false;
 558+ $fieldName = $fname;
 559+ break;
 560+ }
 561+ $curindex++;
 562+ }
 563+
 564+ return $fieldName;
 565+ }
 566+
 567+ /**
 568+ * Given an SMWDescription that is just a conjunction or disjunction of
 569+ * SMWValueDescription objects, create and return a plain WHERE condition
 570+ * string for it.
 571+ *
 572+ * @param $query
 573+ * @param SMWDescription $description
 574+ * @param SMWSQLStore2Table $proptable
 575+ * @param integer $valueIndex
 576+ * @param string $operator
 577+ */
 578+ protected function compileAttributeWhere(
 579+ $query, SMWDescription $description, SMWSQLStore2Table $proptable, $valueIndex, $operator = 'AND' ) {
 580+
 581+ $where = '';
 582+
 583+ if ( $description instanceof SMWValueDescription ) {
 584+ $dv = $description->getDatavalue();
 585+ $keys = $dv->getDBkeys();
 586+
 587+ // Try comparison based on value field and comparator.
 588+ if ( $valueIndex >= 0 ) {
 589+ // Find field name for comparison.
 590+ $smwidjoinfield = false;
 591+ $fieldName = $this->getDBFieldsForDVIndex( $proptable->objectfields, $valueIndex, $smwidjoinfield );
 592+
 593+ // Do not support smw_id joined data for now.
 594+ if ( $fieldName && !$smwidjoinfield ) {
 595+ $comparator = false;
 596+ $customSQL = false;
 597+
 598+ // See if the getSQLCondition method exists and call it if this is the case.
 599+ if ( method_exists( $description, 'getSQLCondition' ) ) {
 600+ $customSQL = $description->getSQLCondition( $query->alias, array_keys( $proptable->objectfields ), $this->m_dbs );
 601+ }
 602+
 603+ if ( $customSQL ) {
 604+ $where = $customSQL;
 605+ } else {
 606+ $value = $keys[$valueIndex];
 607+
 608+ switch ( $description->getComparator() ) {
 609+ case SMW_CMP_EQ: $comparator = '='; break;
 610+ case SMW_CMP_LEQ: $comparator = '<='; break;
 611+ case SMW_CMP_GEQ: $comparator = '>='; break;
 612+ case SMW_CMP_NEQ: $comparator = '!='; break;
 613+ case SMW_CMP_LIKE: case SMW_CMP_NLKE:
 614+ $comparator = ' LIKE ';
 615+ if ( $description->getComparator() == SMW_CMP_NLKE ) $comparator = " NOT{$comparator}";
 616+ $value = str_replace( array( '%', '_', '*', '?' ), array( '\%', '\_', '%', '_' ), $value );
 617+ }
 618+
 619+ if ( $comparator ) {
 620+ $where = "$query->alias.{$fieldName}{$comparator}" . $this->m_dbs->addQuotes( $value );
 621+ }
 622+ }
 623+ }
 624+ }
 625+
 626+ if ( $where == '' ) { // comparators did not apply; match all fields
 627+ $i = 0;
 628+
 629+ foreach ( $proptable->objectfields as $fname => $ftype ) {
 630+ if ( $i >= count( $keys ) ) break;
 631+
 632+ if ( $ftype == 'p' ) { // Special case: page id, resolve this in advance
 633+ $oid = $this->getSMWPageID( $keys[$i], $keys[$i + 1], $keys[$i + 2] );
 634+ $i += 3; // skip these additional values (sortkey not needed here)
 635+ $where .= ( $where ? ' AND ' : '' ) . "{$query->alias}.$fname=" . $this->m_dbs->addQuotes( $oid );
 636+ } elseif ( $ftype != 'l' ) { // plain value, but not a text blob
 637+ $where .= ( $where ? ' AND ' : '' ) . "{$query->alias}.$fname=" . $this->m_dbs->addQuotes( $keys[$i] );
 638+ }
 639+
 640+ $i++;
 641+ }
 642+ }
 643+
 644+ } elseif ( ( $description instanceof SMWConjunction ) || ( $description instanceof SMWDisjunction ) ) {
 645+ $op = ( $description instanceof SMWConjunction ) ? 'AND' : 'OR';
 646+
 647+ foreach ( $description->getDescriptions() as $subdesc ) {
 648+ $this->compileAttributeWhere( $query, $subdesc, $proptable, $valueIndex, $op );
 649+ }
 650+ }
 651+
 652+ if ( $where != '' ) $query->where .= ( $query->where ? " $operator " : '' ) . "($where)";
 653+ }
 654+
 655+ /**
 656+ * Process stored queries and change store accordingly. The query obj is modified
 657+ * so that it contains non-recursive description of a select to execute for getting
 658+ * the actual result.
 659+ *
 660+ * @param SMWSQLStore2Query $query
 661+ */
 662+ protected function executeQueries( SMWSQLStore2Query &$query ) {
 663+ global $wgDBtype;
 664+
 665+ switch ( $query->type ) {
 666+ case SMW_SQL2_TABLE: // Normal query with conjunctive subcondition.
 667+ foreach ( $query->components as $qid => $joinfield ) {
 668+ $subquery = $this->m_queries[$qid];
 669+ $this->executeQueries( $subquery );
 670+
 671+ if ( $subquery->jointable != '' ) { // Join with jointable.joinfield
 672+ $query->from .= ' INNER JOIN ' . $this->m_dbs->tableName( $subquery->jointable ) . " AS $subquery->alias ON $joinfield=" . $subquery->joinfield;
 673+ } elseif ( $subquery->joinfield !== '' ) { // Require joinfield as "value" via WHERE.
 674+ $condition = '';
 675+
 676+ foreach ( $subquery->joinfield as $value ) {
 677+ $condition .= ( $condition ? ' OR ':'' ) . "$joinfield=" . $this->m_dbs->addQuotes( $value );
 678+ }
 679+
 680+ if ( count( $subquery->joinfield ) > 1 ) {
 681+ $condition = "($condition)";
 682+ }
 683+
 684+ $query->where .= ( ( $query->where == '' ) ? '':' AND ' ) . $condition;
 685+ } else { // interpret empty joinfields as impossible condition (empty result)
 686+ $query->joinfield = ''; // make whole query false
 687+ $query->jointable = '';
 688+ $query->where = '';
 689+ $query->from = '';
 690+ break;
 691+ }
 692+
 693+ if ( $subquery->where != '' ) {
 694+ $query->where .= ( ( $query->where == '' ) ? '':' AND ' ) . '(' . $subquery->where . ')';
 695+ }
 696+
 697+ $query->from .= $subquery->from;
 698+ }
 699+
 700+ $query->components = array();
 701+ break;
 702+ case SMW_SQL2_CONJUNCTION:
 703+ // pick one subquery with jointable as anchor point ...
 704+ reset( $query->components );
 705+ $key = false;
 706+
 707+ foreach ( $query->components as $qkey => $qid ) {
 708+ if ( $this->m_queries[$qkey]->jointable != '' ) {
 709+ $key = $qkey;
 710+ break;
 711+ }
 712+ }
 713+
 714+ if ( $key !== false ) {
 715+ $result = $this->m_queries[$key];
 716+ unset( $query->components[$key] );
 717+
 718+ // Execute it first (may change jointable and joinfield, e.g. when making temporary tables)
 719+ $this->executeQueries( $result );
 720+
 721+ // ... and append to this query the remaining queries.
 722+ foreach ( $query->components as $qid => $joinfield ) {
 723+ $result->components[$qid] = $result->joinfield;
 724+ }
 725+
 726+ // Second execute, now incorporating remaining conditions.
 727+ $this->executeQueries( $result );
 728+ } else { // Only fixed values in conjunction, make a new value without joining.
 729+ $key = $qkey;
 730+ $result = $this->m_queries[$key];
 731+ unset( $query->components[$key] );
 732+
 733+ foreach ( $query->components as $qid => $joinfield ) {
 734+ if ( $result->joinfield != $this->m_queries[$qid]->joinfield ) {
 735+ $result->joinfield = ''; // all other values should already be ''
 736+ break;
 737+ }
 738+ }
 739+ }
 740+ $query = $result;
 741+ break;
 742+ case SMW_SQL2_DISJUNCTION:
 743+ // modified by ning, disable TEMPORARY tables
 744+// if ( $this->m_qmode !== SMWQuery::MODE_DEBUG ) {
 745+// $this->m_dbs->query( $this->getCreateTempIDTableSQL( $this->m_dbs->tableName( $query->alias ) ), 'SMW::executeQueries' );
 746+// }
 747+//
 748+// $this->m_querylog[$query->alias] = array();
 749+
 750+ $sql = array();
 751+ foreach ( $query->components as $qid => $joinfield ) {
 752+ $subquery = $this->m_queries[$qid];
 753+ $this->executeQueries( $subquery );
 754+// $sql = '';
 755+
 756+ if ( $subquery->jointable != '' ) {
 757+// $sql = 'INSERT ' . ( ( $wgDBtype == 'postgres' ) ? '':'IGNORE ' ) . 'INTO ' .
 758+// $this->m_dbs->tableName( $query->alias ) .
 759+// " SELECT $subquery->joinfield FROM " . $this->m_dbs->tableName( $subquery->jointable ) .
 760+// " AS $subquery->alias $subquery->from" . ( $subquery->where ? " WHERE $subquery->where":'' );
 761+ $sql[] = "(SELECT $subquery->joinfield AS id FROM " . $this->m_dbs->tableName( $subquery->jointable ) .
 762+ " AS $subquery->alias $subquery->from" . ( $subquery->where ? " WHERE $subquery->where":'' ) . ")";
 763+ } elseif ( $subquery->joinfield !== '' ) {
 764+ // NOTE: this works only for single "unconditional" values without further
 765+ // WHERE or FROM. The execution must take care of not creating any others.
 766+ $values = '';
 767+
 768+ foreach ( $subquery->joinfield as $value ) {
 769+ $values .= ( $values ? ',' : '' ) . '(' . $this->m_dbs->addQuotes( $value ) . ')';
 770+ }
 771+
 772+// $sql = 'INSERT ' . ( ( $wgDBtype == 'postgres' ) ? '':'IGNORE ' ) . 'INTO ' . $this->m_dbs->tableName( $query->alias ) . " (id) VALUES $values";
 773+ $sql[] = "(SELECT smw_id AS id FROM " . $this->m_dbs->tableName( 'smw_ids' ) . " WHERE smw_id IN ($values))";
 774+ } // else: // interpret empty joinfields as impossible condition (empty result), ignore
 775+// if ( $sql ) {
 776+// $this->m_querylog[$query->alias][] = $sql;
 777+//
 778+// if ( $this->m_qmode !== SMWQuery::MODE_DEBUG ) {
 779+// $this->m_dbs->query( $sql , 'SMW::executeQueries' );
 780+// }
 781+// }
 782+ }
 783+
 784+// $query->jointable = $query->alias;
 785+ $query->jointable = "(" . implode( " UNION ", $sql ) . ")";
 786+ $query->joinfield = "$query->alias.id";
 787+ $query->sortfields = array(); // Make sure we got no sortfields.
 788+ // TODO: currently this eliminates sortkeys, possibly keep them (needs different temp table format though, maybe not such a good thing to do)
 789+ break;
 790+ case SMW_SQL2_PROP_HIERARCHY: case SMW_SQL2_CLASS_HIERARCHY: // make a saturated hierarchy
 791+ $this->executeHierarchyQuery( $query );
 792+ break;
 793+ case SMW_SQL2_VALUE: break; // nothing to do
 794+ }
 795+ }
 796+
 797+ /**
 798+ * Find subproperties or subcategories. This may require iterative computation,
 799+ * and temporary tables are used in many cases.
 800+ *
 801+ * @param SMWSQLStore2Query $query
 802+ */
 803+ protected function executeHierarchyQuery( SMWSQLStore2Query &$query ) {
 804+ global $wgDBtype;
 805+ global $smwgQSubpropertyDepth, $smwgQSubcategoryDepth;
 806+
 807+ $fname = "SMWSQLStore2Queries::executeQueries-hierarchy-$query->type (SMW)";
 808+ wfProfileIn( $fname );
 809+
 810+ $depth = ( $query->type == SMW_SQL2_PROP_HIERARCHY ) ? $smwgQSubpropertyDepth : $smwgQSubcategoryDepth;
 811+
 812+ if ( $depth <= 0 ) { // treat as value, no recursion
 813+ $query->type = SMW_SQL2_VALUE;
 814+ wfProfileOut( $fname );
 815+ return;
 816+ }
 817+
 818+ $values = '';
 819+ $valuecond = '';
 820+
 821+ foreach ( $query->joinfield as $value ) {
 822+ $values .= ( $values ? ',':'' ) . '(' . $this->m_dbs->addQuotes( $value ) . ')';
 823+ $valuecond .= ( $valuecond ? ' OR ':'' ) . 'o_id=' . $this->m_dbs->addQuotes( $value );
 824+ }
 825+
 826+ $smwtable = $this->m_dbs->tableName( ( $query->type == SMW_SQL2_PROP_HIERARCHY ) ? 'smw_subp2':'smw_subs2' );
 827+
 828+ // Try to safe time (SELECT is cheaper than creating/dropping 3 temp tables):
 829+ $res = $this->m_dbs->select( $smwtable, 's_id', $valuecond, array( 'LIMIT' => 1 ) );
 830+
 831+ if ( !$this->m_dbs->fetchObject( $res ) ) { // no subobjects, we are done!
 832+ $this->m_dbs->freeResult( $res );
 833+ $query->type = SMW_SQL2_VALUE;
 834+ wfProfileOut( $fname );
 835+ return;
 836+ }
 837+
 838+ $this->m_dbs->freeResult( $res );
 839+ $tablename = $this->m_dbs->tableName( $query->alias );
 840+ // modified by ning
 841+// $this->m_querylog[$query->alias] = array( "Recursively computed hierarchy for element(s) $values." );
 842+ $this->m_querylog[$query->alias]["$depth:$values"] = "Recursively computed hierarchy for element(s) $values.";
 843+ $query->jointable = $query->alias;
 844+ $query->joinfield = "$query->alias.id";
 845+
 846+ if ( $this->m_qmode == SMWQuery::MODE_DEBUG ) {
 847+ wfProfileOut( $fname );
 848+ return; // No real queries in debug mode.
 849+ }
 850+
 851+ $this->m_dbs->query( $this->getCreateTempIDTableSQL( $tablename ), 'SMW::executeHierarchyQuery' );
 852+
 853+ if ( array_key_exists( $values, $this->m_hierarchies ) ) { // Just copy known result.
 854+ $this->m_dbs->query( "INSERT INTO $tablename (id) SELECT id" .
 855+ ' FROM ' . $this->m_hierarchies[$values],
 856+ 'SMW::executeHierarchyQuery' );
 857+ wfProfileOut( $fname );
 858+ return;
 859+ }
 860+
 861+ // NOTE: we use two helper tables. One holds the results of each new iteration, one holds the
 862+ // results of the previous iteration. One could of course do with only the above result table,
 863+ // but then every iteration would use all elements of this table, while only the new ones
 864+ // obtained in the previous step are relevant. So this is a performance measure.
 865+ $tmpnew = 'smw_new';
 866+ $tmpres = 'smw_res';
 867+ $this->m_dbs->query( $this->getCreateTempIDTableSQL( $tmpnew ), 'SMW::executeQueries' );
 868+ $this->m_dbs->query( $this->getCreateTempIDTableSQL( $tmpres ), 'SMW::executeQueries' );
 869+ $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? "" : "IGNORE" ) . " INTO $tablename (id) VALUES $values", 'SMW::executeHierarchyQuery' );
 870+ $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? "" : "IGNORE" ) . " INTO $tmpnew (id) VALUES $values", 'SMW::executeHierarchyQuery' );
 871+
 872+ for ( $i = 0; $i < $depth; $i++ ) {
 873+ $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? '' : 'IGNORE ' ) . "INTO $tmpres (id) SELECT s_id" . ( $wgDBtype == 'postgres' ? '::integer':'' ) . " FROM $smwtable, $tmpnew WHERE o_id=id",
 874+ 'SMW::executeHierarchyQuery' );
 875+ if ( $this->m_dbs->affectedRows() == 0 ) { // no change, exit loop
 876+ break;
 877+ }
 878+
 879+ $this->m_dbs->query( "INSERT " . ( ( $wgDBtype == 'postgres' ) ? '' : 'IGNORE ' ) . "INTO $tablename (id) SELECT $tmpres.id FROM $tmpres",
 880+ 'SMW::executeHierarchyQuery' );
 881+
 882+ if ( $this->m_dbs->affectedRows() == 0 ) { // no change, exit loop
 883+ break;
 884+ }
 885+
 886+ $this->m_dbs->query( 'TRUNCATE TABLE ' . $tmpnew, 'SMW::executeHierarchyQuery' ); // empty "new" table
 887+ $tmpname = $tmpnew;
 888+ $tmpnew = $tmpres;
 889+ $tmpres = $tmpname;
 890+ }
 891+
 892+ $this->m_hierarchies[$values] = $tablename;
 893+ $this->m_dbs->query( ( ( $wgDBtype == 'postgres' ) ? 'DROP TABLE IF EXISTS smw_new' : 'DROP TEMPORARY TABLE smw_new' ), 'SMW::executeHierarchyQuery' );
 894+ $this->m_dbs->query( ( ( $wgDBtype == 'postgres' ) ? 'DROP TABLE IF EXISTS smw_res' : 'DROP TEMPORARY TABLE smw_res' ), 'SMW::executeHierarchyQuery' );
 895+
 896+ wfProfileOut( $fname );
 897+ }
 898+
 899+ /**
 900+ * After querying, make sure no temporary database tables are left.
 901+ * @todo I might be better to keep the tables and possibly reuse them later
 902+ * on. Being temporary, the tables will vanish with the session anyway.
 903+ */
 904+ protected function cleanUp() {
 905+ global $wgDBtype;
 906+ if ( $this->m_qmode !== SMWQuery::MODE_DEBUG ) {
 907+ foreach ( $this->m_querylog as $table => $log ) {
 908+ $this->m_dbs->query( ( ( $wgDBtype == 'postgres' ) ? "DROP TABLE IF EXISTS ":"DROP TEMPORARY TABLE " ) . $this->m_dbs->tableName( $table ), 'SMW::getQueryResult' );
 909+ }
 910+ }
 911+ }
 912+
 913+ /**
 914+ * Get SQL code suitable to create a temporary table of the given name, used to store ids.
 915+ * MySQL can do that simply by creating new temporary tables. PostgreSQL first checks if such
 916+ * a table exists, so the code is ready to reuse existing tables if the code was modified to
 917+ * keep them after query answering. Also, PostgreSQL tables will use a RULE to achieve built-in
 918+ * duplicate elimination. The latter is done using INSERT IGNORE in MySQL.
 919+ *
 920+ * @param string $tablename
 921+ */
 922+ protected function getCreateTempIDTableSQL( $tablename ) {
 923+ global $wgDBtype;
 924+
 925+ if ( $wgDBtype == 'postgres' ) { // PostgreSQL: no memory tables, use RULE to emulate INSERT IGNORE
 926+ return "CREATE OR REPLACE FUNCTION create_" . $tablename . "() RETURNS void AS "
 927+ . "$$ "
 928+ . "BEGIN "
 929+ . " IF EXISTS(SELECT NULL FROM pg_tables WHERE tablename='" . $tablename . "' AND schemaname = ANY (current_schemas(true))) "
 930+ . " THEN DELETE FROM " . $tablename . "; "
 931+ . " ELSE "
 932+ . " CREATE TEMPORARY TABLE " . $tablename . " (id INTEGER PRIMARY KEY); "
 933+ . " CREATE RULE " . $tablename . "_ignore AS ON INSERT TO " . $tablename . " WHERE (EXISTS (SELECT NULL FROM " . $tablename
 934+ . " WHERE (" . $tablename . ".id = new.id))) DO INSTEAD NOTHING; "
 935+ . " END IF; "
 936+ . "END; "
 937+ . "$$ "
 938+ . "LANGUAGE 'plpgsql'; "
 939+ . "SELECT create_" . $tablename . "(); ";
 940+ } else { // MySQL_ just a temporary table, use INSERT IGNORE later
 941+ return "CREATE TEMPORARY TABLE " . $tablename . "( id INT UNSIGNED KEY ) TYPE=MEMORY";
 942+ }
 943+ }
 944+}
Property changes on: trunk/extensions/SemanticNotifyMe/includes/storage/SMW_SQLStore2_QueriesNM.smw15.php
___________________________________________________________________
Added: svn:eol-style
945945 + native

Status & tagging log