/
MediawikiNavigator.php
527 lines (478 loc) · 17.7 KB
/
MediawikiNavigator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
<?php
/**
* Mediawiki Navigor class. Simple and manutenable cookie buffer and POST/GET access;
* oriented to file_get_contents() use.
* @version 1.0 2015-01-30
* @licence MIT
* @author ppkrauss
* @see https://github.com/ppKrauss/MediawikiNavigor
*
* EXAMPLE:
* $wbuff = new MediawikiNavigor('http://www.mywiki.org/wiki', 'MyUser', 'MyPass');
* var_dump($wbuff->cookies);
* $wikipage = $wbuff->get('/Test_page'); // or '/index.php?action=render&title=Test_page';
*/
class MediawikiNavigor {
var $base_url = ''; // default wiki or empty. parse_url()~"$scheme://$host/$path?$query..."
var $httpOptions = NULL; // refresh with httpOptions() method
var $cookies = NULL; // refresh with login() method
var $pageInUse = ''; // title or pageid, cache from last call.
var $pageInUse_idtype = 'title';
var $wikitext = NULL; // when get wikitext
var $wikitext_tpls = NULL;
var $wikitext_normalizeConfig = NULL;
var $wikitext_tpls_allParams = NULL; // for template help
/**
* Constructor.
* @param $base_url string base_url (starting with HTTP).
* @param $lgname string username.
* @param $lgpassword string password.
* @return boolean false on error.
*/
function __construct($base_url='',$lgname='',$lgpassword='') {
$ok = true;
$base_descr = parse_url($base_url);
if (substr($base_descr['scheme'],0,4)=='http') {
$this->wikitext_normalizeConfig = array(
'#spaces1'=>function ($k,$v) {
// remove tabs and extra-spaces, preserving internal \n's
return trim(preg_replace('/[ \t]+/s',' ',$v));
},
'CACHE'=>NULL,
);
if ($base_url) $this->base_url=$base_url;
if ($lgname)
$ok = $this->login($lgname,$lgpassword);
if (!$ok)
die("LOGIN ERROR");
} else { // scheme 'php' or 'path'
die("\nUNDER CONSTRUCTION schemes 'php' or 'path'\n");
}
}
/**
* Login with api.php in the base_url.
* @param $lgname string username.
* @param $lgpassword string password.
* @return boolean false on error.
*/
function login($lgname,$lgpassword) {
$api = '/api.php';
$data = array('action'=>'login', 'lgname'=>$lgname, 'lgpassword'=>$lgpassword,'format'=>'php');
$this->cookies = NULL; // clean
$wikisec = unserialize( $this->post($data,$api) );
if ($wikisec['login']['result']=='NeedToken'){ // see http://www.mediawiki.org/wiki/API:Login#Confirm_token
$data['lgtoken'] = $wikisec['login']['token'];
$ck_prefix = $wikisec['login']['cookieprefix'];
$this->cookies = array("{$ck_prefix}_session"=>$wikisec['login']['sessionid']);
$wikisec = unserialize( $this->post($data,$api) );
}
if ($wikisec['login']['result']!='Success')
return false; //die("LOGIN ERROR");
else {
$ck_prefix = $wikisec['login']['cookieprefix'];
$this->cookies = array(
"{$ck_prefix}_session" =>$wikisec['login']['sessionid'],
"{$ck_prefix}UserName" =>$wikisec['login']['lgusername'],
"{$ck_prefix}UserID" =>$wikisec['login']['lguserid'],
"{$ck_prefix}Token" =>$wikisec['login']['lgtoken']
);
return true;
}
} // func
function httpOptions($data=NULL){
if ( $this->cookies !== NULL ) {
$cookies = $this->assoc_join($this->cookies,'; ');
$cookies = "Cookie: $cookies\r\n";
} else $cookies='';
$this->httpOptions = $data?
array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n$cookies",
'method' => 'POST',
'content' => http_build_query($data),
))
: ($cookies? array('http'=>array('header'=>$cookies)): NULL); // GET
} // func
/**
* Execute file_get_contents() with POST method in the base_url. Use $this->cookies.
* @param $data array or NULL.
* @param $relat_url string (optional) URL relative for base_url.
* @param $refreshHttpOptions boolean (default=true) for refresh the httpOptions.
* @return string with contents, or FALSE on failure.
*/
function post($data,$relat_url='',$refreshHttpOptions=true, $debug=false) {
$url = $this->base_url.$relat_url;
if ($refreshHttpOptions) $this->httpOptions($data); // $data can be NULL
if ($debug) { // for terminal use
print "\n----\n---- DEBEUG_post $url\n";
var_dump($this->httpOptions);
}
return is_array($this->httpOptions)?
file_get_contents($url, false, stream_context_create($this->httpOptions) ): // GET or POST
file_get_contents($url); // GET
}
/**
* Wrap method for post(NULL,$relat_url).
* Execute file_get_contents() with GET method in the base_url. Use $this->cookies.
* @param $relat_url string (optional) URL relative for base_url.
* @return string with contents, or FALSE on failure.
*/
function get($relat_url='',$refreshHttpOptions=true) {
return $this->post(NULL,$relat_url,$refreshHttpOptions);
}
/**
* Tokenizes wikitex-templates. The template-parameters must be regular.
* To complex paramters, use https://www.mediawiki.org/wiki/Manual:Preprocessor.php
* @param $splitParams booleam to split content into params.
*/
function wikitextTpl_tokenize($splitParams=TRUE) {
$n=0;
$tpls = array();
$this->wikitext_tpls_allParams = array();
$this->wikitext = preg_replace_callback(
'~\{\{([a-z][\w\d_\-]+)(.+?)\}\}~uis', // templates wikitext
function ($m) use (&$n,&$tpls,$splitParams) {
$name = $m[1];
$content = $m[2];
if ($splitParams) {
$params=array('#name'=>$name, '#idx'=>$n); // idx reduntant
$np = 0;
$content = str_replace("\t",' ',$content); // remove tabs
foreach( explode('|',$content) as $p) {
$p = trim($p);
if ($p) {
if (preg_match('/^([a-z][_\w\-\d]+)\s*=\s*(.+)$/is',$p,$mm))
$params[$mm[1]]=$mm[2];
else {
$np++; //1,2,3,...
$params["#$np"]=$p; // #1, #2, ...
}
} // if p
} // for
// aqui $wikitext_tpls_allParams = array_merge($wikitext_tpls_allParams,array_keys($params));
$tpls[$n] = $params;
} else
$tpls[$n] = $content;
$ret = "#_tpl_#$name#$n##";
$n++;
return $ret;
},
$this->wikitext
);
$this->wikitext_tpls = $tpls;
} // func
function wikitextTpl_untokenize1Tpl($params,$tplName='norma',$sortParams=TRUE,$VPARAM_SEP=' | ') {
$sortParams_knames = array();
if ($sortParams!==NULL && is_array($sortParams)) {
$sortParams_knames = $sortParams;
$sortParams=2;
} else
$sortParams=$sortParams? 1: 0;
$start = '{{'.$tplName;
if (is_array($params)) { // normalized template
$knames = $sortParams_knames;
$vparams = array();
if ($sortParams) ksort($params);
foreach(array_keys($params) as $k) if (!in_array($k,$sortParams_knames)) {
if (substr($k,0,1)!='#')
$knames[]=$k;
elseif ( ctype_digit(substr($k,1)) ) // $k!='#name' && $k!='#idx'
$vparams[]=$params[$k];
}
if (count($vparams)) $start .= '|'.join($VPARAM_SEP,$vparams);
foreach($knames as $k) if (isset($params[$k])) // avoid extra sortParams_knames
$start.="\n|$k=".$params[$k];
return "$start\n}}";
} else
return "$start$params\n}}";
}
/**
* Undo tokens of wikitex-templates. Normalize parametric templates.
* @param $sortParams booleam to sort template-parameters, or array with initial params.
*/
function wikitextTpl_untokenize($sortParams=TRUE,$close=TRUE,$VPARAM_SEP=' | ') {
$tpls = &$this->wikitext_tpls;
$this->wikitext = preg_replace_callback(
'~#_tpl_#([a-z][\w\d_\-]+)#(\d+)##~is', // templates wikitext
function ($m) use (&$tpls,$sortParams,$VPARAM_SEP) {
$idx = $m[2];
if (isset($tpls[$idx]))
return MediawikiNavigor::wikitextTpl_untokenize1Tpl($tpls[$idx],$m[1],$sortParams,$VPARAM_SEP);
else
return '';
},
$this->wikitext
);
if ($close) $this->wikitext_tpls = NULL; // see
} // func
/**
* Normalize wikitext_tpls.
* @param $sortParams booleam to sort template-parameters.
*/
function wikitextTpl_normalize_tpls($splitParams=TRUE) {
if ($this->wikitext_tpls === NULL)
$this->wikitextTpl_tokenize($splitParams);
$confFuncs = array();
$cacheFuncs = array();
foreach($this->wikitext_normalizeConfig as $name=>$c)
if (substr($name,0,1)=='#' && is_callable($c)) $confFuncs[] = $c;
$normFunc = function($k,$v) use (&$confFuncs) {
foreach($confFuncs as $func)
$v=$func($k,$v);
return $v;
};
for($i=0; $i<count($this->wikitext_tpls); $i++) {
$tpl = &$this->wikitext_tpls[$i]; // alias
if (is_array($tpl)) {
foreach($tpl as $k=>$v)
$tpl[$k] = $normFunc($k,$v);
if ($this->wikitext_normalizeConfig['CACHE']!==NULL) {
$f = &$this->wikitext_normalizeConfig['CACHE'];
$f($i,$tpl); // add or replace kx_param
} // if cache
} else
$tpl = $normFunc($tpl);
} // for
return $i;
} // func
/**
* Normalize parametric templates.
* @param $sortParams booleam to sort template-parameters.
*/
function wikitextTpl_normalize($splitParams=TRUE,$sortParams=TRUE,$close=TRUE) {
if ($this->wikitext!==NULL) {
$this->wikitextTpl_normalize_tpls($splitParams,$sortParams);
$this->wikitextTpl_untokenize($sortParams,$close);
}
}
// // // // // // // //
// // BEGIN:CSV_METHODS
/**
* Get selected row (by preffix like "csv_" or all vals) or header.
* @param $row associative array.
* @param $prefix4 string "csv_" or "" for all.
* @param $getKeys mix,
* boolean TRUE for get, FALSE (or NULL) for no;
* array for a header that will ordenate row-columns.
*/
function expCSV_getRow($row, $prefix4='csv_', $getKeys=FALSE){
$theKeys = NULL;
if ($getKeys===NULL)
$getKeys=FALSE;
elseif (is_array($getKeys)) {
$theKeys = $getKeys;
$getKeys = FALSE;
}
$vals = array();
if ($theKeys!==NULL) {
foreach ($theKeys as $k) $vals[]=isset($row["$prefix4$k"])? $row["$prefix4$k"]: '';
return $vals;
} elseif ($prefix4) {
foreach ($row as $k=>$val) if (substr($k,0,4)==$prefix4)
$vals[]=$getKeys? substr($k,4): $val;
return $vals;
} else
return $row;
}
/**
* Outputs a CSV or TSV file from $wikitext_tpls of keys "csv_".
* @param $mode csv or tsv.
* @param $file output filename (default STDOUT).
* @param $prefix4 "csv_" or "" for all.
* @param $enforceHead mix (booleam to enforce column-order or array with coluns and enforcing)
*/
function wikitextTpl_expCSV($mode='csv', $showHead=TRUE, $file="php://output", $prefix4='csv_',$enforceHead=TRUE,$sortHead=FALSE) {
$SEP = ($mode=='csv')? ',': "\t";
$outputBuffer = fopen($file, 'w');
$hasHeader = FALSE;
if ($enforceHead!==NULL && is_array($enforceHead))
list($hasHeader,$header,$enforceHead) = array(TRUE,$enforceHead,TRUE);
if (isset($this->wikitext_tpls[0])) {
$header = $this->expCSV_getRow($this->wikitext_tpls[0],$prefix4,TRUE);
if ($header && $sortHead) sort($header);
if ($showHead) fputcsv($outputBuffer, $header, $SEP);
} else $header = NULL; // die()
if (!$enforceHead) $header=NULL;
foreach($this->wikitext_tpls as $row)
fputcsv($outputBuffer, $this->expCSV_getRow($row,$prefix4,$header), $SEP);
fclose($outputBuffer);
}
/**
* Merge and/or import a CSV file with $wikitext_tpls, by a primary key and include CSV columns.
*/
function wikitextTpl_mergimportCSVbyPK() {
}
// // END:CSV_METHODS
// // // // // // // //
// // // // // // // // //
// // BEGIN:UTIL_METHODS
/**
* Wrap method for Mediawiki's api.php and index.php, with one title at a time.
* @param $cmd string local convention about commands.
* @param $title string article's title.
* @param $format string to be returned (xml, html, json, php, wikitext).
* @return string with contents, or FALSE on failure.
*/
//REVISAR: gerenciar array e compor saídas, conferir com outras libs e usar $this->assoc_join($a,'&')
function getByTitle($cmd,$title='',$format='') {
$article = $this->pageInUse_check($title);
// falta api.php?format=xml&action=query&prop=extracts&titles=
//api.php?action=query&prop=revisions&format=json&titles=Main_page&rvprop=timestamp|user|comment|content
if ($cmd=='raw') $format='wikitext';
$ret = FALSE;
if (!$format || $format=='html') switch ($cmd) {
case 'full': $ret = $this->get("/index.php?$article");
break;
case 'render': $ret = $this->get("/index.php?action=render&$article");
break;
case 'pageCategs':
$ret = $this->get("/api.php?action=query&format=html&prop=categories&titles={$this->pageInUse}");
break;
default: die("\nERRO getByTitle($cmd com $format)");
} else switch ($cmd) {
case 'raw': // wikitext, see http://www.mediawiki.org/wiki/Manual:Parameters_to_index.php#Raw
$ret = $this->wikitext = $this->get("/index.php?action=raw&$article");
break;
// raw-expanded de api.php?action=expandtemplates ... ver http://www.mediawiki.org/wiki/API:Parsing_wikitext
case 'pageCategs':
$ret = $this->get("/api.php?action=query&prop=categories&format=$format&titles={$this->pageInUse}");
break;
default: die("\nERRO getByTitle($cmd com $format)");
}
if ($format=='php')
return unserialize($ret);
else
return $ret;
}
/**
* Extracts only the category names (ns=14) from requested data.
* @return array of names.
*/
function getPageCategsNames($title='') {
$all = $this->getByTitle('pageCategs',$title,'xml');
preg_match_all('/ns="14" title="[^:"]+:([^"]+)"/s', $all, $m);
return $m[1];
}
/**
* Wrap method for Mediawiki's "api.php?prop=info" with one title at a time.
* @see http://www.mediawiki.org/wiki/API:Properties#info_.2F_in
* @param $title string article's title.
* @param $prop string '' (to return all props) or the prop name (ex. 'touched').
* @return array, value or NULL on error.
*/
function info($title='',$prop='') {
$article = $this->pageInUse_check($title,'s');
$r = unserialize( $this->get("/api.php?format=php&action=query&prop=info&$article") );
if (isset($r['query']['pages'])) {
$page = array_pop( $r['query']['pages'] );
return $prop? $page[$prop]: $page;
} else
return NULL;
} // func
/**
AQUI remover Rapidom e usar lib mais simples para carregar HTML livre e devolver XML.
* Lists all the main-ns items of a category.
* @param $categName string category's name.
* @return array with all items.
*/
function category_listOfItems($categName, $classOfDiv='mw-content-ltr') {
$list = array();
$wikipage = $this->getByTitle('render',"Category:$categName");
//print "\n$wikipage";
$rdoc = new RapiDOM("<html>$wikipage</html>");
$xp = new DOMXpath($rdoc->dom);
// $nodes = $xp->query("//div[@class='$classOfDiv']//table//ul/li//a/@title[not(contains(.,':'))]");
$nodes = $xp->query("//div[@dir='ltr']//ul/li//a/@title[not(contains(.,':'))]");
foreach (iterator_to_array($nodes) as $i)
$list[] = $i->nodeValue;
return $list;
} // func
/**
* Edits an article.
* @param $newWikiText string text to be replaced.
* @param $title string text to be replaced.
* @return array with all items.
*/
function edit($newWikiText, $title='', $summary='#mn-edit') {
$article = $this->pageInUse_check($title);
$r = unserialize( $this->get("/api.php?action=query&format=php&meta=tokens") );
$token = $r['query']['tokens']['csrftoken'];
$data = array( 'summary'=>$summary, 'text'=>$newWikiText, 'token'=>$token );
$r = unserialize( $this->post($data,"/api.php?action=edit&format=php&$article") );
return isset($r['edit']['result'])? ($r['edit']['result']=='Success'): -1;
}
function pageInUse_check($title,$title_sufix='') {
$title=str_replace(' ','_',trim($title));
if ($title)
list($this->pageInUse, $this->pageInUse_idtype) = array($title,"title$title_sufix");
return "{$this->pageInUse_idtype}={$this->pageInUse}";
}
// // END:UTIL_METHODS
// // // // // // // // // // // // //
// // // // // // // // // // // // // //
// // BEGIN:ARRAY_TOOLS
/**
* Joins a set of key-value pairs by $pairSep, and all pairs of the set by $sep.
* NOTE: assoc_join($a,'&') is similar to http_build_query($a).
* @param $a mix NULL or array (handdled as reference) to be joined.
* @param $sep string (default '; ') separator in the final string.
* @param $pairSep string (default '=') pair separator (joins key-val pair).
* @return mix NULL if $a is NULL, string if $a is array.
*/
private function assoc_join(&$a,$sep='; ',$pairSep='=') {
return is_array($a)?
join($sep, array_map(
function($key) use ($a,$pairSep) {
$key = trim($key);
return "$key$pairSep{$a[$key]}";
},
array_keys($a)
)):
NULL;
}
/**
* Replaces or appends array. On key-conflicts, use the appended values.
* @param $a mix NULL or array (handdled as reference) to be changed.
* @param $append mix, string in the form "key=value", or associative array.
*/
private function assoc_merge(&$a,$append) {
if ( is_string($append) && count($append=explode('=',$append)) )
$append = array($append[0]=>$append[1]);
elseif (!is_array($append))
$append = array();
$a = ($a===NULL)? $append: array_merge($append,$a);
}
/**
* Rename keys of an associative array. On key-conflicts, use the flag to decide.
* @param $a mix NULL or array (handdled as reference) to be changed.
* @param $rename associative array with the pairs oldKey-newKey.
* @param $renameOverride boolean (default true) to decide override on conflicts with new keys.
*/
private function assoc_rename(&$a, $rename, $renameOverride=true) {
if (!is_array($a) || !is_array($rename))
return false;
foreach ($rename as $key=>$newKey)
if ( array_key_exists($key, $a) && ($renameOverride || !array_key_exists($newKey, $a)) ) {
$a[$newKey] = $a[$key];
unset($a[$key]);
}
return true;
} // func
/**
* Removes key-value pairs from array, by keys.
* @param $a mix NULL or array (handdled as reference) to be changed.
* @param $keys mix, string with the key, or array of keys.
*/
private function assoc_unset(&$a,$keys) {
if ( $a!==NULL ) {
if (!is_array($keys))
$keys=array($keys);
foreach ($keys as $key) if (array_key_exists($key,$a))
unset($a[$key]);
}
}
// // END:ARRAY_TOOLS
// // // // // // // // // // // // //
} // class
// FALTA TRATAMENTO DE OPTIONS (GET OR TERMINAL)
?>