-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCourseEditorUtils.php
803 lines (754 loc) · 28.2 KB
/
CourseEditorUtils.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
<?php
if ( !defined( 'MEDIAWIKI' ) ){
die( );
}
class CourseEditorUtils {
private static $requestContext = null;
public static function getTopics(){
try {
$api = new ApiMain(
new DerivativeRequest(
self::getRequestContext()->getRequest(),
array(
'action' => 'query',
'list' => 'embeddedin',
'eititle' => 'Template:Topic',
'eilimit' => 500
)
),
true
);
$api->execute();
$results = $api->getResult()->getResultData(null, array('Strip' => 'all'));
$pages = $results['query']['embeddedin'];
$topics = array();
foreach ($pages as $page) {
array_push($topics, $page['title']);
}
sort($topics);
return $topics;
} catch(UsageException $e){
return $e->getMessage();
}
}
public static function addElement(&$operationObj, $text = ""){
$elementName = $operationObj->elementName;
$apiResult = CourseEditorUtils::editWrapper($elementName, $text, null, null);
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
public static function moveElement(&$operationObj){
$levelTwoName = $operationObj->elementName;
$newLevelTwoName = $operationObj->newElementName;
$apiResult = CourseEditorUtils::moveWrapper($levelTwoName, $newLevelTwoName, true, false);
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
public static function deleteElement(&$operationObj){
global $wgCourseEditorTemplates, $wgCourseEditorCategories, $wgContLang;
$context = CourseEditorUtils::getRequestContext();
$user = $context->getUser();
$elementToRemove = $operationObj->elementName;
$title = Title::newFromText($elementToRemove, $defaultNamespace=NS_MAIN);
if(!$title->userCan('delete', $user, 'secure')){
$prependText = "\r\n{{". $wgCourseEditorTemplates['DeleteMe'] ."}}";
$apiResult = CourseEditorUtils::editWrapper($elementToRemove, null, $prependText, null);
}else {
$apiResult = CourseEditorUtils::deleteWrapper($elementToRemove);
}
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
/**
* Update a levelTwoName page.
* Case 1: the method was triggered by a levelTwo rename, so either elementName
* and newElementName params are set.
* Case 2: the the method was triggered by a levelTwo change, for example
* a levelThree was added. In this case newElementName is not set.
* @param Object $operationObj it could cointain elementName, newElementName and
* elementsList
*/
public static function updateLevelTwo(&$operationObj){
global $wgCourseEditorCategories, $wgContLang;
$levelTwoName = $operationObj->elementName;
$newLevelTwoName = (isset($operationObj->newElementName)) ? $operationObj->newElementName : $levelTwoName;
$levelsThree = (isset($operationObj->elementsList)) ? json_decode($operationObj->elementsList) : CourseEditorUtils::getLevelsThree($newLevelTwoName);
$newLevelTwoText = "";
foreach ($levelsThree as $levelThree) {
$newLevelTwoText .= "* [[" . $newLevelTwoName . "/" . $levelThree ."|". $levelThree ."]]\r\n";
}
$newLevelTwoText .= "\r\n<noinclude>[["
. $wgContLang->getNsText( NS_CATEGORY ) . ":". $wgCourseEditorCategories['CourseLevelTwo'] ."]]</noinclude>";
$apiResult = CourseEditorUtils::editWrapper($newLevelTwoName, $newLevelTwoText, null, null);
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
public static function updateRoot(&$operationObj){
global $wgCourseEditorTemplates, $wgCourseEditorCategories, $wgContLang;
$courseName = $operationObj->elementName;
$newCourseText = "{{". $wgCourseEditorTemplates['CourseRoot'] ."|\r\n";
$newLevelsTwoArray = json_decode($operationObj->elementsList);
foreach ($newLevelsTwoArray as $levelTwo) {
$newCourseText .= "{{". $wgCourseEditorTemplates['CourseLevelTwo'] ."|" . $levelTwo ."}}\r\n";
}
$newCourseText .= "}}";
$newCourseText .= "\r\n<noinclude>[[" . $wgContLang->getNsText( NS_CATEGORY ) . ":"
. $wgCourseEditorCategories['CourseRoot']. "]]</noinclude>";
$apiResult = CourseEditorUtils::editWrapper($courseName, $newCourseText, null, null);
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
public static function purgeCache(&$operationObj){
$pageToBePurged = $operationObj->elementName;
$apiResult = CourseEditorUtils::purgeWrapper($pageToBePurged);
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
/**
* Create/update the collection page of a public course
* @param Object $operationObj
*/
public static function updateCollection(&$operationObj) {
$courseName = $operationObj->elementName;
list($namespace, $name) = explode(':', $courseName, 2);
$title = Title::newFromText($courseName, $defaultNamespace=NS_COURSE );
$namespaceIndex = $title->getNamespace();
if(MWNamespace::equals($namespaceIndex, NS_USER)){
self::updateUserCollection($operationObj);
}else {
$pageTitle = "Project:" . wfMessage('courseeditor-collection-book-category') ."/" . $name;
$collectionText = "{{" . wfMessage('courseeditor-collection-savedbook-template') . "
\n| setting-papersize = a4
\n| setting-toc = auto
\n| setting-columns = 1
\n| setting-footer = yes\n}}\n";
$collectionText .= "== " . str_replace('_', ' ', $name) . " ==\r\n";
$levelsTwo = self::getLevelsTwo($courseName);
foreach ($levelsTwo as $levelTwo) {
$levelsThree = self::getLevelsThree($courseName . '/' .$levelTwo);
$collectionText .= ";" . $levelTwo . "\r\n";
foreach ($levelsThree as $levelThree) {
$collectionText .= ":[[" . $courseName . "/" . $levelTwo . "/" . $levelThree . "]]\r\n";
}
}
$categoryName = wfMessage('courseeditor-collection-book-category');
if ( !$categoryName->isDisabled() ) {
$catTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
if ( !is_null( $catTitle ) ) {
$collectionText .= "\n[[" . $catTitle->getPrefixedText() ."|" . $name . "]]";
}
}
$apiResult = self::editWrapper($pageTitle, $collectionText, null, null);
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
}
/**
* Create/update the collection page of a private course
* @param $operationObj
*/
private static function updateUserCollection(&$operationObj){
$courseName = $operationObj->elementName;
list($namespaceAndUser, $title) = explode('/', $courseName, 2);
$pageTitle = $namespaceAndUser . "/" . wfMessage('courseeditor-collection-book-category') . "/" . $title;
$collectionText = "{{" . wfMessage('courseeditor-collection-savedbook-template') . "
\n| setting-papersize = a4
\n| setting-toc = auto
\n| setting-columns = 1
\n| setting-footer = yes\n}}\n";
$collectionText .= "== " . str_replace('_', ' ', $title). " ==\r\n";
$levelsTwo = self::getLevelsTwo($courseName);
foreach ($levelsTwo as $levelTwo) {
$levelsThree = self::getLevelsThree($courseName . '/' .$levelTwo);
$collectionText .= ";" . $levelTwo . "\r\n";
foreach ($levelsThree as $levelThree) {
$collectionText .= ":[[" . $courseName . "/" . $levelTwo . "/" . $levelThree . "]]\r\n";
}
}
$categoryName = wfMessage('courseeditor-collection-book-category');
if ( !$categoryName->isDisabled() ) {
$catTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
if ( !is_null( $catTitle ) ) {
$collectionText .= "\n[[" . $catTitle->getPrefixedText() ."|" . $title. "]]";
}
}
$apiResult = self::editWrapper($pageTitle, $collectionText, null, null);
CourseEditorUtils::setSingleOperationSuccess($operationObj, $apiResult);
}
/**
* Get the metadata of a course
* @param String $courseName the name of a course
* @return Array $metadataResult the associative array with the metadata keys
* and values
*/
public static function getMetadata($courseName){
$title = Title::newFromText($courseName, $defaultNamespace=NS_COURSEMETADATA );
$page = WikiPage::factory( $title );
$content = $page->getContent( Revision::RAW );
$text = ContentHandler::getContentText( $content );
if($text === ''){
return null;
}
/*
This regex is used on strings formed like this:
'<section begin=metadataKey>metadataValue<section end=metadataKey>'
*/
$regex = "/<section begin=(.*?)\s*\/>(.*?)<section end=.*?\/>/s";
preg_match_all($regex, $text, $matches, PREG_PATTERN_ORDER);
$metadataResult = array();
$metadataKeys = $matches[1];
$metadataValues = $matches[2];
for ($i=0; $i < sizeof($metadataKeys); $i++) {
$metadataResult[$metadataKeys[$i]] = $metadataValues[$i];
}
return $metadataResult;
}
/**
* Get the courses in a topic page
* @param String $topic the name of a topic page
* @return Array $matches the courses within a topic page
*/
public static function getTopicCourses($topic){
global $wgCourseEditorTemplates;
$title = Title::newFromText($topic, $defaultNamespace=NS_MAIN );
$page = WikiPage::factory( $title );
$content = $page->getContent( Revision::RAW );
$text = ContentHandler::getContentText( $content );
$textNoNewLines = trim(preg_replace('/\n+/', '', $text));
/*
This regex is used on strings formed like this (space are trimmed):
'{{Topic|
{{CourseTemplateName|Course}}
{{CourseTemplateName|Course}}
}}'
*/
$regex = "/({{" . $wgCourseEditorTemplates['Topic'] . "|.+)}}.*$/";
preg_match_all($regex, $textNoNewLines, $matches, PREG_PATTERN_ORDER);
return $matches[1][0];
}
/**
* This method is a workaround (read it HACK) to check the API results.
* MediaWiki ApiResult object is not "standard" but if an error/exception
* occurs the result variable is a string.
*/
public static function setSingleOperationSuccess(&$operation, $result){
$isSuccess = true;
if (is_string($result)) {
$isSuccess = false;
$operation->error = $result;
}
$operation->success = $isSuccess;
}
/**
* This method is a workaround (read it HACK) to check the API results.
* MediaWiki ApiResult object is not "standard" but if an error/exception
* occurs the result variable is a string.
*/
public static function setComposedOperationSuccess(&$operation, $resultsArray){
$isSuccess = true;
foreach ($resultsArray as $result) {
if (is_string($result)) {
$isSuccess = false;
$operation->error = $result;
break;
}
}
$operation->success = $isSuccess;
}
/**
* Utility function that implement the Singleton pattern
* to get the instance of the requestContext object
*/
public static function getRequestContext(){
if(self::$requestContext == null)
{
$context = new RequestContext();
self::$requestContext = $context;
}
return self::$requestContext;
}
/**
* Utility wrapper to get the category of a page
* @param Title $courseName the name of a course
* @return Array the array with the category titles
*/
public static function getCategories($courseName){
try {
$api = new ApiMain(
new DerivativeRequest(
self::getRequestContext()->getRequest(),
array(
'action' => 'query',
'titles' => $courseName,
'prop' => 'categories'
)
),
true
);
$api->execute();
$results = $api->getResult()->getResultData(null, array('Strip' => 'all'));
$page = reset($results['query']['pages']);
return $page['categories'];
} catch(UsageException $e){
return $e->getMessage();
}
}
/**
* Utility to get the levelsThree
* @param Title $courseName the name of a course
* @return Array $matches the levelThree pages
*/
public static function getLevelsThree($levelTwoName){
$title = Title::newFromText($levelTwoName, $defaultNamespace=NS_MAIN );
$page = WikiPage::factory( $title );
$content = $page->getContent( Revision::RAW );
$text = ContentHandler::getContentText( $content );
/*
This regex is used on string formed like this:
'*[[LinkToLevelThree|LevelThreeName]]'
*/
$regex = "/\*\s*\[{2}([^|]*)\|?([^\]]*)\]{2}\s*/";
preg_match_all($regex, $text, $matches, PREG_PATTERN_ORDER);
return $matches[2];
}
/**
* Utility to get the levelsTwo
* @param Title $courseName the name of a course
* @return Array $matches the levelTwo pages
*/
public static function getLevelsTwo($courseName){
global $wgCourseEditorTemplates;
$title = Title::newFromText( $courseName, $defaultNamespace=NS_MAIN );
$page = WikiPage::factory( $title );
$content = $page->getContent( Revision::RAW );
$text = ContentHandler::getContentText( $content );
/*
This regex is used on string formed like this:
'{{LevelTwoTemplateName|LevelTwoName}}'
*/
$regex = "/\{{2}". $wgCourseEditorTemplates['CourseLevelTwo'] ."\|(.*)\}{2}/";
preg_match_all($regex, $text, $matches, PREG_PATTERN_ORDER);
return $matches[1];
}
/**
* Utility to get the levelsThree in JSON
* @param Title $courseName the name of a course
* @return Array with the levelsTwo
*/
public static function getLevelsThreeJson($courseName){
return json_encode(self::getLevelsThree($courseName));
}
/**
* Utility to get the levelsTwo in JSON
* @param Title $courseName the name of a course
* @return Array with the levelsTwo
*/
public static function getLevelsTwoJson($courseName){
return json_encode(self::getLevelsTwo($courseName));
}
public static function getCourseTree($courseName){
$tree = array(
'root' => $courseName,
'levelsTwo' => array(),
'levelsThree' => array()
);
$levelsTwo = self::getLevelsTwo($courseName);
//array_walk($levelsTwo, array('self', 'buildFullPageName'), $courseName);
$tree['levelsTwo'] = $levelsTwo;
foreach ($levelsTwo as $level) {
$levelsThree = self::getLevelsThree($courseName . '/' . $level);
//array_walk($levelsThree, array('self', 'buildFullPageName'), $level);
array_push($tree['levelsThree'], $levelsThree);
}
return json_encode($tree);
}
/*public static function getCourseTree($courseName){
$tree = array(
'root' => $courseName,
'levelsTwo' => array(),
'levelsThree' => array()
);
$levelsTwo = self::getLevelsTwo($courseName);
array_walk($levelsTwo, array('self', 'buildFullPageName'), $courseName);
$tree['levelsTwo'] = $levelsTwo;
foreach ($tree['levelsTwo'] as $level) {
$levelsThree = self::getLevelsThree($level);
array_walk($levelsThree, array('self', 'buildFullPageName'), $level);
array_push($tree['levelsThree'], $levelsThree);
}
return json_encode($tree);
}
private function buildFullPageName(&$item, $key, $toBePrepended){
$item = $toBePrepended . '/' . $item;
}*/
/**
* Get the previous and the next pages of a given page
* @param Title $pageTitle the name of page
* @return Array with the error element or the next and previous pages
*/
public static function getPreviousAndNext($pageTitle){
$subElements = self::getSubCourseElements($pageTitle);
if(isset($subElements['error'])){
return $subElements;
}else {
return self::buildPreviousAndNext($pageTitle, $subElements);
}
}
/**
* Utility function to get the array with the levelTwo or levelThree pages
* @param Title $pageTitle the name of page
* @return Array $subElements the levelTwo or levelThree pages
*/
private static function getSubCourseElements($pageTitle) {
$namespace = $pageTitle->getNamespace();
//Count subpage levels to define what type of subElements should be gotten
$levels = substr_count($pageTitle->getText(), "/");
$basePage = MWNamespace::getCanonicalName($namespace) . ":" . $pageTitle->getBaseText();
if($namespace === NS_COURSE){
if($levels === 1){
$subElements = self::getLevelsTwo($basePage);
}elseif ($levels === 2) {
$subElements = self::getLevelsThree($basePage);
}else {
return array('error' => "Page levels not valid." );
}
}elseif ($namespace === NS_USER) {
if($levels === 2){
$subElements = self::getLevelsTwo($basePage);
}elseif ($levels === 3) {
$subElements = self::getLevelsThree($basePage);
}else {
return array('error' => "Page levels not valid." );
}
}else {
return array('error' => "Namespace not valid." );
}
return $subElements;
}
/**
* Utility function to build the array with the next and the previous
* of a given levelTwo or levelThree
* @param Title $pageTitle the name of page
* @param Array $subElements the levelTwo or levelThree elements
* @return Array $previousAndNext the associative array with the next and the
* previous page
*/
private static function buildPreviousAndNext($pageTitle, $subElements){
$namespace = $pageTitle->getNamespace();
$basePage = MWNamespace::getCanonicalName($namespace) . ":" . $pageTitle->getBaseText();
$lastPage = $pageTitle->getSubpageText();
$previous = null;
$next = null;
$previousAndNext = array('previous' => $previous, 'next' => $next);
//If there are less than 2 subElements it means there is no next/previous
if(sizeof($subElements) < 2){
return $previousAndNext;
}else {
//$key = array_search($lastPage, $subElements);
for ($i=0; $i < sizeof($subElements); $i++) {
$safeTitle = Title::makeTitleSafe($namespace, $subElements[$i]);
if (is_null($safeTitle)) {
$result = strcmp($lastPage, rawurldecode($subElements[$i]));
} else {
$result = strcmp($lastPage, $safeTitle->getText());
}
if($result === 0){
$key = $i;
break;
}
}
if($key === sizeof($subElements) - 1){
$previousAndNext['previous'] = $basePage . "/" . $subElements[$key - 1];
}else if($key === 0){
$previousAndNext['next'] = $basePage . "/" . $subElements[$key + 1];
}else{
$previousAndNext['previous'] = $basePage . "/" . $subElements[$key - 1];
$previousAndNext['next'] = $basePage . "/" . $subElements[$key + 1];
}
return $previousAndNext;
}
}
/**
* Utility delete wrapper to delete a page
* @param String $title the name of page
* @return Array the result of the API call
*/
public static function deleteWrapper($title){
$context = self::getRequestContext();
try {
$user = $context->getUser();
$token = $user->getEditToken();
$api = new ApiMain(
new DerivativeRequest(
$context->getRequest(),
array(
'action' => 'delete',
'title' => $title,
'token' => $token
),
true
),
true
);
$api->execute();
return $api->getResult()->getResultData(null, array('Strip' => 'all'));
} catch(UsageException $e){
return $e->getMessage();
}
}
/**
* Utility purge wrapper to purge the cache of a page/s
* @param String $titles the title of the page/s
* @return Array the result of the API call
*/
public static function purgeWrapper($titles){
$context = self::getRequestContext();
try {
$api = new ApiMain(
new DerivativeRequest(
$context->getRequest(),
array(
'action' => 'purge',
'titles' => $titles,
'forcerecursivelinkupdate' => true
),
true
),
true
);
$api->execute();
return $api->getResult()->getResultData(null, array('Strip' => 'all'));
} catch(UsageException $e){
return $e->getMessage();
}
}
/**
* Utility edit API wrapper to edit or create a page
* @param String $title the name of page
* @param String $text the text of the section
* @param String $textToPrepend the text to prepend to the section
* @param String $textToAppend the text to append to the section
* @return Array the result of the API call
*/
public static function editWrapper($title, $text, $textToPrepend, $textToAppend){
$context = self::getRequestContext();
try {
$user = $context->getUser();
$token = $user->getEditToken();
//$token = $this->getCsrfToken();
$api = new ApiMain(
new DerivativeRequest(
$context->getRequest(),
array(
'action' => 'edit',
'title' => $title,
'text' => $text,
// automatically override text
'prependtext' => $textToPrepend,
// automatically override text
'appendtext' => $textToAppend,
'notminor' => true,
'token' => $token
),
true
),
true
);
$api->execute();
return $api->getResult()->getResultData(null, array('Strip' => 'all'));
} catch(UsageException $e){
return $e->getMessage();
}
}
/**
* Utility edit section wrapper to edit or create a specific section in a page
* @param String $title the name of page
* @param String $text the text of the section
* @param String $textToPrepend the text to prepend to the section
* @param String $textToAppend the text to append to the section
* @return Array the result of the API call
*/
public static function editSectionWrapper($title, $text, $textToPrepend, $textToAppend){
$context = self::getRequestContext();
try {
$user = $context->getUser();
$token = $user->getEditToken();
$levelTwoExist = self::checkNewTopicsSectionExist($title);
//Create the section if not exists, otherwise append to it
if(!$levelTwoExist){
$api = new ApiMain(
new DerivativeRequest(
$context->getRequest(),
array(
'action' => 'edit',
'title' => $title,
'text' => $text,
'section' => 'new',
'sectiontitle' => wfMessage('courseeditor-newtopics-section-title'),
// automatically override text
'prependtext' => $textToPrepend,
// automatically override text
'appendtext' => $textToAppend,
'notminor' => true,
'token' => $token
),
true
),
true
);
}else {
$api = new ApiMain(
new DerivativeRequest(
$context->getRequest(),
array(
'action' => 'edit',
'title' => $title,
'text' => $text,
'sectiontitle' => wfMessage('courseeditor-newtopics-section-title'),
// automatically override text
'prependtext' => $textToPrepend,
// automatically override text
'appendtext' => $textToAppend,
'notminor' => true,
'token' => $token
),
true
),
true
);
}
$api->execute();
return $api->getResult()->getResultData(null, array('Strip' => 'all'));
} catch(UsageException $e){
return $e->getMessage();
}
}
/**
* Utility wrapper of the move API.
* @param String $from the name of page to be moved
* @param String $to the new name of the page
* @param boolean $withSubpages (optional) move the subpages also
* @param boolean $noRedirect (optional) suppress the redirects
* @return Array the result of the API call
*/
public static function moveWrapper($from, $to, $withSubpages=true, $noRedirect=false){
$context = self::getRequestContext();
$params = array(
'action' => 'move',
'from' => $from,
'to' => $to,
'movetalk' => true
);
if($withSubpages){
$params['movesubpages'] = true;
}
if ($noRedirect) {
$params['noredirect'] = true;
}
try {
$user = $context->getUser();
$token = $user->getEditToken();
$params['token'] = $token;
$api = new ApiMain(
new DerivativeRequest(
$context->getRequest(),
$params,
true
),
true
);
$api->execute();
return $api->getResult()->getResultData(null, array('Strip' => 'all'));
} catch(UsageException $e){
return $e->getMessage();
}
}
/**
* Get the private courses ready to be published using the categorymembers
* API.
* @return Array $readyCourses the private courses ready to be published
*/
public static function getReadyToBePublishedCourses(){
global $wgCourseEditorCategories;
$context = self::getRequestContext();
try {
$user = $context->getUser();
$token = $user->getEditToken();
$api = new ApiMain(
new DerivativeRequest(
$context->getRequest(),
array(
'action' => 'query',
'list' => 'categorymembers',
'cmtitle' => 'Category:' . $wgCourseEditorCategories['ReadyToBePublished']
)
)
);
$api->execute();
$apiResult = $api->getResult()->getResultData(null, array('Strip' => 'all'));
$readyCoursesDirtyArray = $apiResult['query']['categorymembers'];
$readyCourses = [];
//Clean the result array and get only the titles
foreach ($readyCoursesDirtyArray as $course) {
array_push($readyCourses, $course['title']);
}
return $readyCourses;
} catch(UsageException $e){
return $e->getMessage();
}
}
/**
* Check if the section where new topics are added is in the department page.
* @param String $department the name of the department page
* @return boolean $ret true if the there is the section
*/
private function checkNewTopicsSectionExist($department) {
$title = Title::newFromText( $department);
$page = WikiPage::factory( $title);
$context = self::getRequestContext();
$parserOptions = ParserOptions::newFromContext($context);
$levelsTwo = $page->getParserOutput($parserOptions)->getSections();
$newCoursesSection = wfMessage('courseeditor-newtopics-section-title')->text();
if(!is_array($levelsTwo)){
return false;
}else {
foreach($levelsTwo as $element) {
$ret = in_array($newCoursesSection, $element);
}
}
return $ret;
}
/**
* Generate the url to edit the root level of a course
* @param Title $title the title of the course page
* @return Array $result an array with the 'href' to CourseEditor SpecialPage and
* the localised title for the actiontype
*/
public static function makeEditCourseUrl($title){
$titleText = $title->getNsText() . ":" . $title->getText();
$url = "/Special:CourseEditor?actiontype=editcourse&pagename=" . $titleText;
$result = array('href' => $url, 'text' => wfMessage('courseeditor-editcourse-pagetitle')->text());
return $result;
}
/**
* Generate the url to edit the second level of a course
* @param Title $title the title of the course page
* @return Array $result an array with the 'href' to CourseEditor SpecialPage and
* the localised title for the actiontype
*/
public static function makeEditLevelTwoUrl($title){
$titleText = $title->getNsText() . ":" . $title->getText();
$url = "/Special:CourseEditor?actiontype=editleveltwo&pagename=" . $titleText;
$result = array('href' => $url, 'text' => wfMessage('courseeditor-editlevelTwo-pagetitle')->text());
return $result;
}
/**
* Generate the url to download a whole course through Collection extension
* @param Title $title the title of the course page
* @return string $url the url to Collection SpecialPage
*/
public static function makeDownloadCourseUrl($title){
if($title->getNamespace() === NS_USER){
$user = $title->getRootText();
$collection = $title->getNstext() . ":" . $user . "/" . wfMessage('courseeditor-collection-book-category')->text() . "/" . $title->getSubpageText();
}else {
$collection = "Project:" . wfMessage('courseeditor-collection-book-category')->text() . "/" . $title->getRootText();
}
//Return only the url instead of an array with 'href' and 'title'.
//The title is created within the skin using the titles of the Collection tools
return $url = "/Special:Collection?bookcmd=render_collection&writer=rdf2latex&colltitle=" . $collection;
}
}