-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModuleReleaseNotes.module
964 lines (809 loc) · 41.1 KB
/
ModuleReleaseNotes.module
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
<?php namespace ProcessWire;
/**
* ProcessWire
* Copyright (C) 2014-present by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://processwire.com
*
* TODO
* ----
* - Add paging to API result fetches
* - Add public data-access API for other modules to use
*
* Known Issues
* ------------
*
* Need to decide on my own changelog format. Will probably end up being a simplified version of Keep a Changelog.
*/
require_once 'FileCache.php';
class ModuleReleaseNotes extends Process implements ConfigurableModule {
protected $github_read_info = null;
protected $repo_client = null;
protected $taglist = null;
public static function getModuleInfo() {
return [
'title' => __('Module Release Notes'),
'summary' => __("Discovers and shows what has changed with each module version."),
'version' => '0.11.4',
'author' => 'Netcarver',
'autoload' => 'template=admin, process=ProcessModule',
'singular' => true,
'permanent' => false,
'requires' => 'ProcessWire>=3.0.0, PHP>=5.4.0',
'installs' => 'TextformatterParsedownExtraPlugin',
'icon' => 'code-fork',
];
}
/**
*
*/
static public function getDefaultConfig() {
return [
'fallbackCommitHistory' => 12,
'openSettings' => 0,
'wordWrapColumn' => 90,
'breakingPhrases' => 'BreakingChange, Breaking Change, Breaking-Change',
'usePrismIfAvailable' => 0,
'cacheDirectory' => 'module-release-notes',
];
}
/**
* Lists mappings of file extensions to markup language and preferred textformatter to be used.
*
* Anything not matching the list here (or if the formatter fails to be loaded) will be escaped and output
* 'verbatim'.
*/
static $formatters = [
'md' => ['type' => 'Markdown', 'use' => 'TextformatterParsedownExtraPlugin'],
];
/**
* Make config data available within the instance variable.
*/
public function __construct() {
foreach(self::getDefaultConfig() as $key => $value) {
$this->$key = $value;
}
}
protected function getReadDepletionMessage($service_info) {
$time = date('Y-m-d H:i:s', $service_info['reset']);
$message = sprintf(__('Out of reads at %s. A maximum of %s reads per hour is allowed.<br>Try again after %s.'), $service_info['name'], $service_info['limit'], $time);
return "<div class='warning'>$message</span>";
}
/**
* Prepares commit meta-data for display
*/
protected function formatCommitMetaData($commit, $icon = null) {
$author = $commit['author'];
$date = $commit['date'];
$sha = substr($commit['sha'], 0, 8);
$tag = $commit['tag'];
$url = $commit['url'];
if (null === $icon) {
$icon = "<i class='fa fa-icon fa-git'></i>";
}
// Format a tag marker...
if ($tag) {
$tag = "— <span class='has-git-tag'><i class='fa fa-icon fa-tag' aria-hidden=true></i> $tag</span>";
} else {
$tag = '';
}
$date = str_replace('T', ' ', $date);
$sig = "$icon — $date — <a href='$url' target='_diff'>$sha <i class='fa fa-icon fa-external-link'></i></a> — $author $tag";
return $sig;
}
/**
* Sanitise a string for further processing and display.
*/
public function sanitizeString($string) {
$san = wire('sanitizer');
$string = $san->purify($string);
return $string;
}
static protected function cacheLocation($cache_name) {
$cache_dir = realpath(wire('config')->paths->cache);
$cache_dir = "{$cache_dir}/$cache_name";
if (!is_dir($cache_dir) && !mkdir($cache_dir)) {
throw new \Exception(sprintf(__("Could not create cache directory at %s, is the assets directory writable?"), $cache_dir));
}
return $cache_dir;
}
protected function getClientForRepo($remote) {
$m = [];
preg_match('~https?://(.+?)/~i', $remote, $m);
$client = $m[1];
$http = new WireHttp();
$http->setTimeout(2);
$application = 'PW-Module-Release-Notes';
$cache_dir = self::cacheLocation($this->cacheDirectory);
if (false !== stripos($remote, '://github.com')) {
require_once 'GithubRepositoryAdaptor.php';
$client = new \Netcarver\GithubRepositoryAdaptor($http, $remote, $application, ['cache_dir' => $cache_dir]);
} else if (false !== stripos($remote, '://bitbucket.org')) {
require_once 'BitbucketRepositoryAdaptor.php';
$client = new \Netcarver\BitbucketRepositoryAdaptor($http, $remote, $application, ['cache_dir' => $cache_dir]);
} else if (false !== stripos($remote, '://gitlab.com')) {
// TODO develop gitlab client
}
return $client;
}
protected function formatCommitList($commits, $icon) {
$list = '';
if (count($commits['commits'])) {
foreach ($commits['commits'] as $commit) {
$message = $this->sanitizeString($commit['message']);
$message = $this->utf8_wordwrap($message);
$sig = $this->formatCommitMetaData($commit, $icon);
$entry = "<li class='commit'><span class='sig'>$sig</span><br><pre>$message</pre></li>";
$list .= $entry;
}
}
$url = @$commits['url']; // Optional URL to repo host where this list can be viewed.
if ($url) {
$url = "<p><a href='$url' target='_diff'>$icon " . __('View in repository.') . "</a></p>";
}
return "<ul class='commits'>$list</ul>$url";
}
/**
* Add hooks to display release information to modules prior to upgrade and add the readme and changelog to module
* information pages.
*/
public function ready() {
if (!$this->user->isLoggedin() || !$this->user->hasPermission('module-admin')) return;
/**
* Add Release notes and/or a list of commits between tags and/or the latest changelog and/or the latest
* commit messages to the download confirmation form.
*/
$this->addHookAfter("ProcessModule::buildDownloadConfirmForm", function($event) {
$info = $event->arguments[0];
$module_class = $info['class_name'];
$current_info = $this->modules->getModuleInfoVerbose($module_class);
$current_version = $current_info['versionStr']; // This is a string.
$new_version = $info['module_version']; // This is a string.
$remote = $info['project_url'];
$remote_icon = '<i class="fa fa-icon fa-external-link"></i>';
$info['version_current'] = $current_version; // Push the current version into the $info
$info['module_version_current'] = $current_version;
$info['remote_icon'] = $remote_icon;
ksort($info);
$changes = $current_version != $new_version;
$version_order = version_compare($current_version, $new_version);
if ($version_order == 0) {
return; // No change!
}
$return_info = $event->return;
$children = $return_info->children;
$wrapper = $this->modules->get('InputfieldFieldset');
$wrapper->name = 'changes-wrapper';
$wrapper->label = __("What's Changed?");
//
// Handle case where a more recent version is installed locally.
//
if ($version_order > 0) {
$field = $this->modules->get('InputfieldMarkup');
$field->name = 'release-notes release-notes-warning';
$field->label = __("Version Downgrade Warning");
$field->value = "<div class=warning>" . sprintf(__("The version currently installed may be more developed than the one you are about to install. If you continue, you may lose some functionality or experience problems."), $current_version, $new_version) . "</div>";
$wrapper->add($field);
$return_info->children->insertAfter($wrapper, $children[0]);
return;
}
$client = $this->getClientForRepo($remote);
if (is_string($client)) {
$field = $this->modules->get('InputfieldMarkup');
$field->name = 'release-notes release-notes-warning';
$field->label = __("Unsupported Remote Repository Host");
$field->value = "<div class=warning>" . sprintf(__("Sorry, ModuleReleaseNotes doesn't know how to connect to the git hosting service at %s. Please let Netcarver know about this by posting <a href='https://processwire.com/talk/topic/17767-module-release-notes/'>on the PW forum.</a>"), $client) . "</div>";
$wrapper->add($field);
$return_info->children->insertAfter($wrapper, $children[0]);
return;
}
$client_info = $client->GetInfo();
$repo_icon = $client_info['icon'];
$repo_supports_releases = in_array('release-notes', $client_info['capabilities']);
$repo_supports_tag_to_tag = in_array('tag-to-tag-commits', $client_info['capabilities']);
$repo_supports_changelog = in_array('changelog-access', $client_info['capabilities']);
$repo_supports_commit_list = in_array('commits', $client_info['capabilities']);
if (!$repo_supports_releases && !$repo_supports_tag_to_tag && !$repo_supports_changelog && !$repo_supports_commit_list) {
$field = $this->modules->get('InputfieldMarkup');
$field->name = 'release-notes release-notes-warning';
$field->label = __("Impotent Repository Adaptor");
$needed = 'release-notes, tag-to-tag-commits, changelog-access, commits';
$field->value = "<div class=warning>" . sprintf(__("Sorry, but the %s client adaptor for ModuleReleaseNotes doesn't have any of the needed query capabilities [%s]"), $client_info['name'], $needed) . "</div>";
$wrapper->add($field);
$return_info->children->insertAfter($wrapper, $children[0]);
return;
}
$release_notes = $release_notes_default = __('Not Available - Release Notes Not Found');
$tagged_log = $tagged_log_default = __('Not Available - One or More Git Tags Missing');
$changelog_file = $changelog_file_default = __('Not Available - File Missing');
$latest_commits = $latest_commits_default = __('Comming Soon!');
//
// Fetch release notes...
//
if ($repo_supports_releases) {
$release_link = $client->GetReleaseNoteViewUrl($new_version);
$tmp_release_notes = $client->GetReleaseNotes($new_version);
$client_info = $client->GetInfo();
if (!empty($tmp_release_notes)) {
$release_notes_newtype = 'txt';
$release_notes = $this->formatTextOfType('release-notes', 'md', $tmp_release_notes, $fmt_note, $release_notes_newtype);
} elseif (0 == $client_info['remaining']) {
$release_notes = $this->getReadDepletionMessage($client_info);
}
}
$has_release_notes = $release_notes != $release_notes_default;
//
// Fetch a tag-to-tag commit list...
//
if ($repo_supports_tag_to_tag) {
$tmp_commits = $client->GetCommits($current_version, $new_version);
$client_info = $client->GetInfo();
if (null !== $tmp_commits) {
$tagged_log = $this->formatCommitList($tmp_commits, $repo_icon);
} elseif (0 == $client_info['remaining']) {
$tagged_log = $this->getReadDepletionMessage($client_info);
}
}
$has_tagged_log = $tagged_log != $tagged_log_default;
//
// Fetch changelog file (if any)...
//
if ($repo_supports_changelog) {
$tmp_changelog_file = $client->GetChangelog();
if (null !== $tmp_changelog_file) {
$changelog_file = $tmp_changelog_file;
}
}
$has_changelog_file = $changelog_file != $changelog_file_default;
//
// Github release notes section
//
if ($repo_supports_releases) {
$field = $this->modules->get('InputfieldMarkup');
$field->name = 'release-notes';
if ($has_release_notes) {
$field->label = sprintf(__("Release Notes for version %s."), $new_version);
$release_notes = "<div class='release-notes'>$release_notes<p><a href='$release_link' target='_diff'>$repo_icon View</a><p></div>";
if ($this->config->debug) $field->notes = $fmt_note;
} else {
$field->label = sprintf(__("No Release Notes for version %s."), $new_version);
$field->notes = __('To add official release notes, please ask the module author to start using the Github [Releases](https://help.github.com/articles/creating-releases/) feature. They will have to start [tagging](https://git-scm.com/book/en/v2/Git-Basics-Tagging) the code as they push new versions in order to use this feature.');
$field->collapsed = Inputfield::collapsedYes;
}
$field->value = $release_notes;
$wrapper->add($field);
}
//
// Tag-to-Tag commit list section
//
if ($repo_supports_tag_to_tag) {
$field = $this->modules->get('InputfieldMarkup');
$field->name = 'tagged-log';
if ($has_tagged_log) {
$field->label = sprintf(__("Tag-to-Tag Commit History - from version %s to %s"), $current_version, $new_version);
} else {
$field->label = __("No Tag-to-Tag Commit History Available");
$field->notes = __('If the author doesn\'t use Github Releases, they can start to show code changes between versions if they start [tagging](https://git-scm.com/book/en/v2/Git-Basics-Tagging) each commit that increments the module version. **This helps the reader as it limits the listed commits to those representing changes.** The tags must match the version numbering scheme used by the module for this feature to work.');
}
if ($has_release_notes || $has_changelog_file) {
$field->collapsed = Inputfield::collapsedYes;
}
$field->value = "<div class='release-notes release-notes-commit-list'>$tagged_log</div>";
$wrapper->add($field);
}
//
// CHANGELOG section
//
if ($repo_supports_changelog && (!$has_release_notes || $has_changelog_file)) {
// If there are no release notes, or there is a changelog file, we show this field.
$field = $this->modules->get('InputfieldMarkup');
$field->name = 'changelog';
if ($has_changelog_file) {
$field->label = sprintf(__("Changelog from remote version %s"), $new_version);
$changelog_newtype = 'txt';
$changelog_file = $this->formatTextOfType('changelog', 'md', $changelog_file, $fmt_note, $changelog_newtype);
$changelog_file = $this->insertMarkerForVersion($current_version, $changelog_file, $changelog_newtype, $new_version);
$changelog_file = "<div class='release-notes release-notes-changelog'>$changelog_file</div>";
if ($this->config->debug) $field->notes = $fmt_note;
} else {
$field->label = sprintf(__("No Changelog from remote version %s"), $new_version);
$field->notes = __('If the author does not want to tag versions or create Github Releases, then they could consider adding (and maintaining) a ```CHANGELOG``` file in the root of the module repository. If they do, it will show up here. If they already use the releases feature, or tag module versions, this is not necessary and can lead to duplicated effort.');
$field->collapsed = Inputfield::collapsedYes;
}
$field->value = $changelog_file;
$wrapper->add($field);
}
//
// Last N commits section
//
if ($repo_supports_commit_list && !$has_tagged_log) {
$tmp_commits = $client->GetCommits($this->fallbackCommitHistory);
$client_info = $client->GetInfo();
if (null !== $tmp_commits) {
$latest_commits = $this->formatCommitList($tmp_commits, $repo_icon);
} elseif (0 == $client_info['remaining']) {
$latest_commits = $this->getReadDepletionMessage($client_info);
}
$has_latest_commits = $latest_commits != $latest_commits_default;
$field = $this->modules->get('InputfieldMarkup');
$field->name = 'commit-log';
$field->label = sprintf(__("Last %s Commits, most recent first."), $this->data['fallbackCommitHistory']);
if (!$has_latest_commits) {
$field->notes = __('Please ask the author to add support for one of the above options, as this list is simply the most recent Git commit message log. Adding and maintaining a ```CHANGELOG.md``` file is a step-up. Tagging git commits at each new version is better still, as it allows automatic diffing between versions. If on Github, using the Releases feature is a nice step up.');
}
$field->value = "<div class='release-notes release-notes-commit-list'>$latest_commits</div>";
if ($has_release_notes || $has_changelog_file) {
$field->collapsed = Inputfield::collapsedYes;
}
$wrapper->add($field);
}
//
// Display remaining reads (Debug mode only and the client has read limits.)
//
if ($this->config->debug && $client_info['reset'] !== 0) {
$wrapper->notes = sprintf(__("%s API reads remaining: %s/%s. Resets at %s"), $client_info['name'], $client_info['remaining'], $client_info['limit'], date('Y-m-d H:i:s', $client_info['reset']));
}
$return_info->children->insertAfter($wrapper, $children[0]);
});
/**
* Display README and CHANGELOG sections on all module information pages, if these files exist in the
* installation. This allows access to a level of help for modules that wasn't there before.
*/
$this->addHookAfter("ProcessModule::executeEdit", function($event) {
$info = null;
$module_class = '';
$append_info = false;
if (isset($_POST['name'])) {
$module_class = $_POST['name'];
} elseif (isset($_GET['name'])) {
$module_class = $_GET['name'];
}
$module_class = $this->sanitizer->name($module_class);
$info = $this->modules->getModuleInfoVerbose($module_class);
$outer_wrapper = new InputfieldWrapper();
$wrapper = $this->modules->get('InputfieldFieldset');
$wrapper->id = 'module-release-notes-fieldset';
$wrapper->name = 'changes-wrapper';
$wrapper->label = __("Support Files");
$wrapper->icon = 'book';
$wrapper->collapsed = $this->data['openSettings'] ? Inputfield::collapsedNo : Inputfield::collapsedYes;
$outer_wrapper->add($wrapper);
$dir = dirname(realpath($info['file']));
$append_info |= $this->addSupportFiles('readme', 'file-text-o', $wrapper, $dir.DIRECTORY_SEPARATOR."[Rr][Ee][Aa][Dd][Mm][Ee]*");
$append_info |= $this->addSupportFiles('documentation', 'file-text-o', $wrapper, $dir.DIRECTORY_SEPARATOR."[Dd][Oo][Cc][Uu][Mm][Ee][Nn][Tt][Aa][Tt][Ii][Oo][Nn]*");
$append_info |= $this->addSupportFiles('changelog', 'tags', $wrapper, $dir.DIRECTORY_SEPARATOR."[Cc][Hh][Aa][Nn][Gg][Ee][Ll][Oo][Gg]*");
$append_info |= $this->addSupportFiles('license', 'balance-scale', $wrapper, $dir.DIRECTORY_SEPARATOR."[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]*");
if ($append_info) {
$event->return = $outer_wrapper->render() . $event->return;
}
});
}
/**
* Searches for all files matching the given glob and attempts to read and format the contents of any
* matches. These are added to the given wrapper.
*/
protected function addSupportFiles($section, $icon, &$wrapper, $glob_regex) {
$append_info = false;
$files = glob($glob_regex);
foreach ($files as $filename) {
$newtype = 'txt';
$content = $this->getFormattedTextFromFile($filename, $formatting_notes, $newtype);
if (!$content) continue;
$basename = basename($filename);
if (!$this->config->debug) $formatting_notes = '';
$wrapper->add(self::wrapValueInField($section, $content, $basename, $icon, $formatting_notes));
$append_info = true;
}
return $append_info;
}
/**
* Returns a formatter for the given file extension (if possible)
*/
static function getFormatterForFiletype($ext, &$formatter_info) {
$ext = strtolower($ext);
if (empty($ext)) $ext = 'txt';
$formatter_info = @self::$formatters[$ext];
$formatter = null; // null => no load tried. false => load tried and failed.
if ($formatter_info) {
$formatter = @$formatter_info['instance'];
if (null === $formatter) {
if (is_string($formatter_info['use']) && !empty($formatter_info['use'])) {
$formatter = wire('modules')->get($formatter_info['use']);
}
self::$formatters[$ext]['instance'] = ($formatter) ? $formatter: false;
}
}
return $formatter;
}
/**
* Given a filename, tries to read and format the content with an appropriate textformatter.
*/
public function getFormattedTextFromFile($filename, &$transformation_applied, &$newtype) {
$transformation_applied = __('None');
if (!is_file($filename) || !is_readable($filename)) return false;
// Which extension is the file using?
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (empty($ext)) $ext = 'txt';
$content = file_get_contents($filename);
if (false !== $content && false != trim($content)) {
$tmpval = $newtype;
$tmp = $this->formatTextOfType(strtolower($filename), $ext, $content, $transformation_applied, $tmpval);
$tmp = self::addExpansionWrapper($tmp, __('Show All'), 'long', 'full-height');
$newtype = $tmpval;
return $tmp;
}
return false;
}
/**
* UTF-8 wordwrapping function.
*
* Source: http://php.net/manual/en/function.wordwrap.php#107570
* minor edit to correct variable $search name in else clause.
*/
protected function utf8_wordwrap($string, $break="\n", $cut=false) {
$width = $this->wordWrapColumn;
if($cut) {
// Match anything 1 to $width chars long followed by whitespace or EOS,
// otherwise match anything $width chars long
$search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
$replace = '$1$2'.$break;
} else {
// Anchor the beginning of the pattern with a lookahead
// to avoid crazy backtracking when words are longer than $width
$search = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
$replace = '$1'.$break;
}
return preg_replace($search, $replace, $string);
}
/**
* Demotes first H1 element to an H2.was-h1 element. The H1 must start at the beginning of a line.
* Strips all attributes from the H1.
*/
protected function changeH1toH2($content) {
$regex = '^<h1([^>]*)>(.*)<\/h1>';
$content = preg_replace("~$regex~im", "<h2 class=was-h1>$2</h2>", $content, 1);
return $content;
}
/**
* The github flavored markdown seems to allow for fenced codeblocks with mutliple language definitions.
* Our versions of markdown don't seem to be able to cope with this, so simplify to first language (if any)
*/
protected function simplifyMarkdownCodeblocks($content) {
$regex = '^```([a-z0-9-_]*).*$';
$content = preg_replace("~$regex~im", "```$1", $content);
return $content;
}
/**
* Adds id attributes to heading 2 and heading 3 elements to allow documentation with a working table-of-contents.
*
* As there can be more than one documentation file per module, each table-of-contents id is prefixed with the name
* of the file in which it occurs.
*
* TODO: Work out how to guarantee unique ids when multiple documentation files may be present.
*/
protected function applyIdToHeadings($filename, $content) {
$filename = str_replace(['---', '.'], '-', trim(wire('sanitizer')->pageName($filename), '-'));
$uplink = " <a class='right-align small' href='#$filename-table-of-contents'>" . __('top') . " <i class='fa fa-icon fa-chevron-up'></i></a>";
$new_content = preg_replace_callback("~<h([23])>([^<]*)</h[23]>~iU", function($matches) use ($filename, $uplink) {
$level = $matches[1];
$content = $matches[2];
$id = trim(wire('sanitizer')->pageName($content), '-');
$id = str_replace('---', '-', $id);
if ('table-of-contents' !== $id) {
$link = $uplink;
} else {
$id = "$filename-table-of-contents";
$link = '';
}
$replace = "<h$level id='$id'>$content$link</h$level>";
return $replace;
}, $content);
if (is_string($new_content)) {
$content = $new_content;
}
return $content;
}
/**
* Tries to apply an appropriate textformatter to a given content string.
* If no suitable external formatter is available, it will be passed through an internal 'verbatim' formatter.
*
* It also records which formatter was applied.
*/
protected function formatTextOfType($filename, $ext, $unsafe_content, &$transformation_applied, &$newtype) {
$filename = basename($filename);
$transforms = [];
$reason = '';
$formatter = self::getFormatterForFiletype($ext, $formatter_info);
if (true && ($formatter || ($formatter_info && $ext == 'md'))) {
$unsafe_content = $this->simplifyMarkdownCodeblocks($unsafe_content);
$transforms[] = __('Simplify Markdown codeblocks');
if (true && $formatter) {
// Attempt to use preferred formatter.
$formatter->formatValue(new \ProcessWire\Page(), new \ProcessWire\Field(), $unsafe_content);
$transforms[] = $formatter_info['type'] . ' (' . $formatter_info['use'] .')';
} else {
// Fallback to using PW's own entitiesMarkdown sanitiser...
$unsafe_content = $this->sanitizer->entitiesMarkdown($unsafe_content, true);
$transforms[] = __('PW EntitiesMarkdown');
}
// Always apply HTML purifier to the above as it has come from potentially unsafe input.
$content = $this->sanitizeString($unsafe_content);
$transforms[] = __('HTML Purifier');
// Conditionally apply automatic IDs to all headings in documentation files...
if (0 === stripos($filename, 'documentation')) {
$content = $this->applyIdToHeadings($filename, $content);
$transforms[] = __('Auto ID Headings');
}
// Conditionally apply Prism code formatting...
if ($this->usePrismIfAvailable && $this->modules->isInstalled('TextformatterPrism')) {
$this->modules->get('TextformatterPrism')->format($content);
$transforms[] = __('Prism Code Highlighter');
}
// Always demote any H1 heading to a classed H2 to prevent multiple H1s from being present and breaking the
// admin theme.
$content = $this->changeH1toH2($content);
$transforms[] = __('Demote h1 to h2');
$newtype = 'html';
} else {
/**
* Display verbatim. Need to prevent possible XSS vectors here so it is all escaped...
*
* We call html_entity_decode() to convert entities to their UTF-8 character versions when possible,
* before then passing it through htmlspecialchars() to encode angle brackets and quotes. If this is not
* done then some characters with diacritic marks remain as html entities in the code.
*/
$content = html_entity_decode($unsafe_content, ENT_COMPAT, 'UTF-8');
$transforms[] = __('HTML Entity Decode');
$content = htmlspecialchars($content, ENT_COMPAT, 'UTF-8');
$transforms[] = __('HTML Special Character Encode');
$content = $this->utf8_wordwrap($content);
$transforms[] = __('UTF8 Wordwrap');
$content = "<pre>$content</pre>";
if ($formatter_info) {
/**
* formatter_info existing shows we had a textformatter entry for this filetype but couldn't load it
*/
$reason = sprintf(
__(" because the %s formatter [%s] is not available"),
$formatter_info['type'],
$formatter_info['use']
);
$newtype = strtolower($formatter_info['type']);
}
}
$transforms = implode(' → ', $transforms);
$transformation_applied = sprintf(__("Prepared text (type '%s') using the ```%s``` format chain%s."), $ext, $transforms, $reason);
return $content;
}
protected function highlightBreakingChanges($changes, &$flag) {
$breaking_changes = explode(',', $this->breakingPhrases);
foreach ($breaking_changes as $bp) {
$bp = trim($bp);
$pos = stripos($changes, $bp);
if (false !== $pos && !$flag) {
$flag |= true;
$changes = str_ireplace($bp, "<span class=breaking-change>$bp</span>", $changes);
}
}
return $changes;
}
static $cut_regexes = [
'html' => [
'heading' => '(<h2 class=was-h1>.*</h2>)$',
'version' => '(<h[2-3][^>]*>.*%s[\s<].*)$',
],
'markdown' => [
'pre' => '<pre>',
'post' => '</pre>',
'heading' => '^(# .*)$',
'version' => '(#{2,3} \[?%s[\s\]].*)$',
],
];
protected function insertMarkerForVersion($version, $changelog, $type, $latest_version = false) {
$str_high = __("Remote");
$str_low = __("Installed");
$pre = '';
$post = '';
$heading = '';
// Slice off the <pre> and </pre> in case this is a raw, or unformatted MD file...
if (0 === stripos($changelog, '<pre>')) {
$pre = '<pre>';
$changelog = substr($changelog, 5);
}
if ('</pre>' === strtolower(substr($changelog, -6))) {
$post = '</pre>';
$changelog = substr($changelog, 0, -6);
}
$new_class = '';
$newstuff = '';
// Slice off, and preserve the first "h2.was-h1" or "# h1 title" element.
$heading_regex = @self::$cut_regexes[$type]['heading'];
if (!empty($heading_regex) && '0.0.0' !== $version) {
$heading_regex = "~$heading_regex~imU";
$parts = preg_split($heading_regex, $changelog, 3, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if (count($parts) > 1) {
$heading = array_shift($parts);
$heading = "<div class='heading has-gutter from-$type'>$heading</div>";
$changelog = trim(implode('', $parts));
}
}
$version_master_regex = @self::$cut_regexes[$type]['version'];
if (!empty($version_master_regex) && '0.0.0' !== $version) {
// Insert a marker for latest version (if given).
if (is_string($latest_version) && !empty($latest_version)) {
$version_regex = sprintf($version_master_regex, preg_quote(trim($latest_version, ',.')));
$changelog = preg_replace("~$version_regex~imU", "<span class='annotation arrow-box arrow-box-latest'>$str_high</span>\$1", $changelog, 1);
}
// Insert marker for the version we are currently on...
$version_regex = sprintf($version_master_regex, preg_quote(trim($version, ',.')));
$changelog = preg_replace("~$version_regex~imU", "<span class='annotation arrow-box arrow-box-current'>$str_low</span>\$1", $changelog, 1);
// Divide the remaining document into the new and old portions. Classes on the divs are used to control
// the display of the result.
$entries = preg_split("~$version_regex~imU", $changelog, -1, PREG_SPLIT_DELIM_CAPTURE);
$newstuff = array_shift($entries);
$newstuff .= array_shift($entries);
$oldstuff = implode('', $entries);
$new_class = "new-changes has-gutter from-$type";
$has_breaking_change = false;
$newstuff = $this->highlightBreakingChanges($newstuff, $has_breaking_change);
if ($has_breaking_change) {
$new_class .= ' breaking-change';
}
$newstuff = "<div class='$new_class'>$newstuff</div>";
$wrap_class = "old-changes has-gutter from-$type";
} else {
$oldstuff = $changelog;
$wrap_class = 'all-changes';
}
// Rebuild the changelog with the divisions in place...
$grow_label = __('Show More');
$oldstuff = self::addExpansionWrapper($oldstuff, $grow_label, $wrap_class);
$changelog = "$pre$heading$newstuff$oldstuff$post";
return $changelog;
}
/**
* Wrap the given content with a height-limiting wrapper and provide a link that expands it when clicked.
*/
static protected function addExpansionWrapper($content, $label, $expand_class='', $link_class='grow-height') {
return "<div class='expansion-wrapper'><div class='$expand_class expand'>$content</div><p class='expand-control'><a class='cursor-pointer ui-button ui-corner-all ui-state-default $link_class'><span class='ui-button-text'>$label</span></a></p></div>";
}
/**
* Builds a markup input field to contain the given information.
*/
static protected function wrapValueInField($name, $value, $label, $icon, $notes) {
$value = "<div class='release-notes release-notes-$name'>$value</div>";
$f = wire('modules')->get('InputfieldMarkup');
$f->name = $name;
$f->label = $label;
$notes = trim($notes);
if (!empty($notes)) $f->notes = $notes;
$f->value = $value;
$f->collapsed = Inputfield::collapsedYes;
$f->icon = $icon;
return $f;
}
/**
*
*/
public function init() {
parent::init();
}
/**
*
*/
static public function getModuleConfigInputfields(array $data) {
$modules = wire('modules');
$fields = new InputfieldWrapper();
$defaults = self::getDefaultConfig();
$data = array_merge($defaults, $data);
$pre_upgrade = $modules->get("InputfieldFieldset");
$pre_upgrade->label = __('Pre-Upgrade Options');
$f = $modules->get('InputfieldInteger');
$f->attr('name', 'fallbackCommitHistory');
$f->attr('inputType', 'number');
$f->attr('type', 'number');
$f->label = __('Number of Commits To Show');
$f->description = __('If there are no Release Notes, Tagged Commits or Changelog, show how many commits?');
$f->max = 30;
$f->min = 2;
$f->notes = __("Minimum 2, Maximum 30");
$f->attr('value', $data['fallbackCommitHistory']);
$f->columnWidth = 40;
$pre_upgrade->add($f);
$fields->add($pre_upgrade);
$f = $modules->get('InputfieldText');
$f->attr('name', 'breakingPhrases');
$f->label = __('Breaking Changes');
$f->description = __('A comma-separated list of words or phrases that indicate a breaking-change may be present.');
$f->notes = __("Searches will be case-insensitive.");
$f->attr('value', $data['breakingPhrases']);
$f->columnWidth = 60;
$pre_upgrade->add($f);
$module_config = $modules->get("InputfieldFieldset");
$module_config->label = __('Module Config Page Options');
$f = $modules->get('InputfieldRadios');
$f->attr('name', 'openSettings');
$f->label = __('Auto-open the "Support Files" section?');
$f->addOption(0, __('No, keep it collapsed.'));
$f->addOption(1, __('Yes, show me a list of support files.'));
$f->attr('value', $data['openSettings']);
$f->columnWidth = 50;
$module_config->add($f);
if ($modules->isInstalled('TextformatterPrism')) {
$f = $modules->get('InputfieldRadios');
$f->attr('name', 'usePrismIfAvailable');
$f->label = __('Use PRISM code formatting - if possible?');
$f->addOption(0, __('No'));
$f->addOption(1, __('Yes'));
$f->attr('value', $data['usePrismIfAvailable']);
$f->columnWidth = 50;
$module_config->add($f);
}
$fields->add($module_config);
$common_config = $modules->get("InputfieldFieldset");
$common_config->label = __('Common Options');
$f = $modules->get('InputfieldInteger');
$f->attr('name', 'wordWrapColumn');
$f->attr('inputType', 'number');
$f->attr('type', 'number');
$f->label = __('Wrap text files at which column position?');
$f->max = 300;
$f->min = 40;
$f->notes = __("Minimum 40, Maximum 300");
$f->attr('value', $data['wordWrapColumn']);
$common_config->add($f);
$fields->add($common_config);
$cache_config = $modules->get("InputfieldFieldset");
$cache_config->label = __('Cache Options');
$cache_config->collapsed = Inputfield::collapsedYes;
$cache = new \Netcarver\FileCache();
$cache_dir = self::cacheLocation($data['cacheDirectory']);
$cache->setCacheDirectory($cache_dir);
/**
* Clear out the cached files when requested to
*/
if (isset($_POST['clearCache']) && $_POST['clearCache'] == 1) {
$cache->clearCache();
$cached_files = [];
} else {
$locale = localeconv();
$cached_files = array_map(
function($i) use ($cache_dir, $locale) {
$size = number_format(filesize($i), 0, $locale['decimal_point'], $locale['thousands_sep']);
return htmlspecialchars(str_replace("$cache_dir/", '', $i)." ($size bytes)");
},
$cache->getCachedFiles()
);
}
$cached_file_count = count($cached_files);
$f = $modules->get('InputfieldText');
$f->attr('name', 'cacheDirectory');
$f->label = __('Cache Directory');
$f->notes = __("Default is the Processwire asset cache/module-release-notes");
$f->attr('value', $data['cacheDirectory']);
$cache_config->add($f);
if ($cached_file_count) {
$f = $modules->get('InputfieldMarkup');
$f->attr('name', 'cachedFiles');
$f->label = sprintf(__('Cached Content List (%u)'), $cached_file_count);
$f->attr('value', '<div class="release-notes"><pre>' . implode("\n", $cached_files) . '</pre></div>');
$f->collapsed = Inputfield::collapsedYes;
$cache_config->add($f);
$f = $modules->get('InputfieldRadios');
$f->attr('name', 'clearCache');
$f->label = __('Clear the cached files on Submit of this page?');
$f->addOption(0, __('No, keep them.'));
$f->addOption(1, __('Yes, get rid of them.'));
$f->attr('value', 0);
$cache_config->add($f);
}
$fields->add($cache_config);
return $fields;
}
/**
* Installs needed resources.
*/
public function ___install() {
}
}