PB SEO Friendly Images - Version 3.1.0

Version Description

  • serveral bugs are fixed and code was optimized
  • improved image and figure handling - Thanks to BasTaller (@bastaller)
Download this release

Release Info

Developer PascalBajorat
Plugin Icon 128x128 PB SEO Friendly Images
Version 3.1.0
Comparing to
See all releases

Code changes from version 3.0.0 to 3.1.0

inc/pbSettingsFramework.php CHANGED
@@ -8,7 +8,7 @@ if ( !class_exists('WP') ) {
8
  if( ! class_exists('pbSettingsFramework') ):
9
  class pbSettingsFramework
10
  {
11
- const version = '1.2.0';
12
  static $textDomain = false;
13
  static $page = false;
14
  static $section = false;
@@ -176,14 +176,17 @@ if( ! class_exists('pbSettingsFramework') ):
176
  return;
177
 
178
  foreach ( (array) $wp_settings_sections[$page] as $section ) {
179
- if ( $section['prepend'] )
180
  echo $section['prepend'];
 
181
 
182
- if ( $section['title'] )
183
  echo "<h2 class='pb-section-title'>{$section['title']}</h2>\n";
 
184
 
185
- if ( $section['callback'] )
186
  call_user_func( $section['callback'], $section );
 
187
 
188
  if ( ! isset( $wp_settings_fields ) || !isset( $wp_settings_fields[$page] ) || !isset( $wp_settings_fields[$page][$section['id']] ) )
189
  continue;
@@ -194,8 +197,9 @@ if( ! class_exists('pbSettingsFramework') ):
194
  echo '</table>';
195
  echo '</div>';
196
 
197
- if ( $section['append'] )
198
  echo $section['append'];
 
199
  }
200
  }
201
  }
8
  if( ! class_exists('pbSettingsFramework') ):
9
  class pbSettingsFramework
10
  {
11
+ const version = '1.3.0';
12
  static $textDomain = false;
13
  static $page = false;
14
  static $section = false;
176
  return;
177
 
178
  foreach ( (array) $wp_settings_sections[$page] as $section ) {
179
+ if ( isset($section['prepend']) && !empty($section['prepend']) ){
180
  echo $section['prepend'];
181
+ }
182
 
183
+ if ( isset($section['title']) && !empty($section['title']) ) {
184
  echo "<h2 class='pb-section-title'>{$section['title']}</h2>\n";
185
+ }
186
 
187
+ if ( isset($section['callback']) && !empty($section['callback']) ) {
188
  call_user_func( $section['callback'], $section );
189
+ }
190
 
191
  if ( ! isset( $wp_settings_fields ) || !isset( $wp_settings_fields[$page] ) || !isset( $wp_settings_fields[$page][$section['id']] ) )
192
  continue;
197
  echo '</table>';
198
  echo '</div>';
199
 
200
+ if ( isset($section['append']) && !empty($section['append']) ) {
201
  echo $section['append'];
202
+ }
203
  }
204
  }
205
  }
inc/settings.php CHANGED
@@ -556,7 +556,7 @@ if( !class_exists('pbSEOFriendlyImagesSettings') ):
556
  </h4>
557
  <div class="desc">
558
  <p><?php _e('PrimusNote is a Project Management and Team Collaboration software based on WordPress.', 'pb-seo-friendly-images') ?></p>
559
- <p><a href="https://goo.gl/D9P49K" target="_blank" class="button"><?php _e('Install Plugin', 'pb-seo-friendly-images') ?></a></p>
560
  </div>
561
  </div>
562
 
556
  </h4>
557
  <div class="desc">
558
  <p><?php _e('PrimusNote is a Project Management and Team Collaboration software based on WordPress.', 'pb-seo-friendly-images') ?></p>
559
+ <p><a href="https://goo.gl/b7SZvA" target="_blank" class="button"><?php _e('Install Plugin', 'pb-seo-friendly-images') ?></a></p>
560
  </div>
561
  </div>
562
 
pb-seo-friendly-images.php CHANGED
@@ -3,7 +3,7 @@
3
  Plugin Name: PB SEO Friendly Images
4
  Plugin URI: https://wordpress.org/extend/plugins/pb-seo-friendly-images/
5
  Description: This plugin is a full-featured solution for SEO friendly images. Optimize "alt" and "title" attributes for all images and post thumbnails. This plugin helps you to improve your traffic from search engines.
6
- Version: 3.0.0
7
  Author: Pascal Bajorat
8
  Author URI: https://www.pascal-bajorat.com
9
  Text Domain: pb-seo-friendly-images
@@ -36,7 +36,7 @@ if( !class_exists('pbSEOFriendlyImages') ):
36
 
37
  class pbSEOFriendlyImages
38
  {
39
- public static $verMajor = '3.0';
40
  public static $verMinor = '0';
41
 
42
  public static $basename = false;
@@ -255,6 +255,7 @@ if( !class_exists('pbSEOFriendlyImages') ):
255
  is_feed() || // exclude for feeds
256
  strstr( strtolower($content), 'arforms') || // exclude for ARForms
257
  strstr( strtolower($content), 'arf_form') || // exclude for ARForms
 
258
  isset($_GET['dslc']) // exclude for LiveComposer
259
  ) {
260
  return $content;
@@ -281,6 +282,26 @@ if( !class_exists('pbSEOFriendlyImages') ):
281
  return $content;
282
  }
283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  $imgTags = $document->getElementsByTagName('img');
285
 
286
  if( ! $imgTags->length )
3
  Plugin Name: PB SEO Friendly Images
4
  Plugin URI: https://wordpress.org/extend/plugins/pb-seo-friendly-images/
5
  Description: This plugin is a full-featured solution for SEO friendly images. Optimize "alt" and "title" attributes for all images and post thumbnails. This plugin helps you to improve your traffic from search engines.
6
+ Version: 3.1.0
7
  Author: Pascal Bajorat
8
  Author URI: https://www.pascal-bajorat.com
9
  Text Domain: pb-seo-friendly-images
36
 
37
  class pbSEOFriendlyImages
38
  {
39
+ public static $verMajor = '3.1';
40
  public static $verMinor = '0';
41
 
42
  public static $basename = false;
255
  is_feed() || // exclude for feeds
256
  strstr( strtolower($content), 'arforms') || // exclude for ARForms
257
  strstr( strtolower($content), 'arf_form') || // exclude for ARForms
258
+ strstr( strtolower($content), 'spb_gallery') || // exclude for spb_gallery_widget
259
  isset($_GET['dslc']) // exclude for LiveComposer
260
  ) {
261
  return $content;
282
  return $content;
283
  }
284
 
285
+ /*
286
+ * Recommendation by BasTaller
287
+ * @url https://wordpress.org/support/topic/proposal-for-best-replacement/
288
+ */
289
+ $figTags = $document->getElementsByTagName('figure');
290
+
291
+ if( ! $figTags->length ) {
292
+ foreach ($figTags as $tag){
293
+ $caption = $tag->nodeValue;
294
+ $imgTags = $tag->getElementsByTagName('img');
295
+
296
+ if( empty($caption) )
297
+ continue;
298
+
299
+ foreach ($imgTags as $tag) {
300
+ $tag->setAttribute('title', $caption);
301
+ }
302
+ }
303
+ }
304
+
305
  $imgTags = $document->getElementsByTagName('img');
306
 
307
  if( ! $imgTags->length )
plugin-update-checker/css/puc-debug-bar.css ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .puc-debug-bar-panel pre {
2
+ margin-top: 0;
3
+ }
4
+
5
+ /* Style the debug data table to match "widefat" table style used by WordPress. */
6
+ table.puc-debug-data {
7
+ width: 100%;
8
+ clear: both;
9
+ margin: 0;
10
+
11
+ border-spacing: 0;
12
+ background-color: #f9f9f9;
13
+
14
+ border-radius: 3px;
15
+ border: 1px solid #dfdfdf;
16
+ border-collapse: separate;
17
+ }
18
+
19
+ table.puc-debug-data * {
20
+ word-wrap: break-word;
21
+ }
22
+
23
+ table.puc-debug-data th {
24
+ width: 11em;
25
+ padding: 7px 7px 8px;
26
+ text-align: left;
27
+
28
+ font-family: "Georgia", "Times New Roman", "Bitstream Charter", "Times", serif;
29
+ font-weight: 400;
30
+ font-size: 14px;
31
+ line-height: 1.3em;
32
+ text-shadow: rgba(255, 255, 255, 0.804) 0 1px 0;
33
+ }
34
+
35
+ table.puc-debug-data td, table.puc-debug-data th {
36
+ border-width: 1px 0;
37
+ border-style: solid;
38
+
39
+ border-top-color: #fff;
40
+ border-bottom-color: #dfdfdf;
41
+
42
+ text-transform: none;
43
+ }
44
+
45
+ table.puc-debug-data td {
46
+ color: #555;
47
+ font-size: 12px;
48
+ padding: 4px 7px 2px;
49
+ vertical-align: top;
50
+ }
51
+
52
+ .puc-ajax-response {
53
+ border: 1px solid #dfdfdf;
54
+ border-radius: 3px;
55
+ padding: 0.5em;
56
+ margin: 5px 0;
57
+ background-color: white;
58
+ }
59
+
60
+ .puc-ajax-nonce {
61
+ display: none;
62
+ }
plugin-update-checker/debug-bar-panel.php ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('PluginUpdateCheckerPanel_3_2', false) && class_exists('Debug_Bar_Panel', false) ) {
4
+
5
+ /**
6
+ * A Debug Bar panel for the plugin update checker.
7
+ */
8
+ class PluginUpdateCheckerPanel_3_2 extends Debug_Bar_Panel {
9
+ /** @var PluginUpdateChecker_3_2 */
10
+ private $updateChecker;
11
+
12
+ private $responseBox = '<div class="puc-ajax-response" style="display: none;"></div>';
13
+
14
+ public function __construct($updateChecker) {
15
+ $this->updateChecker = $updateChecker;
16
+ $title = sprintf(
17
+ '<span id="puc-debug-menu-link-%s">PUC (%s)</span>',
18
+ esc_attr($this->updateChecker->slug),
19
+ $this->updateChecker->slug
20
+ );
21
+ parent::Debug_Bar_Panel($title);
22
+ }
23
+
24
+ public function render() {
25
+ printf(
26
+ '<div class="puc-debug-bar-panel" id="puc-debug-bar-panel_%1$s" data-slug="%1$s" data-nonce="%2$s">',
27
+ esc_attr($this->updateChecker->slug),
28
+ esc_attr(wp_create_nonce('puc-ajax'))
29
+ );
30
+
31
+ $this->displayConfiguration();
32
+ $this->displayStatus();
33
+ $this->displayCurrentUpdate();
34
+
35
+ echo '</div>';
36
+ }
37
+
38
+ private function displayConfiguration() {
39
+ echo '<h3>Configuration</h3>';
40
+ echo '<table class="puc-debug-data">';
41
+ $this->row('Plugin file', htmlentities($this->updateChecker->pluginFile));
42
+ $this->row('Slug', htmlentities($this->updateChecker->slug));
43
+ $this->row('DB option', htmlentities($this->updateChecker->optionName));
44
+
45
+ $requestInfoButton = '';
46
+ if ( function_exists('get_submit_button') ) {
47
+ $requestInfoButton = get_submit_button('Request Info', 'secondary', 'puc-request-info-button', false, array('id' => 'puc-request-info-button-' . $this->updateChecker->slug));
48
+ }
49
+ $this->row('Metadata URL', htmlentities($this->updateChecker->metadataUrl) . ' ' . $requestInfoButton . $this->responseBox);
50
+
51
+ $scheduler = $this->updateChecker->scheduler;
52
+ if ( $scheduler->checkPeriod > 0 ) {
53
+ $this->row('Automatic checks', 'Every ' . $scheduler->checkPeriod . ' hours');
54
+ } else {
55
+ $this->row('Automatic checks', 'Disabled');
56
+ }
57
+
58
+ if ( isset($scheduler->throttleRedundantChecks) ) {
59
+ if ( $scheduler->throttleRedundantChecks && ($scheduler->checkPeriod > 0) ) {
60
+ $this->row(
61
+ 'Throttling',
62
+ sprintf(
63
+ 'Enabled. If an update is already available, check for updates every %1$d hours instead of every %2$d hours.',
64
+ $scheduler->throttledCheckPeriod,
65
+ $scheduler->checkPeriod
66
+ )
67
+ );
68
+ } else {
69
+ $this->row('Throttling', 'Disabled');
70
+ }
71
+ }
72
+ echo '</table>';
73
+ }
74
+
75
+ private function displayStatus() {
76
+ echo '<h3>Status</h3>';
77
+ echo '<table class="puc-debug-data">';
78
+ $state = $this->updateChecker->getUpdateState();
79
+ $checkNowButton = '';
80
+ if ( function_exists('get_submit_button') ) {
81
+ $checkNowButton = get_submit_button('Check Now', 'secondary', 'puc-check-now-button', false, array('id' => 'puc-check-now-button-' . $this->updateChecker->slug));
82
+ }
83
+
84
+ if ( isset($state, $state->lastCheck) ) {
85
+ $this->row('Last check', $this->formatTimeWithDelta($state->lastCheck) . ' ' . $checkNowButton . $this->responseBox);
86
+ } else {
87
+ $this->row('Last check', 'Never');
88
+ }
89
+
90
+ $nextCheck = wp_next_scheduled($this->updateChecker->scheduler->getCronHookName());
91
+ $this->row('Next automatic check', $this->formatTimeWithDelta($nextCheck));
92
+
93
+ if ( isset($state, $state->checkedVersion) ) {
94
+ $this->row('Checked version', htmlentities($state->checkedVersion));
95
+ $this->row('Cached update', $state->update);
96
+ }
97
+ $this->row('Update checker class', htmlentities(get_class($this->updateChecker)));
98
+ echo '</table>';
99
+ }
100
+
101
+ private function displayCurrentUpdate() {
102
+ $update = $this->updateChecker->getUpdate();
103
+ if ( $update !== null ) {
104
+ echo '<h3>An Update Is Available</h3>';
105
+ echo '<table class="puc-debug-data">';
106
+ $fields = array('version', 'download_url', 'slug', 'homepage', 'upgrade_notice');
107
+ foreach($fields as $field) {
108
+ $this->row(ucwords(str_replace('_', ' ', $field)), htmlentities($update->$field));
109
+ }
110
+ echo '</table>';
111
+ } else {
112
+ echo '<h3>No updates currently available</h3>';
113
+ }
114
+ }
115
+
116
+ private function formatTimeWithDelta($unixTime) {
117
+ if ( empty($unixTime) ) {
118
+ return 'Never';
119
+ }
120
+
121
+ $delta = time() - $unixTime;
122
+ $result = human_time_diff(time(), $unixTime);
123
+ if ( $delta < 0 ) {
124
+ $result = 'after ' . $result;
125
+ } else {
126
+ $result = $result . ' ago';
127
+ }
128
+ $result .= ' (' . $this->formatTimestamp($unixTime) . ')';
129
+ return $result;
130
+ }
131
+
132
+ private function formatTimestamp($unixTime) {
133
+ return gmdate('Y-m-d H:i:s', $unixTime + (get_option('gmt_offset') * 3600));
134
+ }
135
+
136
+ private function row($name, $value) {
137
+ if ( is_object($value) || is_array($value) ) {
138
+ $value = '<pre>' . htmlentities(print_r($value, true)) . '</pre>';
139
+ } else if ($value === null) {
140
+ $value = '<code>null</code>';
141
+ }
142
+ printf('<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>', $name, $value);
143
+ }
144
+ }
145
+
146
+ }
plugin-update-checker/debug-bar-plugin.php ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('PucDebugBarPlugin_3_2', false) ) {
3
+
4
+ class PucDebugBarPlugin_3_2 {
5
+ /** @var PluginUpdateChecker_3_2 */
6
+ private $updateChecker;
7
+
8
+ public function __construct($updateChecker) {
9
+ $this->updateChecker = $updateChecker;
10
+
11
+ add_filter('debug_bar_panels', array($this, 'addDebugBarPanel'));
12
+ add_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies'));
13
+
14
+ add_action('wp_ajax_puc_debug_check_now', array($this, 'ajaxCheckNow'));
15
+ add_action('wp_ajax_puc_debug_request_info', array($this, 'ajaxRequestInfo'));
16
+ }
17
+
18
+ /**
19
+ * Register the PUC Debug Bar panel.
20
+ *
21
+ * @param array $panels
22
+ * @return array
23
+ */
24
+ public function addDebugBarPanel($panels) {
25
+ require_once dirname(__FILE__) . '/debug-bar-panel.php';
26
+ if ( current_user_can('update_plugins') && class_exists('PluginUpdateCheckerPanel_3_2', false) ) {
27
+ $panels[] = new PluginUpdateCheckerPanel_3_2($this->updateChecker);
28
+ }
29
+ return $panels;
30
+ }
31
+
32
+ /**
33
+ * Enqueue our Debug Bar scripts and styles.
34
+ */
35
+ public function enqueuePanelDependencies() {
36
+ wp_enqueue_style(
37
+ 'puc-debug-bar-style',
38
+ plugins_url( "/css/puc-debug-bar.css", __FILE__ ),
39
+ array('debug-bar'),
40
+ '20130927'
41
+ );
42
+
43
+ wp_enqueue_script(
44
+ 'puc-debug-bar-js',
45
+ plugins_url( "/js/debug-bar.js", __FILE__ ),
46
+ array('jquery'),
47
+ '20121026'
48
+ );
49
+ }
50
+
51
+ /**
52
+ * Run an update check and output the result. Useful for making sure that
53
+ * the update checking process works as expected.
54
+ */
55
+ public function ajaxCheckNow() {
56
+ if ( $_POST['slug'] !== $this->updateChecker->slug ) {
57
+ return;
58
+ }
59
+ $this->preAjaxReqest();
60
+ $update = $this->updateChecker->checkForUpdates();
61
+ if ( $update !== null ) {
62
+ echo "An update is available:";
63
+ echo '<pre>', htmlentities(print_r($update, true)), '</pre>';
64
+ } else {
65
+ echo 'No updates found.';
66
+ }
67
+ exit;
68
+ }
69
+
70
+ /**
71
+ * Request plugin info and output it.
72
+ */
73
+ public function ajaxRequestInfo() {
74
+ if ( $_POST['slug'] !== $this->updateChecker->slug ) {
75
+ return;
76
+ }
77
+ $this->preAjaxReqest();
78
+ $info = $this->updateChecker->requestInfo();
79
+ if ( $info !== null ) {
80
+ echo 'Successfully retrieved plugin info from the metadata URL:';
81
+ echo '<pre>', htmlentities(print_r($info, true)), '</pre>';
82
+ } else {
83
+ echo 'Failed to retrieve plugin info from the metadata URL.';
84
+ }
85
+ exit;
86
+ }
87
+
88
+ /**
89
+ * Check access permissions and enable error display (for debugging).
90
+ */
91
+ private function preAjaxReqest() {
92
+ if ( !current_user_can('update_plugins') ) {
93
+ die('Access denied');
94
+ }
95
+ check_ajax_referer('puc-ajax');
96
+
97
+ error_reporting(E_ALL);
98
+ @ini_set('display_errors','On');
99
+ }
100
+ }
101
+
102
+ }
plugin-update-checker/github-checker.php ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('PucGitHubChecker_3_2', false) ):
4
+
5
+ class PucGitHubChecker_3_2 extends PluginUpdateChecker_3_2 {
6
+ /**
7
+ * @var string GitHub username.
8
+ */
9
+ protected $userName;
10
+ /**
11
+ * @var string GitHub repository name.
12
+ */
13
+ protected $repositoryName;
14
+
15
+ /**
16
+ * @var string Either a fully qualified repository URL, or just "user/repo-name".
17
+ */
18
+ protected $repositoryUrl;
19
+
20
+ /**
21
+ * @var string The branch to use as the latest version. Defaults to "master".
22
+ */
23
+ protected $branch;
24
+
25
+ /**
26
+ * @var string GitHub authentication token. Optional.
27
+ */
28
+ protected $accessToken;
29
+
30
+ public function __construct(
31
+ $repositoryUrl,
32
+ $pluginFile,
33
+ $branch = 'master',
34
+ $checkPeriod = 12,
35
+ $optionName = '',
36
+ $muPluginFile = ''
37
+ ) {
38
+
39
+ $this->repositoryUrl = $repositoryUrl;
40
+ $this->branch = empty($branch) ? 'master' : $branch;
41
+
42
+ $path = @parse_url($repositoryUrl, PHP_URL_PATH);
43
+ if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
44
+ $this->userName = $matches['username'];
45
+ $this->repositoryName = $matches['repository'];
46
+ } else {
47
+ throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
48
+ }
49
+
50
+ parent::__construct($repositoryUrl, $pluginFile, '', $checkPeriod, $optionName, $muPluginFile);
51
+ }
52
+
53
+ /**
54
+ * Retrieve details about the latest plugin version from GitHub.
55
+ *
56
+ * @param array $unusedQueryArgs Unused.
57
+ * @return PluginInfo_3_2
58
+ */
59
+ public function requestInfo($unusedQueryArgs = array()) {
60
+ $info = new PluginInfo_3_2();
61
+ $info->filename = $this->pluginFile;
62
+ $info->slug = $this->slug;
63
+
64
+ $this->setInfoFromHeader($this->getPluginHeader(), $info);
65
+
66
+ //Figure out which reference (tag or branch) we'll use to get the latest version of the plugin.
67
+ $ref = $this->branch;
68
+ if ( $this->branch === 'master' ) {
69
+ //Use the latest release.
70
+ $release = $this->getLatestRelease();
71
+ if ( $release !== null ) {
72
+ $ref = $release->tag_name;
73
+ $info->version = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
74
+ $info->last_updated = $release->created_at;
75
+ $info->download_url = $release->zipball_url;
76
+
77
+ if ( !empty($release->body) ) {
78
+ $info->sections['changelog'] = $this->parseMarkdown($release->body);
79
+ }
80
+ if ( isset($release->assets[0]) ) {
81
+ $info->downloaded = $release->assets[0]->download_count;
82
+ }
83
+ } else {
84
+ //Failing that, use the tag with the highest version number.
85
+ $tag = $this->getLatestTag();
86
+ if ( $tag !== null ) {
87
+ $ref = $tag->name;
88
+ $info->version = $tag->name;
89
+ $info->download_url = $tag->zipball_url;
90
+ }
91
+ }
92
+ }
93
+
94
+ if ( empty($info->download_url) ) {
95
+ $info->download_url = $this->buildArchiveDownloadUrl($ref);
96
+ } else if ( !empty($this->accessToken) ) {
97
+ $info->download_url = add_query_arg('access_token', $this->accessToken, $info->download_url);
98
+ }
99
+
100
+ //Get headers from the main plugin file in this branch/tag. Its "Version" header and other metadata
101
+ //are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
102
+ $mainPluginFile = basename($this->pluginFile);
103
+ $remotePlugin = $this->getRemoteFile($mainPluginFile, $ref);
104
+ if ( !empty($remotePlugin) ) {
105
+ $remoteHeader = $this->getFileHeader($remotePlugin);
106
+ $this->setInfoFromHeader($remoteHeader, $info);
107
+ }
108
+
109
+ //Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain
110
+ //a lot of useful information like the required/tested WP version, changelog, and so on.
111
+ if ( $this->readmeTxtExistsLocally() ) {
112
+ $this->setInfoFromRemoteReadme($ref, $info);
113
+ }
114
+
115
+ //The changelog might be in a separate file.
116
+ if ( empty($info->sections['changelog']) ) {
117
+ $info->sections['changelog'] = $this->getRemoteChangelog($ref);
118
+ if ( empty($info->sections['changelog']) ) {
119
+ $info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker');
120
+ }
121
+ }
122
+
123
+ if ( empty($info->last_updated) ) {
124
+ //Fetch the latest commit that changed the main plugin file and use it as the "last_updated" date.
125
+ //It's reasonable to assume that every update will change the version number in that file.
126
+ $latestCommit = $this->getLatestCommit($mainPluginFile, $ref);
127
+ if ( $latestCommit !== null ) {
128
+ $info->last_updated = $latestCommit->commit->author->date;
129
+ }
130
+ }
131
+
132
+ $info = apply_filters('puc_request_info_result-' . $this->slug, $info, null);
133
+ return $info;
134
+ }
135
+
136
+ /**
137
+ * Get the latest release from GitHub.
138
+ *
139
+ * @return StdClass|null
140
+ */
141
+ protected function getLatestRelease() {
142
+ $releases = $this->api('/repos/:user/:repo/releases');
143
+ if ( is_wp_error($releases) || !is_array($releases) || !isset($releases[0]) ) {
144
+ return null;
145
+ }
146
+
147
+ $latestRelease = $releases[0];
148
+ return $latestRelease;
149
+ }
150
+
151
+ /**
152
+ * Get the tag that looks like the highest version number.
153
+ *
154
+ * @return StdClass|null
155
+ */
156
+ protected function getLatestTag() {
157
+ $tags = $this->api('/repos/:user/:repo/tags');
158
+
159
+ if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
160
+ return null;
161
+ }
162
+
163
+ usort($tags, array($this, 'compareTagNames')); //Sort from highest to lowest.
164
+ return $tags[0];
165
+ }
166
+
167
+ /**
168
+ * Compare two GitHub tags as if they were version number.
169
+ *
170
+ * @param string $tag1
171
+ * @param string $tag2
172
+ * @return int
173
+ */
174
+ protected function compareTagNames($tag1, $tag2) {
175
+ if ( !isset($tag1->name) ) {
176
+ return 1;
177
+ }
178
+ if ( !isset($tag2->name) ) {
179
+ return -1;
180
+ }
181
+ return -version_compare($tag1->name, $tag2->name);
182
+ }
183
+
184
+ /**
185
+ * Get the latest commit that changed the specified file.
186
+ *
187
+ * @param string $filename
188
+ * @param string $ref Reference name (e.g. branch or tag).
189
+ * @return StdClass|null
190
+ */
191
+ protected function getLatestCommit($filename, $ref = 'master') {
192
+ $commits = $this->api(
193
+ '/repos/:user/:repo/commits',
194
+ array(
195
+ 'path' => $filename,
196
+ 'sha' => $ref,
197
+ )
198
+ );
199
+ if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
200
+ return $commits[0];
201
+ }
202
+ return null;
203
+ }
204
+
205
+ protected function getRemoteChangelog($ref = '') {
206
+ $filename = $this->getChangelogFilename();
207
+ if ( empty($filename) ) {
208
+ return null;
209
+ }
210
+
211
+ $changelog = $this->getRemoteFile($filename, $ref);
212
+ if ( $changelog === null ) {
213
+ return null;
214
+ }
215
+ return $this->parseMarkdown($changelog);
216
+ }
217
+
218
+ protected function getChangelogFilename() {
219
+ $pluginDirectory = dirname($this->pluginAbsolutePath);
220
+ if ( empty($this->pluginAbsolutePath) || !is_dir($pluginDirectory) || ($pluginDirectory === '.') ) {
221
+ return null;
222
+ }
223
+
224
+ $possibleNames = array('CHANGES.md', 'CHANGELOG.md', 'changes.md', 'changelog.md');
225
+ $files = scandir($pluginDirectory);
226
+ $foundNames = array_intersect($possibleNames, $files);
227
+
228
+ if ( !empty($foundNames) ) {
229
+ return reset($foundNames);
230
+ }
231
+ return null;
232
+ }
233
+
234
+ /**
235
+ * Convert Markdown to HTML.
236
+ *
237
+ * @param string $markdown
238
+ * @return string
239
+ */
240
+ protected function parseMarkdown($markdown) {
241
+ if ( !class_exists('Parsedown', false) ) {
242
+ require_once(dirname(__FILE__) . '/vendor/Parsedown' . (version_compare(PHP_VERSION, '5.3.0', '>=') ? '' : 'Legacy') . '.php');
243
+ }
244
+
245
+ $instance = Parsedown::instance();
246
+ return $instance->text($markdown);
247
+ }
248
+
249
+ /**
250
+ * Perform a GitHub API request.
251
+ *
252
+ * @param string $url
253
+ * @param array $queryParams
254
+ * @return mixed|WP_Error
255
+ */
256
+ protected function api($url, $queryParams = array()) {
257
+ $variables = array(
258
+ 'user' => $this->userName,
259
+ 'repo' => $this->repositoryName,
260
+ );
261
+ foreach ($variables as $name => $value) {
262
+ $url = str_replace('/:' . $name, '/' . urlencode($value), $url);
263
+ }
264
+ $url = 'https://api.github.com' . $url;
265
+
266
+ if ( !empty($this->accessToken) ) {
267
+ $queryParams['access_token'] = $this->accessToken;
268
+ }
269
+ if ( !empty($queryParams) ) {
270
+ $url = add_query_arg($queryParams, $url);
271
+ }
272
+
273
+ $response = wp_remote_get($url, array('timeout' => 10));
274
+ if ( is_wp_error($response) ) {
275
+ return $response;
276
+ }
277
+
278
+ $code = wp_remote_retrieve_response_code($response);
279
+ $body = wp_remote_retrieve_body($response);
280
+ if ( $code === 200 ) {
281
+ $document = json_decode($body);
282
+ return $document;
283
+ }
284
+
285
+ return new WP_Error(
286
+ 'puc-github-http-error',
287
+ 'GitHub API error. HTTP status: ' . $code
288
+ );
289
+ }
290
+
291
+ /**
292
+ * Set the access token that will be used to make authenticated GitHub API requests.
293
+ *
294
+ * @param string $accessToken
295
+ */
296
+ public function setAccessToken($accessToken) {
297
+ $this->accessToken = $accessToken;
298
+ }
299
+
300
+ /**
301
+ * Get the contents of a file from a specific branch or tag.
302
+ *
303
+ * @param string $path File name.
304
+ * @param string $ref
305
+ * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
306
+ */
307
+ protected function getRemoteFile($path, $ref = 'master') {
308
+ $apiUrl = '/repos/:user/:repo/contents/' . $path;
309
+ $response = $this->api($apiUrl, array('ref' => $ref));
310
+
311
+ if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
312
+ return null;
313
+ }
314
+ return base64_decode($response->content);
315
+ }
316
+
317
+ /**
318
+ * Parse plugin metadata from the header comment.
319
+ * This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
320
+ *
321
+ * @param $content
322
+ * @return array
323
+ */
324
+ protected function getFileHeader($content) {
325
+ $headers = array(
326
+ 'Name' => 'Plugin Name',
327
+ 'PluginURI' => 'Plugin URI',
328
+ 'Version' => 'Version',
329
+ 'Description' => 'Description',
330
+ 'Author' => 'Author',
331
+ 'AuthorURI' => 'Author URI',
332
+ 'TextDomain' => 'Text Domain',
333
+ 'DomainPath' => 'Domain Path',
334
+ 'Network' => 'Network',
335
+
336
+ //The newest WordPress version that this plugin requires or has been tested with.
337
+ //We support several different formats for compatibility with other libraries.
338
+ 'Tested WP' => 'Tested WP',
339
+ 'Requires WP' => 'Requires WP',
340
+ 'Tested up to' => 'Tested up to',
341
+ 'Requires at least' => 'Requires at least',
342
+ );
343
+
344
+ $content = str_replace("\r", "\n", $content); //Normalize line endings.
345
+ $results = array();
346
+ foreach ($headers as $field => $name) {
347
+ $success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
348
+ if ( ($success === 1) && $matches[1] ) {
349
+ $results[$field] = _cleanup_header_comment($matches[1]);
350
+ } else {
351
+ $results[$field] = '';
352
+ }
353
+ }
354
+
355
+ return $results;
356
+ }
357
+
358
+ /**
359
+ * Copy plugin metadata from a file header to a PluginInfo object.
360
+ *
361
+ * @param array $fileHeader
362
+ * @param PluginInfo_3_2 $pluginInfo
363
+ */
364
+ protected function setInfoFromHeader($fileHeader, $pluginInfo) {
365
+ $headerToPropertyMap = array(
366
+ 'Version' => 'version',
367
+ 'Name' => 'name',
368
+ 'PluginURI' => 'homepage',
369
+ 'Author' => 'author',
370
+ 'AuthorName' => 'author',
371
+ 'AuthorURI' => 'author_homepage',
372
+
373
+ 'Requires WP' => 'requires',
374
+ 'Tested WP' => 'tested',
375
+ 'Requires at least' => 'requires',
376
+ 'Tested up to' => 'tested',
377
+ );
378
+ foreach ($headerToPropertyMap as $headerName => $property) {
379
+ if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) {
380
+ $pluginInfo->$property = $fileHeader[$headerName];
381
+ }
382
+ }
383
+
384
+ if ( !empty($fileHeader['Description']) ) {
385
+ $pluginInfo->sections['description'] = $fileHeader['Description'];
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Copy plugin metadata from the remote readme.txt file.
391
+ *
392
+ * @param string $ref GitHub tag or branch where to look for the readme.
393
+ * @param PluginInfo_3_2 $pluginInfo
394
+ */
395
+ protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
396
+ $readmeTxt = $this->getRemoteFile('readme.txt', $ref);
397
+ if ( empty($readmeTxt) ) {
398
+ return;
399
+ }
400
+
401
+ $readme = $this->parseReadme($readmeTxt);
402
+
403
+ if ( isset($readme['sections']) ) {
404
+ $pluginInfo->sections = array_merge($pluginInfo->sections, $readme['sections']);
405
+ }
406
+ if ( !empty($readme['tested_up_to']) ) {
407
+ $pluginInfo->tested = $readme['tested_up_to'];
408
+ }
409
+ if ( !empty($readme['requires_at_least']) ) {
410
+ $pluginInfo->requires = $readme['requires_at_least'];
411
+ }
412
+
413
+ if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) {
414
+ $pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version];
415
+ }
416
+ }
417
+
418
+ protected function parseReadme($content) {
419
+ if ( !class_exists('PucReadmeParser', false) ) {
420
+ require_once(dirname(__FILE__) . '/vendor/readme-parser.php');
421
+ }
422
+ $parser = new PucReadmeParser();
423
+ return $parser->parse_readme_contents($content);
424
+ }
425
+
426
+ /**
427
+ * Check if the currently installed version has a readme.txt file.
428
+ *
429
+ * @return bool
430
+ */
431
+ protected function readmeTxtExistsLocally() {
432
+ $pluginDirectory = dirname($this->pluginAbsolutePath);
433
+ if ( empty($this->pluginAbsolutePath) || !is_dir($pluginDirectory) || ($pluginDirectory === '.') ) {
434
+ return false;
435
+ }
436
+ return is_file($pluginDirectory . '/readme.txt');
437
+ }
438
+
439
+ /**
440
+ * Generate a URL to download a ZIP archive of the specified branch/tag/etc.
441
+ *
442
+ * @param string $ref
443
+ * @return string
444
+ */
445
+ protected function buildArchiveDownloadUrl($ref = 'master') {
446
+ $url = sprintf(
447
+ 'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
448
+ urlencode($this->userName),
449
+ urlencode($this->repositoryName),
450
+ urlencode($ref)
451
+ );
452
+ if ( !empty($this->accessToken) ) {
453
+ $url = add_query_arg('access_token', $this->accessToken, $url);
454
+ }
455
+ return $url;
456
+ }
457
+ }
458
+
459
+ endif;
plugin-update-checker/js/debug-bar.js ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ jQuery(function($) {
2
+
3
+ function runAjaxAction(button, action) {
4
+ button = $(button);
5
+ var panel = button.closest('.puc-debug-bar-panel');
6
+ var responseBox = button.closest('td').find('.puc-ajax-response');
7
+
8
+ responseBox.text('Processing...').show();
9
+ $.post(
10
+ ajaxurl,
11
+ {
12
+ action : action,
13
+ slug : panel.data('slug'),
14
+ _wpnonce: panel.data('nonce')
15
+ },
16
+ function(data) {
17
+ responseBox.html(data);
18
+ },
19
+ 'html'
20
+ );
21
+ }
22
+
23
+ $('.puc-debug-bar-panel input[name="puc-check-now-button"]').click(function() {
24
+ runAjaxAction(this, 'puc_debug_check_now');
25
+ return false;
26
+ });
27
+
28
+ $('.puc-debug-bar-panel input[name="puc-request-info-button"]').click(function() {
29
+ runAjaxAction(this, 'puc_debug_request_info');
30
+ return false;
31
+ });
32
+
33
+
34
+ // Debug Bar uses the panel class name as part of its link and container IDs. This means we can
35
+ // end up with multiple identical IDs if more than one plugin uses the update checker library.
36
+ // Fix it by replacing the class name with the plugin slug.
37
+ var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel');
38
+ panels.each(function(index) {
39
+ var panel = $(this);
40
+ var slug = panel.data('slug');
41
+ var target = panel.closest('.debug-menu-target');
42
+
43
+ //Change the panel wrapper ID.
44
+ target.attr('id', 'debug-menu-target-puc-' + slug);
45
+
46
+ //Change the menu link ID as well and point it at the new target ID.
47
+ $('#puc-debug-menu-link-' + panel.data('slug'))
48
+ .closest('.debug-menu-link')
49
+ .attr('id', 'debug-menu-link-puc-' + slug)
50
+ .attr('href', '#' + target.attr('id'));
51
+ });
52
+ });
plugin-update-checker/languages/plugin-update-checker-de_DE.mo ADDED
Binary file
plugin-update-checker/languages/plugin-update-checker-de_DE.po ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: plugin-update-checker\n"
4
+ "POT-Creation-Date: 2016-06-29 20:21+0100\n"
5
+ "PO-Revision-Date: 2016-06-29 20:23+0100\n"
6
+ "Last-Translator: Igor Lückel <info@igorlueckel.de>\n"
7
+ "Language-Team: \n"
8
+ "MIME-Version: 1.0\n"
9
+ "Content-Type: text/plain; charset=UTF-8\n"
10
+ "Content-Transfer-Encoding: 8bit\n"
11
+ "X-Generator: Poedit 1.8.1\n"
12
+ "X-Poedit-Basepath: ..\n"
13
+ "Plural-Forms: nplurals=2; plural=(n != 1);\n"
14
+ "X-Poedit-SourceCharset: UTF-8\n"
15
+ "X-Poedit-KeywordsList: __;_e\n"
16
+ "Language: de_DE\n"
17
+ "X-Poedit-SearchPath-0: .\n"
18
+
19
+ #: github-checker.php:137
20
+ msgid "There is no changelog available."
21
+ msgstr "Es ist keine Liste von Programmänderungen verfügbar."
22
+
23
+ #: plugin-update-checker.php:852
24
+ msgid "Check for updates"
25
+ msgstr "Nach Update suchen"
26
+
27
+ #: plugin-update-checker.php:896
28
+ msgid "This plugin is up to date."
29
+ msgstr "Das Plugin ist aktuell."
30
+
31
+ #: plugin-update-checker.php:898
32
+ msgid "A new version of this plugin is available."
33
+ msgstr "Es ist eine neue Version für das Plugin verfügbar."
34
+
35
+ #: plugin-update-checker.php:900
36
+ #, php-format
37
+ msgid "Unknown update checker status \"%s\""
38
+ msgstr "Unbekannter Update Status \"%s\""
plugin-update-checker/languages/plugin-update-checker-fa_IR.mo ADDED
Binary file
plugin-update-checker/languages/plugin-update-checker-fa_IR.po ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: plugin-update-checker\n"
4
+ "POT-Creation-Date: 2016-02-17 14:21+0100\n"
5
+ "PO-Revision-Date: 2016-10-28 14:30+0330\n"
6
+ "Last-Translator: studio RVOLA <hello@rvola.com>\n"
7
+ "Language-Team: Pro Style <info@prostyle.ir>\n"
8
+ "Language: fa_IR\n"
9
+ "MIME-Version: 1.0\n"
10
+ "Content-Type: text/plain; charset=UTF-8\n"
11
+ "Content-Transfer-Encoding: 8bit\n"
12
+ "X-Generator: Poedit 1.8.8\n"
13
+ "X-Poedit-Basepath: ..\n"
14
+ "Plural-Forms: nplurals=2; plural=(n > 1);\n"
15
+ "X-Poedit-SourceCharset: UTF-8\n"
16
+ "X-Poedit-KeywordsList: __;_e\n"
17
+ "X-Poedit-SearchPath-0: .\n"
18
+
19
+ #: github-checker.php:120
20
+ msgid "There is no changelog available."
21
+ msgstr "شرحی برای تغییرات یافت نشد"
22
+
23
+ #: plugin-update-checker.php:637
24
+ msgid "Check for updates"
25
+ msgstr "بررسی برای بروزرسانی "
26
+
27
+ #: plugin-update-checker.php:681
28
+ msgid "This plugin is up to date."
29
+ msgstr "شما از آخرین نسخه استفاده میکنید . به‌روز باشید"
30
+
31
+ #: plugin-update-checker.php:683
32
+ msgid "A new version of this plugin is available."
33
+ msgstr "نسخه جدیدی برای افزونه ارائه شده است ."
34
+
35
+ #: plugin-update-checker.php:685
36
+ #, php-format
37
+ msgid "Unknown update checker status \"%s\""
38
+ msgstr "وضعیت ناشناخته برای بروزرسانی \"%s\""
plugin-update-checker/languages/plugin-update-checker-fr_FR.mo ADDED
Binary file
plugin-update-checker/languages/plugin-update-checker-fr_FR.po ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: plugin-update-checker\n"
4
+ "POT-Creation-Date: 2016-02-17 14:21+0100\n"
5
+ "PO-Revision-Date: 2016-08-04 21:08+0200\n"
6
+ "Last-Translator: studio RVOLA <hello@rvola.com>\n"
7
+ "Language-Team: studio RVOLA <http://www.rvola.com>\n"
8
+ "Language: fr_FR\n"
9
+ "MIME-Version: 1.0\n"
10
+ "Content-Type: text/plain; charset=UTF-8\n"
11
+ "Content-Transfer-Encoding: 8bit\n"
12
+ "X-Generator: Poedit 1.8.8\n"
13
+ "X-Poedit-Basepath: ..\n"
14
+ "Plural-Forms: nplurals=2; plural=(n > 1);\n"
15
+ "X-Poedit-SourceCharset: UTF-8\n"
16
+ "X-Poedit-KeywordsList: __;_e\n"
17
+ "X-Poedit-SearchPath-0: .\n"
18
+
19
+ #: github-checker.php:120
20
+ msgid "There is no changelog available."
21
+ msgstr "Il n’y a aucun journal de mise à jour disponible."
22
+
23
+ #: plugin-update-checker.php:637
24
+ msgid "Check for updates"
25
+ msgstr "Vérifier les mises à jour"
26
+
27
+ #: plugin-update-checker.php:681
28
+ msgid "This plugin is up to date."
29
+ msgstr "Cette extension est à jour."
30
+
31
+ #: plugin-update-checker.php:683
32
+ msgid "A new version of this plugin is available."
33
+ msgstr "Une nouvelle version de cette extension est disponible."
34
+
35
+ #: plugin-update-checker.php:685
36
+ #, php-format
37
+ msgid "Unknown update checker status \"%s\""
38
+ msgstr "Un problème inconnu est survenu \"%s\""
plugin-update-checker/languages/plugin-update-checker-hu_HU.mo ADDED
Binary file
plugin-update-checker/languages/plugin-update-checker-hu_HU.po ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: plugin-update-checker\n"
4
+ "POT-Creation-Date: 2016-01-11 21:23+0100\n"
5
+ "PO-Revision-Date: 2016-01-11 21:25+0100\n"
6
+ "Last-Translator: Tamás András Horváth <htomy92@gmail.com>\n"
7
+ "Language-Team: \n"
8
+ "Language: hu_HU\n"
9
+ "MIME-Version: 1.0\n"
10
+ "Content-Type: text/plain; charset=UTF-8\n"
11
+ "Content-Transfer-Encoding: 8bit\n"
12
+ "X-Generator: Poedit 1.8.6\n"
13
+ "X-Poedit-Basepath: ..\n"
14
+ "Plural-Forms: nplurals=2; plural=(n != 1);\n"
15
+ "X-Poedit-SourceCharset: UTF-8\n"
16
+ "X-Poedit-KeywordsList: __;_e\n"
17
+ "X-Poedit-SearchPath-0: .\n"
18
+
19
+ #: github-checker.php:137
20
+ msgid "There is no changelog available."
21
+ msgstr "Nem érhető el a changelog."
22
+
23
+ #: plugin-update-checker.php:852
24
+ msgid "Check for updates"
25
+ msgstr "Frissítés ellenőrzése"
26
+
27
+ #: plugin-update-checker.php:896
28
+ msgid "This plugin is up to date."
29
+ msgstr "Ez a plugin naprakész."
30
+
31
+ #: plugin-update-checker.php:898
32
+ msgid "A new version of this plugin is available."
33
+ msgstr "Új verzió érhető el a kiegészítőhöz"
34
+
35
+ #: plugin-update-checker.php:900
36
+ #, php-format
37
+ msgid "Unknown update checker status \"%s\""
38
+ msgstr "Ismeretlen a frissítés ellenőrző státusza \"%s\""
39
+
40
+ #~ msgid "Every %d hours"
41
+ #~ msgstr "Minden %d órában"
plugin-update-checker/languages/plugin-update-checker.pot ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #, fuzzy
2
+ msgid ""
3
+ msgstr ""
4
+ "Project-Id-Version: plugin-update-checker\n"
5
+ "POT-Creation-Date: 2016-01-11 21:22+0100\n"
6
+ "PO-Revision-Date: 2016-01-10 20:59+0100\n"
7
+ "Last-Translator: Tamás András Horváth <htomy92@gmail.com>\n"
8
+ "Language-Team: \n"
9
+ "Language: en_US\n"
10
+ "MIME-Version: 1.0\n"
11
+ "Content-Type: text/plain; charset=UTF-8\n"
12
+ "Content-Transfer-Encoding: 8bit\n"
13
+ "X-Generator: Poedit 1.8.6\n"
14
+ "X-Poedit-Basepath: ..\n"
15
+ "Plural-Forms: nplurals=2; plural=(n != 1);\n"
16
+ "X-Poedit-SourceCharset: UTF-8\n"
17
+ "X-Poedit-KeywordsList: __;_e\n"
18
+ "X-Poedit-SearchPath-0: .\n"
19
+
20
+ #: github-checker.php:137
21
+ msgid "There is no changelog available."
22
+ msgstr ""
23
+
24
+ #: plugin-update-checker.php:852
25
+ msgid "Check for updates"
26
+ msgstr ""
27
+
28
+ #: plugin-update-checker.php:896
29
+ msgid "This plugin is up to date."
30
+ msgstr ""
31
+
32
+ #: plugin-update-checker.php:898
33
+ msgid "A new version of this plugin is available."
34
+ msgstr ""
35
+
36
+ #: plugin-update-checker.php:900
37
+ #, php-format
38
+ msgid "Unknown update checker status \"%s\""
39
+ msgstr ""
plugin-update-checker/license.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
1
+ Copyright (c) 2014 Jānis Elsts
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
plugin-update-checker/plugin-update-checker.php ADDED
@@ -0,0 +1,1663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Plugin Update Checker Library 3.2
4
+ * http://w-shadow.com/
5
+ *
6
+ * Copyright 2016 Janis Elsts
7
+ * Released under the MIT license. See license.txt for details.
8
+ */
9
+
10
+ if ( !class_exists('PluginUpdateChecker_3_2', false) ):
11
+
12
+ /**
13
+ * A custom plugin update checker.
14
+ *
15
+ * @author Janis Elsts
16
+ * @copyright 2016
17
+ * @version 3.2
18
+ * @access public
19
+ */
20
+ class PluginUpdateChecker_3_2 {
21
+ public $metadataUrl = ''; //The URL of the plugin's metadata file.
22
+ public $pluginAbsolutePath = ''; //Full path of the main plugin file.
23
+ public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
24
+ public $slug = ''; //Plugin slug.
25
+ public $optionName = ''; //Where to store the update info.
26
+ public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
27
+
28
+ public $debugMode = false; //Set to TRUE to enable error reporting. Errors are raised using trigger_error()
29
+ //and should be logged to the standard PHP error log.
30
+ public $scheduler;
31
+
32
+ protected $upgraderStatus;
33
+
34
+ private $debugBarPlugin = null;
35
+ private $cachedInstalledVersion = null;
36
+
37
+ private $metadataHost = ''; //The host component of $metadataUrl.
38
+
39
+ /**
40
+ * Class constructor.
41
+ *
42
+ * @param string $metadataUrl The URL of the plugin's metadata file.
43
+ * @param string $pluginFile Fully qualified path to the main plugin file.
44
+ * @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
45
+ * @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
46
+ * @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
47
+ * @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
48
+ */
49
+ public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
50
+ $this->metadataUrl = $metadataUrl;
51
+ $this->pluginAbsolutePath = $pluginFile;
52
+ $this->pluginFile = plugin_basename($this->pluginAbsolutePath);
53
+ $this->muPluginFile = $muPluginFile;
54
+ $this->slug = $slug;
55
+ $this->optionName = $optionName;
56
+ $this->debugMode = (bool)(constant('WP_DEBUG'));
57
+
58
+ //If no slug is specified, use the name of the main plugin file as the slug.
59
+ //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
60
+ if ( empty($this->slug) ){
61
+ $this->slug = basename($this->pluginFile, '.php');
62
+ }
63
+
64
+ //Plugin slugs must be unique.
65
+ $slugCheckFilter = 'puc_is_slug_in_use-' . $this->slug;
66
+ $slugUsedBy = apply_filters($slugCheckFilter, false);
67
+ if ( $slugUsedBy ) {
68
+ $this->triggerError(sprintf(
69
+ 'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
70
+ htmlentities($this->slug),
71
+ htmlentities($slugUsedBy)
72
+ ), E_USER_ERROR);
73
+ }
74
+ add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));
75
+
76
+
77
+ if ( empty($this->optionName) ){
78
+ $this->optionName = 'external_updates-' . $this->slug;
79
+ }
80
+
81
+ //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
82
+ //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
83
+ if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
84
+ $this->muPluginFile = $this->pluginFile;
85
+ }
86
+
87
+ $this->scheduler = $this->createScheduler($checkPeriod);
88
+ $this->upgraderStatus = new PucUpgraderStatus_3_2();
89
+
90
+ $this->installHooks();
91
+ }
92
+
93
+ /**
94
+ * Create an instance of the scheduler.
95
+ *
96
+ * This is implemented as a method to make it possible for plugins to subclass the update checker
97
+ * and substitute their own scheduler.
98
+ *
99
+ * @param int $checkPeriod
100
+ * @return PucScheduler_3_2
101
+ */
102
+ protected function createScheduler($checkPeriod) {
103
+ return new PucScheduler_3_2($this, $checkPeriod);
104
+ }
105
+
106
+ /**
107
+ * Install the hooks required to run periodic update checks and inject update info
108
+ * into WP data structures.
109
+ *
110
+ * @return void
111
+ */
112
+ protected function installHooks(){
113
+ //Override requests for plugin information
114
+ add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
115
+
116
+ //Insert our update info into the update array maintained by WP.
117
+ add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+
118
+ add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+
119
+ add_filter('site_transient_update_plugins', array($this, 'injectTranslationUpdates'));
120
+
121
+ add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
122
+ add_action('admin_init', array($this, 'handleManualCheck'));
123
+ add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
124
+
125
+ //Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
126
+ add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
127
+ add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
128
+ //Clear translation updates when WP clears the update cache.
129
+ //This needs to be done directly because the library doesn't actually remove obsolete plugin updates,
130
+ //it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O.
131
+ add_action('delete_site_transient_update_plugins', array($this, 'clearCachedTranslationUpdates'));
132
+
133
+ if ( did_action('plugins_loaded') ) {
134
+ $this->initDebugBarPanel();
135
+ } else {
136
+ add_action('plugins_loaded', array($this, 'initDebugBarPanel'));
137
+ }
138
+
139
+ //Rename the update directory to be the same as the existing directory.
140
+ add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);
141
+
142
+ //Enable language support (i18n).
143
+ load_plugin_textdomain('plugin-update-checker', false, plugin_basename(dirname(__FILE__)) . '/languages');
144
+
145
+ //Allow HTTP requests to the metadata URL even if it's on a local host.
146
+ $this->metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST);
147
+ add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
148
+ }
149
+
150
+ /**
151
+ * Explicitly allow HTTP requests to the metadata URL.
152
+ *
153
+ * WordPress has a security feature where the HTTP API will reject all requests that are sent to
154
+ * another site hosted on the same server as the current site (IP match), a local host, or a local
155
+ * IP, unless the host exactly matches the current site.
156
+ *
157
+ * This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
158
+ *
159
+ * That can be a problem when you're developing your plugin and you decide to host the update information
160
+ * on the same server as your test site. Update requests will mysteriously fail.
161
+ *
162
+ * We fix that by adding an exception for the metadata host.
163
+ *
164
+ * @param bool $allow
165
+ * @param string $host
166
+ * @return bool
167
+ */
168
+ public function allowMetadataHost($allow, $host) {
169
+ if ( strtolower($host) === strtolower($this->metadataHost) ) {
170
+ return true;
171
+ }
172
+ return $allow;
173
+ }
174
+
175
+ /**
176
+ * Retrieve plugin info from the configured API endpoint.
177
+ *
178
+ * @uses wp_remote_get()
179
+ *
180
+ * @param array $queryArgs Additional query arguments to append to the request. Optional.
181
+ * @return PluginInfo_3_2
182
+ */
183
+ public function requestInfo($queryArgs = array()){
184
+ //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
185
+ $installedVersion = $this->getInstalledVersion();
186
+ $queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : '';
187
+ $queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs);
188
+
189
+ //Various options for the wp_remote_get() call. Plugins can filter these, too.
190
+ $options = array(
191
+ 'timeout' => 10, //seconds
192
+ 'headers' => array(
193
+ 'Accept' => 'application/json'
194
+ ),
195
+ );
196
+ $options = apply_filters('puc_request_info_options-'.$this->slug, $options);
197
+
198
+ //The plugin info should be at 'http://your-api.com/url/here/$slug/info.json'
199
+ $url = $this->metadataUrl;
200
+ if ( !empty($queryArgs) ){
201
+ $url = add_query_arg($queryArgs, $url);
202
+ }
203
+
204
+ $result = wp_remote_get(
205
+ $url,
206
+ $options
207
+ );
208
+
209
+ //Try to parse the response
210
+ $status = $this->validateApiResponse($result);
211
+ $pluginInfo = null;
212
+ if ( !is_wp_error($status) ){
213
+ $pluginInfo = PluginInfo_3_2::fromJson($result['body']);
214
+ if ( $pluginInfo !== null ) {
215
+ $pluginInfo->filename = $this->pluginFile;
216
+ $pluginInfo->slug = $this->slug;
217
+ }
218
+ } else {
219
+ $this->triggerError(
220
+ sprintf('The URL %s does not point to a valid plugin metadata file. ', $url)
221
+ . $status->get_error_message(),
222
+ E_USER_WARNING
223
+ );
224
+ }
225
+
226
+ $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result);
227
+ return $pluginInfo;
228
+ }
229
+
230
+ /**
231
+ * Check if $result is a successful update API response.
232
+ *
233
+ * @param array|WP_Error $result
234
+ * @return true|WP_Error
235
+ */
236
+ private function validateApiResponse($result) {
237
+ if ( is_wp_error($result) ) { /** @var WP_Error $result */
238
+ return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
239
+ }
240
+
241
+ if ( !isset($result['response']['code']) ) {
242
+ return new WP_Error('puc_no_response_code', 'wp_remote_get() returned an unexpected result.');
243
+ }
244
+
245
+ if ( $result['response']['code'] !== 200 ) {
246
+ return new WP_Error(
247
+ 'puc_unexpected_response_code',
248
+ 'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
249
+ );
250
+ }
251
+
252
+ if ( empty($result['body']) ) {
253
+ return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
254
+ }
255
+
256
+ return true;
257
+ }
258
+
259
+ /**
260
+ * Retrieve the latest update (if any) from the configured API endpoint.
261
+ *
262
+ * @uses PluginUpdateChecker::requestInfo()
263
+ *
264
+ * @return PluginUpdate_3_2 An instance of PluginUpdate, or NULL when no updates are available.
265
+ */
266
+ public function requestUpdate(){
267
+ //For the sake of simplicity, this function just calls requestInfo()
268
+ //and transforms the result accordingly.
269
+ $pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
270
+ if ( $pluginInfo == null ){
271
+ return null;
272
+ }
273
+ $update = PluginUpdate_3_2::fromPluginInfo($pluginInfo);
274
+
275
+ //Keep only those translation updates that apply to this site.
276
+ $update->translations = $this->filterApplicableTranslations($update->translations);
277
+
278
+ return $update;
279
+ }
280
+
281
+ /**
282
+ * Filter a list of translation updates and return a new list that contains only updates
283
+ * that apply to the current site.
284
+ *
285
+ * @param array $translations
286
+ * @return array
287
+ */
288
+ private function filterApplicableTranslations($translations) {
289
+ $languages = array_flip(array_values(get_available_languages()));
290
+ $installedTranslations = wp_get_installed_translations('plugins');
291
+ if ( isset($installedTranslations[$this->slug]) ) {
292
+ $installedTranslations = $installedTranslations[$this->slug];
293
+ } else {
294
+ $installedTranslations = array();
295
+ }
296
+
297
+ $applicableTranslations = array();
298
+ foreach($translations as $translation) {
299
+ //Does it match one of the available core languages?
300
+ $isApplicable = array_key_exists($translation->language, $languages);
301
+ //Is it more recent than an already-installed translation?
302
+ if ( isset($installedTranslations[$translation->language]) ) {
303
+ $updateTimestamp = strtotime($translation->updated);
304
+ $installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']);
305
+ $isApplicable = $updateTimestamp > $installedTimestamp;
306
+ }
307
+
308
+ if ( $isApplicable ) {
309
+ $applicableTranslations[] = $translation;
310
+ }
311
+ }
312
+
313
+ return $applicableTranslations;
314
+ }
315
+
316
+ /**
317
+ * Get the currently installed version of the plugin.
318
+ *
319
+ * @return string Version number.
320
+ */
321
+ public function getInstalledVersion(){
322
+ if ( isset($this->cachedInstalledVersion) ) {
323
+ return $this->cachedInstalledVersion;
324
+ }
325
+
326
+ $pluginHeader = $this->getPluginHeader();
327
+ if ( isset($pluginHeader['Version']) ) {
328
+ $this->cachedInstalledVersion = $pluginHeader['Version'];
329
+ return $pluginHeader['Version'];
330
+ } else {
331
+ //This can happen if the filename points to something that is not a plugin.
332
+ $this->triggerError(
333
+ sprintf(
334
+ "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
335
+ $this->pluginFile
336
+ ),
337
+ E_USER_WARNING
338
+ );
339
+ return null;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Get plugin's metadata from its file header.
345
+ *
346
+ * @return array
347
+ */
348
+ protected function getPluginHeader() {
349
+ if ( !is_file($this->pluginAbsolutePath) ) {
350
+ //This can happen if the plugin filename is wrong.
351
+ $this->triggerError(
352
+ sprintf(
353
+ "Can't to read the plugin header for '%s'. The file does not exist.",
354
+ $this->pluginFile
355
+ ),
356
+ E_USER_WARNING
357
+ );
358
+ return array();
359
+ }
360
+
361
+ if ( !function_exists('get_plugin_data') ){
362
+ /** @noinspection PhpIncludeInspection */
363
+ require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
364
+ }
365
+ return get_plugin_data($this->pluginAbsolutePath, false, false);
366
+ }
367
+
368
+ /**
369
+ * Check for plugin updates.
370
+ * The results are stored in the DB option specified in $optionName.
371
+ *
372
+ * @return PluginUpdate_3_2|null
373
+ */
374
+ public function checkForUpdates(){
375
+ $installedVersion = $this->getInstalledVersion();
376
+ //Fail silently if we can't find the plugin or read its header.
377
+ if ( $installedVersion === null ) {
378
+ $this->triggerError(
379
+ sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile),
380
+ E_USER_WARNING
381
+ );
382
+ return null;
383
+ }
384
+
385
+ $state = $this->getUpdateState();
386
+ if ( empty($state) ){
387
+ $state = new stdClass;
388
+ $state->lastCheck = 0;
389
+ $state->checkedVersion = '';
390
+ $state->update = null;
391
+ }
392
+
393
+ $state->lastCheck = time();
394
+ $state->checkedVersion = $installedVersion;
395
+ $this->setUpdateState($state); //Save before checking in case something goes wrong
396
+
397
+ $state->update = $this->requestUpdate();
398
+ $this->setUpdateState($state);
399
+
400
+ return $this->getUpdate();
401
+ }
402
+
403
+ /**
404
+ * Load the update checker state from the DB.
405
+ *
406
+ * @return stdClass|null
407
+ */
408
+ public function getUpdateState() {
409
+ $state = get_site_option($this->optionName, null);
410
+ if ( empty($state) || !is_object($state)) {
411
+ $state = null;
412
+ }
413
+
414
+ if ( isset($state, $state->update) && is_object($state->update) ) {
415
+ $state->update = PluginUpdate_3_2::fromObject($state->update);
416
+ }
417
+ return $state;
418
+ }
419
+
420
+
421
+ /**
422
+ * Persist the update checker state to the DB.
423
+ *
424
+ * @param StdClass $state
425
+ * @return void
426
+ */
427
+ private function setUpdateState($state) {
428
+ if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) {
429
+ $update = $state->update; /** @var PluginUpdate_3_2 $update */
430
+ $state->update = $update->toStdClass();
431
+ }
432
+ update_site_option($this->optionName, $state);
433
+ }
434
+
435
+ /**
436
+ * Reset update checker state - i.e. last check time, cached update data and so on.
437
+ *
438
+ * Call this when your plugin is being uninstalled, or if you want to
439
+ * clear the update cache.
440
+ */
441
+ public function resetUpdateState() {
442
+ delete_site_option($this->optionName);
443
+ }
444
+
445
+ /**
446
+ * Intercept plugins_api() calls that request information about our plugin and
447
+ * use the configured API endpoint to satisfy them.
448
+ *
449
+ * @see plugins_api()
450
+ *
451
+ * @param mixed $result
452
+ * @param string $action
453
+ * @param array|object $args
454
+ * @return mixed
455
+ */
456
+ public function injectInfo($result, $action = null, $args = null){
457
+ $relevant = ($action == 'plugin_information') && isset($args->slug) && (
458
+ ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
459
+ );
460
+ if ( !$relevant ) {
461
+ return $result;
462
+ }
463
+
464
+ $pluginInfo = $this->requestInfo();
465
+ $pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo);
466
+ if ( $pluginInfo ) {
467
+ return $pluginInfo->toWpFormat();
468
+ }
469
+
470
+ return $result;
471
+ }
472
+
473
+ /**
474
+ * Insert the latest update (if any) into the update list maintained by WP.
475
+ *
476
+ * @param StdClass $updates Update list.
477
+ * @return StdClass Modified update list.
478
+ */
479
+ public function injectUpdate($updates){
480
+ //Is there an update to insert?
481
+ $update = $this->getUpdate();
482
+
483
+ //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
484
+ //is usually different from the main plugin file so the update wouldn't show up properly anyway.
485
+ if ( $this->isUnknownMuPlugin() ) {
486
+ $update = null;
487
+ }
488
+
489
+ if ( !empty($update) ) {
490
+ //Let plugins filter the update info before it's passed on to WordPress.
491
+ $update = apply_filters('puc_pre_inject_update-' . $this->slug, $update);
492
+ $updates = $this->addUpdateToList($updates, $update);
493
+ } else {
494
+ //Clean up any stale update info.
495
+ $updates = $this->removeUpdateFromList($updates);
496
+ }
497
+
498
+ return $updates;
499
+ }
500
+
501
+ /**
502
+ * @param StdClass|null $updates
503
+ * @param PluginUpdate_3_2 $updateToAdd
504
+ * @return StdClass
505
+ */
506
+ private function addUpdateToList($updates, $updateToAdd) {
507
+ if ( !is_object($updates) ) {
508
+ $updates = new stdClass();
509
+ $updates->response = array();
510
+ }
511
+
512
+ $wpUpdate = $updateToAdd->toWpFormat();
513
+ $pluginFile = $this->pluginFile;
514
+
515
+ if ( $this->isMuPlugin() ) {
516
+ //WP does not support automatic update installation for mu-plugins, but we can still display a notice.
517
+ $wpUpdate->package = null;
518
+ $pluginFile = $this->muPluginFile;
519
+ }
520
+ $updates->response[$pluginFile] = $wpUpdate;
521
+ return $updates;
522
+ }
523
+
524
+ /**
525
+ * @param stdClass|null $updates
526
+ * @return stdClass|null
527
+ */
528
+ private function removeUpdateFromList($updates) {
529
+ if ( isset($updates, $updates->response) ) {
530
+ unset($updates->response[$this->pluginFile]);
531
+ if ( !empty($this->muPluginFile) ) {
532
+ unset($updates->response[$this->muPluginFile]);
533
+ }
534
+ }
535
+ return $updates;
536
+ }
537
+
538
+ /**
539
+ * Insert translation updates into the list maintained by WordPress.
540
+ *
541
+ * @param stdClass $updates
542
+ * @return stdClass
543
+ */
544
+ public function injectTranslationUpdates($updates) {
545
+ $translationUpdates = $this->getTranslationUpdates();
546
+ if ( empty($translationUpdates) ) {
547
+ return $updates;
548
+ }
549
+
550
+ //Being defensive.
551
+ if ( !is_object($updates) ) {
552
+ $updates = new stdClass();
553
+ }
554
+ if ( !isset($updates->translations) ) {
555
+ $updates->translations = array();
556
+ }
557
+
558
+ //In case there's a name collision with a plugin hosted on wordpress.org,
559
+ //remove any preexisting updates that match our plugin.
560
+ $translationType = 'plugin';
561
+ $filteredTranslations = array();
562
+ foreach($updates->translations as $translation) {
563
+ if ( ($translation['type'] === $translationType) && ($translation['slug'] === $this->slug) ) {
564
+ continue;
565
+ }
566
+ $filteredTranslations[] = $translation;
567
+ }
568
+ $updates->translations = $filteredTranslations;
569
+
570
+ //Add our updates to the list.
571
+ foreach($translationUpdates as $update) {
572
+ $convertedUpdate = array_merge(
573
+ array(
574
+ 'type' => $translationType,
575
+ 'slug' => $this->slug,
576
+ 'autoupdate' => 0,
577
+ //AFAICT, WordPress doesn't actually use the "version" field for anything.
578
+ //But lets make sure it's there, just in case.
579
+ 'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)),
580
+ ),
581
+ (array)$update
582
+ );
583
+
584
+ $updates->translations[] = $convertedUpdate;
585
+ }
586
+
587
+ return $updates;
588
+ }
589
+
590
+ /**
591
+ * Rename the update directory to match the existing plugin directory.
592
+ *
593
+ * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
594
+ * exactly one directory, and that the directory name will be the same as the directory where
595
+ * the plugin/theme is currently installed.
596
+ *
597
+ * GitHub and other repositories provide ZIP downloads, but they often use directory names like
598
+ * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
599
+ *
600
+ * This is a hook callback. Don't call it from a plugin.
601
+ *
602
+ * @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource.
603
+ * @param string $remoteSource WordPress has extracted the update to this directory.
604
+ * @param WP_Upgrader $upgrader
605
+ * @return string|WP_Error
606
+ */
607
+ public function fixDirectoryName($source, $remoteSource, $upgrader) {
608
+ global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
609
+
610
+ //Basic sanity checks.
611
+ if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
612
+ return $source;
613
+ }
614
+
615
+ //If WordPress is upgrading anything other than our plugin, leave the directory name unchanged.
616
+ if ( !$this->isPluginBeingUpgraded($upgrader) ) {
617
+ return $source;
618
+ }
619
+
620
+ //Rename the source to match the existing plugin directory.
621
+ $pluginDirectoryName = dirname($this->pluginFile);
622
+ if ( $pluginDirectoryName === '.' ) {
623
+ return $source;
624
+ }
625
+ $correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/';
626
+ if ( $source !== $correctedSource ) {
627
+ //The update archive should contain a single directory that contains the rest of plugin files. Otherwise,
628
+ //WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename
629
+ //$remoteSource because that would break WordPress code that cleans up temporary files after update.
630
+ if ( $this->isBadDirectoryStructure($remoteSource) ) {
631
+ return new WP_Error(
632
+ 'puc-incorrect-directory-structure',
633
+ sprintf(
634
+ 'The directory structure of the update is incorrect. All plugin files should be inside ' .
635
+ 'a directory named <span class="code">%s</span>, not at the root of the ZIP file.',
636
+ htmlentities($this->slug)
637
+ )
638
+ );
639
+ }
640
+
641
+ /** @var WP_Upgrader_Skin $upgrader->skin */
642
+ $upgrader->skin->feedback(sprintf(
643
+ 'Renaming %s to %s&#8230;',
644
+ '<span class="code">' . basename($source) . '</span>',
645
+ '<span class="code">' . $pluginDirectoryName . '</span>'
646
+ ));
647
+
648
+ if ( $wp_filesystem->move($source, $correctedSource, true) ) {
649
+ $upgrader->skin->feedback('Plugin directory successfully renamed.');
650
+ return $correctedSource;
651
+ } else {
652
+ return new WP_Error(
653
+ 'puc-rename-failed',
654
+ 'Unable to rename the update to match the existing plugin directory.'
655
+ );
656
+ }
657
+ }
658
+
659
+ return $source;
660
+ }
661
+
662
+ /**
663
+ * Check for incorrect update directory structure. An update must contain a single directory,
664
+ * all other files should be inside that directory.
665
+ *
666
+ * @param string $remoteSource Directory path.
667
+ * @return bool
668
+ */
669
+ private function isBadDirectoryStructure($remoteSource) {
670
+ global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
671
+
672
+ $sourceFiles = $wp_filesystem->dirlist($remoteSource);
673
+ if ( is_array($sourceFiles) ) {
674
+ $sourceFiles = array_keys($sourceFiles);
675
+ $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
676
+ return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
677
+ }
678
+
679
+ //Assume it's fine.
680
+ return false;
681
+ }
682
+
683
+ /**
684
+ * Is there and update being installed RIGHT NOW, for this specific plugin?
685
+ *
686
+ * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
687
+ * @return bool
688
+ */
689
+ public function isPluginBeingUpgraded($upgrader = null) {
690
+ return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
691
+ }
692
+
693
+ /**
694
+ * Get the details of the currently available update, if any.
695
+ *
696
+ * If no updates are available, or if the last known update version is below or equal
697
+ * to the currently installed version, this method will return NULL.
698
+ *
699
+ * Uses cached update data. To retrieve update information straight from
700
+ * the metadata URL, call requestUpdate() instead.
701
+ *
702
+ * @return PluginUpdate_3_2|null
703
+ */
704
+ public function getUpdate() {
705
+ $state = $this->getUpdateState(); /** @var StdClass $state */
706
+
707
+ //Is there an update available?
708
+ if ( isset($state, $state->update) ) {
709
+ $update = $state->update;
710
+ //Check if the update is actually newer than the currently installed version.
711
+ $installedVersion = $this->getInstalledVersion();
712
+ if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
713
+ $update->filename = $this->pluginFile;
714
+ return $update;
715
+ }
716
+ }
717
+ return null;
718
+ }
719
+
720
+ /**
721
+ * Get a list of available translation updates.
722
+ *
723
+ * This method will return an empty array if there are no updates.
724
+ * Uses cached update data.
725
+ *
726
+ * @return array
727
+ */
728
+ public function getTranslationUpdates() {
729
+ $state = $this->getUpdateState();
730
+ if ( isset($state, $state->update, $state->update->translations) ) {
731
+ return $state->update->translations;
732
+ }
733
+ return array();
734
+ }
735
+
736
+ /**
737
+ * Remove all cached translation updates.
738
+ *
739
+ * @see wp_clean_update_cache
740
+ */
741
+ public function clearCachedTranslationUpdates() {
742
+ $state = $this->getUpdateState();
743
+ if ( isset($state, $state->update, $state->update->translations) ) {
744
+ $state->update->translations = array();
745
+ $this->setUpdateState($state);
746
+ }
747
+ }
748
+
749
+ /**
750
+ * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
751
+ * the new link will appear after the "Visit plugin site" link.
752
+ *
753
+ * You can change the link text by using the "puc_manual_check_link-$slug" filter.
754
+ * Returning an empty string from the filter will disable the link.
755
+ *
756
+ * @param array $pluginMeta Array of meta links.
757
+ * @param string $pluginFile
758
+ * @return array
759
+ */
760
+ public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
761
+ $isRelevant = ($pluginFile == $this->pluginFile)
762
+ || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
763
+
764
+ if ( $isRelevant && current_user_can('update_plugins') ) {
765
+ $linkUrl = wp_nonce_url(
766
+ add_query_arg(
767
+ array(
768
+ 'puc_check_for_updates' => 1,
769
+ 'puc_slug' => $this->slug,
770
+ ),
771
+ self_admin_url('plugins.php')
772
+ ),
773
+ 'puc_check_for_updates'
774
+ );
775
+
776
+ $linkText = apply_filters('puc_manual_check_link-' . $this->slug, __('Check for updates', 'plugin-update-checker'));
777
+ if ( !empty($linkText) ) {
778
+ $pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
779
+ }
780
+ }
781
+ return $pluginMeta;
782
+ }
783
+
784
+ /**
785
+ * Check for updates when the user clicks the "Check for updates" link.
786
+ * @see self::addCheckForUpdatesLink()
787
+ *
788
+ * @return void
789
+ */
790
+ public function handleManualCheck() {
791
+ $shouldCheck =
792
+ isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
793
+ && $_GET['puc_slug'] == $this->slug
794
+ && current_user_can('update_plugins')
795
+ && check_admin_referer('puc_check_for_updates');
796
+
797
+ if ( $shouldCheck ) {
798
+ $update = $this->checkForUpdates();
799
+ $status = ($update === null) ? 'no_update' : 'update_available';
800
+ wp_redirect(add_query_arg(
801
+ array(
802
+ 'puc_update_check_result' => $status,
803
+ 'puc_slug' => $this->slug,
804
+ ),
805
+ self_admin_url('plugins.php')
806
+ ));
807
+ }
808
+ }
809
+
810
+ /**
811
+ * Display the results of a manual update check.
812
+ * @see self::handleManualCheck()
813
+ *
814
+ * You can change the result message by using the "puc_manual_check_message-$slug" filter.
815
+ */
816
+ public function displayManualCheckResult() {
817
+ if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
818
+ $status = strval($_GET['puc_update_check_result']);
819
+ if ( $status == 'no_update' ) {
820
+ $message = __('This plugin is up to date.', 'plugin-update-checker');
821
+ } else if ( $status == 'update_available' ) {
822
+ $message = __('A new version of this plugin is available.', 'plugin-update-checker');
823
+ } else {
824
+ $message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
825
+ }
826
+ printf(
827
+ '<div class="updated notice is-dismissible"><p>%s</p></div>',
828
+ apply_filters('puc_manual_check_message-' . $this->slug, $message, $status)
829
+ );
830
+ }
831
+ }
832
+
833
+ /**
834
+ * Check if the plugin file is inside the mu-plugins directory.
835
+ *
836
+ * @return bool
837
+ */
838
+ protected function isMuPlugin() {
839
+ static $cachedResult = null;
840
+
841
+ if ( $cachedResult === null ) {
842
+ //Convert both paths to the canonical form before comparison.
843
+ $muPluginDir = realpath(WPMU_PLUGIN_DIR);
844
+ $pluginPath = realpath($this->pluginAbsolutePath);
845
+
846
+ $cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
847
+ }
848
+
849
+ return $cachedResult;
850
+ }
851
+
852
+ /**
853
+ * MU plugins are partially supported, but only when we know which file in mu-plugins
854
+ * corresponds to this plugin.
855
+ *
856
+ * @return bool
857
+ */
858
+ protected function isUnknownMuPlugin() {
859
+ return empty($this->muPluginFile) && $this->isMuPlugin();
860
+ }
861
+
862
+ /**
863
+ * Clear the cached plugin version. This method can be set up as a filter (hook) and will
864
+ * return the filter argument unmodified.
865
+ *
866
+ * @param mixed $filterArgument
867
+ * @return mixed
868
+ */
869
+ public function clearCachedVersion($filterArgument = null) {
870
+ $this->cachedInstalledVersion = null;
871
+ return $filterArgument;
872
+ }
873
+
874
+ /**
875
+ * Get absolute path to the main plugin file.
876
+ *
877
+ * @return string
878
+ */
879
+ public function getAbsolutePath() {
880
+ return $this->pluginAbsolutePath;
881
+ }
882
+
883
+ /**
884
+ * Register a callback for filtering query arguments.
885
+ *
886
+ * The callback function should take one argument - an associative array of query arguments.
887
+ * It should return a modified array of query arguments.
888
+ *
889
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
890
+ *
891
+ * @param callable $callback
892
+ * @return void
893
+ */
894
+ public function addQueryArgFilter($callback){
895
+ add_filter('puc_request_info_query_args-'.$this->slug, $callback);
896
+ }
897
+
898
+ /**
899
+ * Register a callback for filtering arguments passed to wp_remote_get().
900
+ *
901
+ * The callback function should take one argument - an associative array of arguments -
902
+ * and return a modified array or arguments. See the WP documentation on wp_remote_get()
903
+ * for details on what arguments are available and how they work.
904
+ *
905
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
906
+ *
907
+ * @param callable $callback
908
+ * @return void
909
+ */
910
+ public function addHttpRequestArgFilter($callback){
911
+ add_filter('puc_request_info_options-'.$this->slug, $callback);
912
+ }
913
+
914
+ /**
915
+ * Register a callback for filtering the plugin info retrieved from the external API.
916
+ *
917
+ * The callback function should take two arguments. If the plugin info was retrieved
918
+ * successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
919
+ * it will be NULL. The second argument will be the corresponding return value of
920
+ * wp_remote_get (see WP docs for details).
921
+ *
922
+ * The callback function should return a new or modified instance of PluginInfo or NULL.
923
+ *
924
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
925
+ *
926
+ * @param callable $callback
927
+ * @return void
928
+ */
929
+ public function addResultFilter($callback){
930
+ add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2);
931
+ }
932
+
933
+ /**
934
+ * Register a callback for one of the update checker filters.
935
+ *
936
+ * Identical to add_filter(), except it automatically adds the "puc_" prefix
937
+ * and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result"
938
+ * becomes "puc_request_info_result-your_plugin_slug".
939
+ *
940
+ * @param string $tag
941
+ * @param callable $callback
942
+ * @param int $priority
943
+ * @param int $acceptedArgs
944
+ */
945
+ public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
946
+ add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs);
947
+ }
948
+
949
+ /**
950
+ * Initialize the update checker Debug Bar plugin/add-on thingy.
951
+ */
952
+ public function initDebugBarPanel() {
953
+ $debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php';
954
+ if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) {
955
+ /** @noinspection PhpIncludeInspection */
956
+ require_once $debugBarPlugin;
957
+ $this->debugBarPlugin = new PucDebugBarPlugin_3_2($this);
958
+ }
959
+ }
960
+
961
+ /**
962
+ * Trigger a PHP error, but only when $debugMode is enabled.
963
+ *
964
+ * @param string $message
965
+ * @param int $errorType
966
+ */
967
+ protected function triggerError($message, $errorType) {
968
+ if ( $this->debugMode ) {
969
+ trigger_error($message, $errorType);
970
+ }
971
+ }
972
+ }
973
+
974
+ endif;
975
+
976
+ if ( !class_exists('PluginInfo_3_2', false) ):
977
+
978
+ /**
979
+ * A container class for holding and transforming various plugin metadata.
980
+ *
981
+ * @author Janis Elsts
982
+ * @copyright 2016
983
+ * @version 3.2
984
+ * @access public
985
+ */
986
+ class PluginInfo_3_2 {
987
+ //Most fields map directly to the contents of the plugin's info.json file.
988
+ //See the relevant docs for a description of their meaning.
989
+ public $name;
990
+ public $slug;
991
+ public $version;
992
+ public $homepage;
993
+ public $sections = array();
994
+ public $banners;
995
+ public $translations = array();
996
+ public $download_url;
997
+
998
+ public $author;
999
+ public $author_homepage;
1000
+
1001
+ public $requires;
1002
+ public $tested;
1003
+ public $upgrade_notice;
1004
+
1005
+ public $rating;
1006
+ public $num_ratings;
1007
+ public $downloaded;
1008
+ public $active_installs;
1009
+ public $last_updated;
1010
+
1011
+ public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
1012
+
1013
+ public $filename; //Plugin filename relative to the plugins directory.
1014
+
1015
+ /**
1016
+ * Create a new instance of PluginInfo from JSON-encoded plugin info
1017
+ * returned by an external update API.
1018
+ *
1019
+ * @param string $json Valid JSON string representing plugin info.
1020
+ * @return PluginInfo_3_2|null New instance of PluginInfo, or NULL on error.
1021
+ */
1022
+ public static function fromJson($json){
1023
+ /** @var StdClass $apiResponse */
1024
+ $apiResponse = json_decode($json);
1025
+ if ( empty($apiResponse) || !is_object($apiResponse) ){
1026
+ trigger_error(
1027
+ "Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/",
1028
+ E_USER_NOTICE
1029
+ );
1030
+ return null;
1031
+ }
1032
+
1033
+ $valid = self::validateMetadata($apiResponse);
1034
+ if ( is_wp_error($valid) ){
1035
+ trigger_error($valid->get_error_message(), E_USER_NOTICE);
1036
+ return null;
1037
+ }
1038
+
1039
+ $info = new self();
1040
+ foreach(get_object_vars($apiResponse) as $key => $value){
1041
+ $info->$key = $value;
1042
+ }
1043
+
1044
+ //json_decode decodes assoc. arrays as objects. We want it as an array.
1045
+ $info->sections = (array)$info->sections;
1046
+
1047
+ return $info;
1048
+ }
1049
+
1050
+ /**
1051
+ * Very, very basic validation.
1052
+ *
1053
+ * @param StdClass $apiResponse
1054
+ * @return bool|WP_Error
1055
+ */
1056
+ protected static function validateMetadata($apiResponse) {
1057
+ if (
1058
+ !isset($apiResponse->name, $apiResponse->version)
1059
+ || empty($apiResponse->name)
1060
+ || empty($apiResponse->version)
1061
+ ) {
1062
+ return new WP_Error(
1063
+ 'puc-invalid-metadata',
1064
+ "The plugin metadata file does not contain the required 'name' and/or 'version' keys."
1065
+ );
1066
+ }
1067
+ return true;
1068
+ }
1069
+
1070
+
1071
+ /**
1072
+ * Transform plugin info into the format used by the native WordPress.org API
1073
+ *
1074
+ * @return object
1075
+ */
1076
+ public function toWpFormat(){
1077
+ $info = new stdClass;
1078
+
1079
+ //The custom update API is built so that many fields have the same name and format
1080
+ //as those returned by the native WordPress.org API. These can be assigned directly.
1081
+ $sameFormat = array(
1082
+ 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
1083
+ 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
1084
+ );
1085
+ foreach($sameFormat as $field){
1086
+ if ( isset($this->$field) ) {
1087
+ $info->$field = $this->$field;
1088
+ } else {
1089
+ $info->$field = null;
1090
+ }
1091
+ }
1092
+
1093
+ //Other fields need to be renamed and/or transformed.
1094
+ $info->download_link = $this->download_url;
1095
+ $info->author = $this->getFormattedAuthor();
1096
+ $info->sections = array_merge(array('description' => ''), $this->sections);
1097
+
1098
+ if ( !empty($this->banners) ) {
1099
+ //WP expects an array with two keys: "high" and "low". Both are optional.
1100
+ //Docs: https://wordpress.org/plugins/about/faq/#banners
1101
+ $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
1102
+ $info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
1103
+ }
1104
+
1105
+ return $info;
1106
+ }
1107
+
1108
+ protected function getFormattedAuthor() {
1109
+ if ( !empty($this->author_homepage) ){
1110
+ return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
1111
+ }
1112
+ return $this->author;
1113
+ }
1114
+ }
1115
+
1116
+ endif;
1117
+
1118
+ if ( !class_exists('PluginUpdate_3_2', false) ):
1119
+
1120
+ /**
1121
+ * A simple container class for holding information about an available update.
1122
+ *
1123
+ * @author Janis Elsts
1124
+ * @copyright 2016
1125
+ * @version 3.2
1126
+ * @access public
1127
+ */
1128
+ class PluginUpdate_3_2 {
1129
+ public $id = 0;
1130
+ public $slug;
1131
+ public $version;
1132
+ public $homepage;
1133
+ public $download_url;
1134
+ public $upgrade_notice;
1135
+ public $tested;
1136
+ public $translations = array();
1137
+ public $filename; //Plugin filename relative to the plugins directory.
1138
+
1139
+ private static $fields = array(
1140
+ 'id', 'slug', 'version', 'homepage', 'tested',
1141
+ 'download_url', 'upgrade_notice', 'filename',
1142
+ 'translations'
1143
+ );
1144
+
1145
+ /**
1146
+ * Create a new instance of PluginUpdate from its JSON-encoded representation.
1147
+ *
1148
+ * @param string $json
1149
+ * @return PluginUpdate_3_2|null
1150
+ */
1151
+ public static function fromJson($json){
1152
+ //Since update-related information is simply a subset of the full plugin info,
1153
+ //we can parse the update JSON as if it was a plugin info string, then copy over
1154
+ //the parts that we care about.
1155
+ $pluginInfo = PluginInfo_3_2::fromJson($json);
1156
+ if ( $pluginInfo != null ) {
1157
+ return self::fromPluginInfo($pluginInfo);
1158
+ } else {
1159
+ return null;
1160
+ }
1161
+ }
1162
+
1163
+ /**
1164
+ * Create a new instance of PluginUpdate based on an instance of PluginInfo.
1165
+ * Basically, this just copies a subset of fields from one object to another.
1166
+ *
1167
+ * @param PluginInfo_3_2 $info
1168
+ * @return PluginUpdate_3_2
1169
+ */
1170
+ public static function fromPluginInfo($info){
1171
+ return self::fromObject($info);
1172
+ }
1173
+
1174
+ /**
1175
+ * Create a new instance of PluginUpdate by copying the necessary fields from
1176
+ * another object.
1177
+ *
1178
+ * @param StdClass|PluginInfo_3_2|PluginUpdate_3_2 $object The source object.
1179
+ * @return PluginUpdate_3_2 The new copy.
1180
+ */
1181
+ public static function fromObject($object) {
1182
+ $update = new self();
1183
+ $fields = self::$fields;
1184
+ if ( !empty($object->slug) ) {
1185
+ $fields = apply_filters('puc_retain_fields-' . $object->slug, $fields);
1186
+ }
1187
+ foreach($fields as $field){
1188
+ if (property_exists($object, $field)) {
1189
+ $update->$field = $object->$field;
1190
+ }
1191
+ }
1192
+ return $update;
1193
+ }
1194
+
1195
+ /**
1196
+ * Create an instance of StdClass that can later be converted back to
1197
+ * a PluginUpdate. Useful for serialization and caching, as it avoids
1198
+ * the "incomplete object" problem if the cached value is loaded before
1199
+ * this class.
1200
+ *
1201
+ * @return StdClass
1202
+ */
1203
+ public function toStdClass() {
1204
+ $object = new stdClass();
1205
+ $fields = self::$fields;
1206
+ if ( !empty($this->slug) ) {
1207
+ $fields = apply_filters('puc_retain_fields-' . $this->slug, $fields);
1208
+ }
1209
+ foreach($fields as $field){
1210
+ if (property_exists($this, $field)) {
1211
+ $object->$field = $this->$field;
1212
+ }
1213
+ }
1214
+ return $object;
1215
+ }
1216
+
1217
+
1218
+ /**
1219
+ * Transform the update into the format used by WordPress native plugin API.
1220
+ *
1221
+ * @return object
1222
+ */
1223
+ public function toWpFormat(){
1224
+ $update = new stdClass;
1225
+
1226
+ $update->id = $this->id;
1227
+ $update->slug = $this->slug;
1228
+ $update->new_version = $this->version;
1229
+ $update->url = $this->homepage;
1230
+ $update->package = $this->download_url;
1231
+ $update->tested = $this->tested;
1232
+ $update->plugin = $this->filename;
1233
+
1234
+ if ( !empty($this->upgrade_notice) ){
1235
+ $update->upgrade_notice = $this->upgrade_notice;
1236
+ }
1237
+
1238
+ return $update;
1239
+ }
1240
+ }
1241
+
1242
+ endif;
1243
+
1244
+ if ( !class_exists('PucScheduler_3_2', false) ):
1245
+
1246
+ /**
1247
+ * The scheduler decides when and how often to check for updates.
1248
+ * It calls @see PluginUpdateChecker::checkForUpdates() to perform the actual checks.
1249
+ *
1250
+ * @version 3.2
1251
+ */
1252
+ class PucScheduler_3_2 {
1253
+ public $checkPeriod = 12; //How often to check for updates (in hours).
1254
+ public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
1255
+ public $throttledCheckPeriod = 72;
1256
+
1257
+ /**
1258
+ * @var PluginUpdateChecker_3_2
1259
+ */
1260
+ protected $updateChecker;
1261
+
1262
+ private $cronHook = null;
1263
+
1264
+ /**
1265
+ * Scheduler constructor.
1266
+ *
1267
+ * @param PluginUpdateChecker_3_2 $updateChecker
1268
+ * @param int $checkPeriod How often to check for updates (in hours).
1269
+ */
1270
+ public function __construct($updateChecker, $checkPeriod) {
1271
+ $this->updateChecker = $updateChecker;
1272
+ $this->checkPeriod = $checkPeriod;
1273
+
1274
+ //Set up the periodic update checks
1275
+ $this->cronHook = 'check_plugin_updates-' . $this->updateChecker->slug;
1276
+ if ( $this->checkPeriod > 0 ){
1277
+
1278
+ //Trigger the check via Cron.
1279
+ //Try to use one of the default schedules if possible as it's less likely to conflict
1280
+ //with other plugins and their custom schedules.
1281
+ $defaultSchedules = array(
1282
+ 1 => 'hourly',
1283
+ 12 => 'twicedaily',
1284
+ 24 => 'daily',
1285
+ );
1286
+ if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
1287
+ $scheduleName = $defaultSchedules[$this->checkPeriod];
1288
+ } else {
1289
+ //Use a custom cron schedule.
1290
+ $scheduleName = 'every' . $this->checkPeriod . 'hours';
1291
+ add_filter('cron_schedules', array($this, '_addCustomSchedule'));
1292
+ }
1293
+
1294
+ if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
1295
+ wp_schedule_event(time(), $scheduleName, $this->cronHook);
1296
+ }
1297
+ add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
1298
+
1299
+ register_deactivation_hook($this->updateChecker->pluginFile, array($this, '_removeUpdaterCron'));
1300
+
1301
+ //In case Cron is disabled or unreliable, we also manually trigger
1302
+ //the periodic checks while the user is browsing the Dashboard.
1303
+ add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
1304
+
1305
+ //Like WordPress itself, we check more often on certain pages.
1306
+ /** @see wp_update_plugins */
1307
+ add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
1308
+ add_action('load-plugins.php', array($this, 'maybeCheckForUpdates'));
1309
+ add_action('load-update.php', array($this, 'maybeCheckForUpdates'));
1310
+ //This hook fires after a bulk update is complete.
1311
+ add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0);
1312
+
1313
+ } else {
1314
+ //Periodic checks are disabled.
1315
+ wp_clear_scheduled_hook($this->cronHook);
1316
+ }
1317
+ }
1318
+
1319
+ /**
1320
+ * Check for updates if the configured check interval has already elapsed.
1321
+ * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
1322
+ *
1323
+ * You can override the default behaviour by using the "puc_check_now-$slug" filter.
1324
+ * The filter callback will be passed three parameters:
1325
+ * - Current decision. TRUE = check updates now, FALSE = don't check now.
1326
+ * - Last check time as a Unix timestamp.
1327
+ * - Configured check period in hours.
1328
+ * Return TRUE to check for updates immediately, or FALSE to cancel.
1329
+ *
1330
+ * This method is declared public because it's a hook callback. Calling it directly is not recommended.
1331
+ */
1332
+ public function maybeCheckForUpdates(){
1333
+ if ( empty($this->checkPeriod) ){
1334
+ return;
1335
+ }
1336
+
1337
+ $state = $this->updateChecker->getUpdateState();
1338
+ $shouldCheck =
1339
+ empty($state) ||
1340
+ !isset($state->lastCheck) ||
1341
+ ( (time() - $state->lastCheck) >= $this->getEffectiveCheckPeriod() );
1342
+
1343
+ //Let plugin authors substitute their own algorithm.
1344
+ $shouldCheck = apply_filters(
1345
+ 'puc_check_now-' . $this->updateChecker->slug,
1346
+ $shouldCheck,
1347
+ (!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0,
1348
+ $this->checkPeriod
1349
+ );
1350
+
1351
+ if ( $shouldCheck ) {
1352
+ $this->updateChecker->checkForUpdates();
1353
+ }
1354
+ }
1355
+
1356
+ /**
1357
+ * Calculate the actual check period based on the current status and environment.
1358
+ *
1359
+ * @return int Check period in seconds.
1360
+ */
1361
+ protected function getEffectiveCheckPeriod() {
1362
+ $currentFilter = current_filter();
1363
+ if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
1364
+ //Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
1365
+ $period = 60;
1366
+ } else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) {
1367
+ //Also check more often on the "Plugins" page and /wp-admin/update.php.
1368
+ $period = 3600;
1369
+ } else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
1370
+ //Check less frequently if it's already known that an update is available.
1371
+ $period = $this->throttledCheckPeriod * 3600;
1372
+ } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
1373
+ //WordPress cron schedules are not exact, so lets do an update check even
1374
+ //if slightly less than $checkPeriod hours have elapsed since the last check.
1375
+ $cronFuzziness = 20 * 60;
1376
+ $period = $this->checkPeriod * 3600 - $cronFuzziness;
1377
+ } else {
1378
+ $period = $this->checkPeriod * 3600;
1379
+ }
1380
+
1381
+ return $period;
1382
+ }
1383
+
1384
+ /**
1385
+ * Add our custom schedule to the array of Cron schedules used by WP.
1386
+ *
1387
+ * @param array $schedules
1388
+ * @return array
1389
+ */
1390
+ public function _addCustomSchedule($schedules){
1391
+ if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
1392
+ $scheduleName = 'every' . $this->checkPeriod . 'hours';
1393
+ $schedules[$scheduleName] = array(
1394
+ 'interval' => $this->checkPeriod * 3600,
1395
+ 'display' => sprintf('Every %d hours', $this->checkPeriod),
1396
+ );
1397
+ }
1398
+ return $schedules;
1399
+ }
1400
+
1401
+ /**
1402
+ * Remove the scheduled cron event that the library uses to check for updates.
1403
+ *
1404
+ * @return void
1405
+ */
1406
+ public function _removeUpdaterCron(){
1407
+ wp_clear_scheduled_hook($this->cronHook);
1408
+ }
1409
+
1410
+ /**
1411
+ * Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
1412
+ *
1413
+ * @return string
1414
+ */
1415
+ public function getCronHookName() {
1416
+ return $this->cronHook;
1417
+ }
1418
+ }
1419
+
1420
+ endif;
1421
+
1422
+
1423
+ if ( !class_exists('PucUpgraderStatus_3_2', false) ):
1424
+
1425
+ /**
1426
+ * A utility class that helps figure out which plugin WordPress is upgrading.
1427
+ *
1428
+ * It may seem strange to have an separate class just for that, but the task is surprisingly complicated.
1429
+ * Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
1430
+ * This class uses a few workarounds and heuristics to get the file name.
1431
+ */
1432
+ class PucUpgraderStatus_3_2 {
1433
+ private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress.
1434
+
1435
+ public function __construct() {
1436
+ //Keep track of which plugin WordPress is currently upgrading.
1437
+ add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2);
1438
+ add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
1439
+ add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1);
1440
+ add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1);
1441
+ }
1442
+
1443
+ /**
1444
+ * Is there and update being installed RIGHT NOW, for a specific plugin?
1445
+ *
1446
+ * Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
1447
+ * and upgrader implementations are liable to change without notice.
1448
+ *
1449
+ * @param string $pluginFile The plugin to check.
1450
+ * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
1451
+ * @return bool True if the plugin identified by $pluginFile is being upgraded.
1452
+ */
1453
+ public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
1454
+ if ( isset($upgrader) ) {
1455
+ $upgradedPluginFile = $this->getPluginBeingUpgradedBy($upgrader);
1456
+ if ( !empty($upgradedPluginFile) ) {
1457
+ $this->upgradedPluginFile = $upgradedPluginFile;
1458
+ }
1459
+ }
1460
+ return ( !empty($this->upgradedPluginFile) && ($this->upgradedPluginFile === $pluginFile) );
1461
+ }
1462
+
1463
+ /**
1464
+ * Get the file name of the plugin that's currently being upgraded.
1465
+ *
1466
+ * @param Plugin_Upgrader|WP_Upgrader $upgrader
1467
+ * @return string|null
1468
+ */
1469
+ private function getPluginBeingUpgradedBy($upgrader) {
1470
+ if ( !isset($upgrader, $upgrader->skin) ) {
1471
+ return null;
1472
+ }
1473
+
1474
+ //Figure out which plugin is being upgraded.
1475
+ $pluginFile = null;
1476
+ $skin = $upgrader->skin;
1477
+ if ( $skin instanceof Plugin_Upgrader_Skin ) {
1478
+ if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
1479
+ $pluginFile = $skin->plugin;
1480
+ }
1481
+ } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
1482
+ //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
1483
+ //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
1484
+ //do is compare those headers to the headers of installed plugins.
1485
+ $pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
1486
+ }
1487
+
1488
+ return $pluginFile;
1489
+ }
1490
+
1491
+ /**
1492
+ * Identify an installed plugin based on its headers.
1493
+ *
1494
+ * @param array $searchHeaders The plugin file header to look for.
1495
+ * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
1496
+ */
1497
+ private function identifyPluginByHeaders($searchHeaders) {
1498
+ if ( !function_exists('get_plugins') ){
1499
+ /** @noinspection PhpIncludeInspection */
1500
+ require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
1501
+ }
1502
+
1503
+ $installedPlugins = get_plugins();
1504
+ $matches = array();
1505
+ foreach($installedPlugins as $pluginBasename => $headers) {
1506
+ $diff1 = array_diff_assoc($headers, $searchHeaders);
1507
+ $diff2 = array_diff_assoc($searchHeaders, $headers);
1508
+ if ( empty($diff1) && empty($diff2) ) {
1509
+ $matches[] = $pluginBasename;
1510
+ }
1511
+ }
1512
+
1513
+ //It's possible (though very unlikely) that there could be two plugins with identical
1514
+ //headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
1515
+ if ( count($matches) !== 1 ) {
1516
+ return null;
1517
+ }
1518
+
1519
+ return reset($matches);
1520
+ }
1521
+
1522
+ /**
1523
+ * @access private
1524
+ *
1525
+ * @param mixed $input
1526
+ * @param array $hookExtra
1527
+ * @return mixed Returns $input unaltered.
1528
+ */
1529
+ public function setUpgradedPlugin($input, $hookExtra) {
1530
+ if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) {
1531
+ $this->upgradedPluginFile = $hookExtra['plugin'];
1532
+ } else {
1533
+ $this->upgradedPluginFile = null;
1534
+ }
1535
+ return $input;
1536
+ }
1537
+
1538
+ /**
1539
+ * @access private
1540
+ *
1541
+ * @param array $options
1542
+ * @return array
1543
+ */
1544
+ public function setUpgradedPluginFromOptions($options) {
1545
+ if (isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin'])) {
1546
+ $this->upgradedPluginFile = $options['hook_extra']['plugin'];
1547
+ } else {
1548
+ $this->upgradedPluginFile = null;
1549
+ }
1550
+ return $options;
1551
+ }
1552
+
1553
+ /**
1554
+ * @access private
1555
+ *
1556
+ * @param mixed $input
1557
+ * @return mixed Returns $input unaltered.
1558
+ */
1559
+ public function clearUpgradedPlugin($input = null) {
1560
+ $this->upgradedPluginFile = null;
1561
+ return $input;
1562
+ }
1563
+ }
1564
+
1565
+ endif;
1566
+
1567
+
1568
+ if ( !class_exists('PucFactory', false) ):
1569
+
1570
+ /**
1571
+ * A factory that builds instances of other classes from this library.
1572
+ *
1573
+ * When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 1.2
1574
+ * and 1.3), this factory will always use the latest available version. Register class
1575
+ * versions by calling {@link PucFactory::addVersion()}.
1576
+ *
1577
+ * At the moment it can only build instances of the PluginUpdateChecker class. Other classes
1578
+ * are intended mainly for internal use and refer directly to specific implementations. If you
1579
+ * want to instantiate one of them anyway, you can use {@link PucFactory::getLatestClassVersion()}
1580
+ * to get the class name and then create it with <code>new $class(...)</code>.
1581
+ */
1582
+ class PucFactory {
1583
+ protected static $classVersions = array();
1584
+ protected static $sorted = false;
1585
+
1586
+ /**
1587
+ * Create a new instance of PluginUpdateChecker.
1588
+ *
1589
+ * @see PluginUpdateChecker::__construct()
1590
+ *
1591
+ * @param $metadataUrl
1592
+ * @param $pluginFile
1593
+ * @param string $slug
1594
+ * @param int $checkPeriod
1595
+ * @param string $optionName
1596
+ * @param string $muPluginFile
1597
+ * @return PluginUpdateChecker_3_2
1598
+ */
1599
+ public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
1600
+ $class = self::getLatestClassVersion('PluginUpdateChecker');
1601
+ return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
1602
+ }
1603
+
1604
+ /**
1605
+ * Get the specific class name for the latest available version of a class.
1606
+ *
1607
+ * @param string $class
1608
+ * @return string|null
1609
+ */
1610
+ public static function getLatestClassVersion($class) {
1611
+ if ( !self::$sorted ) {
1612
+ self::sortVersions();
1613
+ }
1614
+
1615
+ if ( isset(self::$classVersions[$class]) ) {
1616
+ return reset(self::$classVersions[$class]);
1617
+ } else {
1618
+ return null;
1619
+ }
1620
+ }
1621
+
1622
+ /**
1623
+ * Sort available class versions in descending order (i.e. newest first).
1624
+ */
1625
+ protected static function sortVersions() {
1626
+ foreach ( self::$classVersions as $class => $versions ) {
1627
+ uksort($versions, array(__CLASS__, 'compareVersions'));
1628
+ self::$classVersions[$class] = $versions;
1629
+ }
1630
+ self::$sorted = true;
1631
+ }
1632
+
1633
+ protected static function compareVersions($a, $b) {
1634
+ return -version_compare($a, $b);
1635
+ }
1636
+
1637
+ /**
1638
+ * Register a version of a class.
1639
+ *
1640
+ * @access private This method is only for internal use by the library.
1641
+ *
1642
+ * @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
1643
+ * @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
1644
+ * @param string $version Version number, e.g. '1.2'.
1645
+ */
1646
+ public static function addVersion($generalClass, $versionedClass, $version) {
1647
+ if ( !isset(self::$classVersions[$generalClass]) ) {
1648
+ self::$classVersions[$generalClass] = array();
1649
+ }
1650
+ self::$classVersions[$generalClass][$version] = $versionedClass;
1651
+ self::$sorted = false;
1652
+ }
1653
+ }
1654
+
1655
+ endif;
1656
+
1657
+ require_once(dirname(__FILE__) . '/github-checker.php');
1658
+
1659
+ //Register classes defined in this file with the factory.
1660
+ PucFactory::addVersion('PluginUpdateChecker', 'PluginUpdateChecker_3_2', '3.2');
1661
+ PucFactory::addVersion('PluginUpdate', 'PluginUpdate_3_2', '3.2');
1662
+ PucFactory::addVersion('PluginInfo', 'PluginInfo_3_2', '3.2');
1663
+ PucFactory::addVersion('PucGitHubChecker', 'PucGitHubChecker_3_2', '3.2');
plugin-update-checker/vendor/Parsedown.php ADDED
@@ -0,0 +1,1538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ #
4
+ #
5
+ # Parsedown
6
+ # http://parsedown.org
7
+ #
8
+ # (c) Emanuil Rusev
9
+ # http://erusev.com
10
+ #
11
+ # For the full license information, view the LICENSE file that was distributed
12
+ # with this source code.
13
+ #
14
+ #
15
+
16
+ class Parsedown
17
+ {
18
+ # ~
19
+
20
+ const version = '1.6.0';
21
+
22
+ # ~
23
+
24
+ function text($text)
25
+ {
26
+ # make sure no definitions are set
27
+ $this->DefinitionData = array();
28
+
29
+ # standardize line breaks
30
+ $text = str_replace(array("\r\n", "\r"), "\n", $text);
31
+
32
+ # remove surrounding line breaks
33
+ $text = trim($text, "\n");
34
+
35
+ # split text into lines
36
+ $lines = explode("\n", $text);
37
+
38
+ # iterate through lines to identify blocks
39
+ $markup = $this->lines($lines);
40
+
41
+ # trim line breaks
42
+ $markup = trim($markup, "\n");
43
+
44
+ return $markup;
45
+ }
46
+
47
+ #
48
+ # Setters
49
+ #
50
+
51
+ function setBreaksEnabled($breaksEnabled)
52
+ {
53
+ $this->breaksEnabled = $breaksEnabled;
54
+
55
+ return $this;
56
+ }
57
+
58
+ protected $breaksEnabled;
59
+
60
+ function setMarkupEscaped($markupEscaped)
61
+ {
62
+ $this->markupEscaped = $markupEscaped;
63
+
64
+ return $this;
65
+ }
66
+
67
+ protected $markupEscaped;
68
+
69
+ function setUrlsLinked($urlsLinked)
70
+ {
71
+ $this->urlsLinked = $urlsLinked;
72
+
73
+ return $this;
74
+ }
75
+
76
+ protected $urlsLinked = true;
77
+
78
+ #
79
+ # Lines
80
+ #
81
+
82
+ protected $BlockTypes = array(
83
+ '#' => array('Header'),
84
+ '*' => array('Rule', 'List'),
85
+ '+' => array('List'),
86
+ '-' => array('SetextHeader', 'Table', 'Rule', 'List'),
87
+ '0' => array('List'),
88
+ '1' => array('List'),
89
+ '2' => array('List'),
90
+ '3' => array('List'),
91
+ '4' => array('List'),
92
+ '5' => array('List'),
93
+ '6' => array('List'),
94
+ '7' => array('List'),
95
+ '8' => array('List'),
96
+ '9' => array('List'),
97
+ ':' => array('Table'),
98
+ '<' => array('Comment', 'Markup'),
99
+ '=' => array('SetextHeader'),
100
+ '>' => array('Quote'),
101
+ '[' => array('Reference'),
102
+ '_' => array('Rule'),
103
+ '`' => array('FencedCode'),
104
+ '|' => array('Table'),
105
+ '~' => array('FencedCode'),
106
+ );
107
+
108
+ # ~
109
+
110
+ protected $unmarkedBlockTypes = array(
111
+ 'Code',
112
+ );
113
+
114
+ #
115
+ # Blocks
116
+ #
117
+
118
+ protected function lines(array $lines)
119
+ {
120
+ $CurrentBlock = null;
121
+
122
+ foreach ($lines as $line)
123
+ {
124
+ if (chop($line) === '')
125
+ {
126
+ if (isset($CurrentBlock))
127
+ {
128
+ $CurrentBlock['interrupted'] = true;
129
+ }
130
+
131
+ continue;
132
+ }
133
+
134
+ if (strpos($line, "\t") !== false)
135
+ {
136
+ $parts = explode("\t", $line);
137
+
138
+ $line = $parts[0];
139
+
140
+ unset($parts[0]);
141
+
142
+ foreach ($parts as $part)
143
+ {
144
+ $shortage = 4 - mb_strlen($line, 'utf-8') % 4;
145
+
146
+ $line .= str_repeat(' ', $shortage);
147
+ $line .= $part;
148
+ }
149
+ }
150
+
151
+ $indent = 0;
152
+
153
+ while (isset($line[$indent]) and $line[$indent] === ' ')
154
+ {
155
+ $indent ++;
156
+ }
157
+
158
+ $text = $indent > 0 ? substr($line, $indent) : $line;
159
+
160
+ # ~
161
+
162
+ $Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
163
+
164
+ # ~
165
+
166
+ if (isset($CurrentBlock['continuable']))
167
+ {
168
+ $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
169
+
170
+ if (isset($Block))
171
+ {
172
+ $CurrentBlock = $Block;
173
+
174
+ continue;
175
+ }
176
+ else
177
+ {
178
+ if ($this->isBlockCompletable($CurrentBlock['type']))
179
+ {
180
+ $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
181
+ }
182
+ }
183
+ }
184
+
185
+ # ~
186
+
187
+ $marker = $text[0];
188
+
189
+ # ~
190
+
191
+ $blockTypes = $this->unmarkedBlockTypes;
192
+
193
+ if (isset($this->BlockTypes[$marker]))
194
+ {
195
+ foreach ($this->BlockTypes[$marker] as $blockType)
196
+ {
197
+ $blockTypes []= $blockType;
198
+ }
199
+ }
200
+
201
+ #
202
+ # ~
203
+
204
+ foreach ($blockTypes as $blockType)
205
+ {
206
+ $Block = $this->{'block'.$blockType}($Line, $CurrentBlock);
207
+
208
+ if (isset($Block))
209
+ {
210
+ $Block['type'] = $blockType;
211
+
212
+ if ( ! isset($Block['identified']))
213
+ {
214
+ $Blocks []= $CurrentBlock;
215
+
216
+ $Block['identified'] = true;
217
+ }
218
+
219
+ if ($this->isBlockContinuable($blockType))
220
+ {
221
+ $Block['continuable'] = true;
222
+ }
223
+
224
+ $CurrentBlock = $Block;
225
+
226
+ continue 2;
227
+ }
228
+ }
229
+
230
+ # ~
231
+
232
+ if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted']))
233
+ {
234
+ $CurrentBlock['element']['text'] .= "\n".$text;
235
+ }
236
+ else
237
+ {
238
+ $Blocks []= $CurrentBlock;
239
+
240
+ $CurrentBlock = $this->paragraph($Line);
241
+
242
+ $CurrentBlock['identified'] = true;
243
+ }
244
+ }
245
+
246
+ # ~
247
+
248
+ if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))
249
+ {
250
+ $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
251
+ }
252
+
253
+ # ~
254
+
255
+ $Blocks []= $CurrentBlock;
256
+
257
+ unset($Blocks[0]);
258
+
259
+ # ~
260
+
261
+ $markup = '';
262
+
263
+ foreach ($Blocks as $Block)
264
+ {
265
+ if (isset($Block['hidden']))
266
+ {
267
+ continue;
268
+ }
269
+
270
+ $markup .= "\n";
271
+ $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']);
272
+ }
273
+
274
+ $markup .= "\n";
275
+
276
+ # ~
277
+
278
+ return $markup;
279
+ }
280
+
281
+ protected function isBlockContinuable($Type)
282
+ {
283
+ return method_exists($this, 'block'.$Type.'Continue');
284
+ }
285
+
286
+ protected function isBlockCompletable($Type)
287
+ {
288
+ return method_exists($this, 'block'.$Type.'Complete');
289
+ }
290
+
291
+ #
292
+ # Code
293
+
294
+ protected function blockCode($Line, $Block = null)
295
+ {
296
+ if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted']))
297
+ {
298
+ return;
299
+ }
300
+
301
+ if ($Line['indent'] >= 4)
302
+ {
303
+ $text = substr($Line['body'], 4);
304
+
305
+ $Block = array(
306
+ 'element' => array(
307
+ 'name' => 'pre',
308
+ 'handler' => 'element',
309
+ 'text' => array(
310
+ 'name' => 'code',
311
+ 'text' => $text,
312
+ ),
313
+ ),
314
+ );
315
+
316
+ return $Block;
317
+ }
318
+ }
319
+
320
+ protected function blockCodeContinue($Line, $Block)
321
+ {
322
+ if ($Line['indent'] >= 4)
323
+ {
324
+ if (isset($Block['interrupted']))
325
+ {
326
+ $Block['element']['text']['text'] .= "\n";
327
+
328
+ unset($Block['interrupted']);
329
+ }
330
+
331
+ $Block['element']['text']['text'] .= "\n";
332
+
333
+ $text = substr($Line['body'], 4);
334
+
335
+ $Block['element']['text']['text'] .= $text;
336
+
337
+ return $Block;
338
+ }
339
+ }
340
+
341
+ protected function blockCodeComplete($Block)
342
+ {
343
+ $text = $Block['element']['text']['text'];
344
+
345
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
346
+
347
+ $Block['element']['text']['text'] = $text;
348
+
349
+ return $Block;
350
+ }
351
+
352
+ #
353
+ # Comment
354
+
355
+ protected function blockComment($Line)
356
+ {
357
+ if ($this->markupEscaped)
358
+ {
359
+ return;
360
+ }
361
+
362
+ if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
363
+ {
364
+ $Block = array(
365
+ 'markup' => $Line['body'],
366
+ );
367
+
368
+ if (preg_match('/-->$/', $Line['text']))
369
+ {
370
+ $Block['closed'] = true;
371
+ }
372
+
373
+ return $Block;
374
+ }
375
+ }
376
+
377
+ protected function blockCommentContinue($Line, array $Block)
378
+ {
379
+ if (isset($Block['closed']))
380
+ {
381
+ return;
382
+ }
383
+
384
+ $Block['markup'] .= "\n" . $Line['body'];
385
+
386
+ if (preg_match('/-->$/', $Line['text']))
387
+ {
388
+ $Block['closed'] = true;
389
+ }
390
+
391
+ return $Block;
392
+ }
393
+
394
+ #
395
+ # Fenced Code
396
+
397
+ protected function blockFencedCode($Line)
398
+ {
399
+ if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
400
+ {
401
+ $Element = array(
402
+ 'name' => 'code',
403
+ 'text' => '',
404
+ );
405
+
406
+ if (isset($matches[1]))
407
+ {
408
+ $class = 'language-'.$matches[1];
409
+
410
+ $Element['attributes'] = array(
411
+ 'class' => $class,
412
+ );
413
+ }
414
+
415
+ $Block = array(
416
+ 'char' => $Line['text'][0],
417
+ 'element' => array(
418
+ 'name' => 'pre',
419
+ 'handler' => 'element',
420
+ 'text' => $Element,
421
+ ),
422
+ );
423
+
424
+ return $Block;
425
+ }
426
+ }
427
+
428
+ protected function blockFencedCodeContinue($Line, $Block)
429
+ {
430
+ if (isset($Block['complete']))
431
+ {
432
+ return;
433
+ }
434
+
435
+ if (isset($Block['interrupted']))
436
+ {
437
+ $Block['element']['text']['text'] .= "\n";
438
+
439
+ unset($Block['interrupted']);
440
+ }
441
+
442
+ if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text']))
443
+ {
444
+ $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
445
+
446
+ $Block['complete'] = true;
447
+
448
+ return $Block;
449
+ }
450
+
451
+ $Block['element']['text']['text'] .= "\n".$Line['body'];;
452
+
453
+ return $Block;
454
+ }
455
+
456
+ protected function blockFencedCodeComplete($Block)
457
+ {
458
+ $text = $Block['element']['text']['text'];
459
+
460
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
461
+
462
+ $Block['element']['text']['text'] = $text;
463
+
464
+ return $Block;
465
+ }
466
+
467
+ #
468
+ # Header
469
+
470
+ protected function blockHeader($Line)
471
+ {
472
+ if (isset($Line['text'][1]))
473
+ {
474
+ $level = 1;
475
+
476
+ while (isset($Line['text'][$level]) and $Line['text'][$level] === '#')
477
+ {
478
+ $level ++;
479
+ }
480
+
481
+ if ($level > 6)
482
+ {
483
+ return;
484
+ }
485
+
486
+ $text = trim($Line['text'], '# ');
487
+
488
+ $Block = array(
489
+ 'element' => array(
490
+ 'name' => 'h' . min(6, $level),
491
+ 'text' => $text,
492
+ 'handler' => 'line',
493
+ ),
494
+ );
495
+
496
+ return $Block;
497
+ }
498
+ }
499
+
500
+ #
501
+ # List
502
+
503
+ protected function blockList($Line)
504
+ {
505
+ list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]');
506
+
507
+ if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches))
508
+ {
509
+ $Block = array(
510
+ 'indent' => $Line['indent'],
511
+ 'pattern' => $pattern,
512
+ 'element' => array(
513
+ 'name' => $name,
514
+ 'handler' => 'elements',
515
+ ),
516
+ );
517
+
518
+ $Block['li'] = array(
519
+ 'name' => 'li',
520
+ 'handler' => 'li',
521
+ 'text' => array(
522
+ $matches[2],
523
+ ),
524
+ );
525
+
526
+ $Block['element']['text'] []= & $Block['li'];
527
+
528
+ return $Block;
529
+ }
530
+ }
531
+
532
+ protected function blockListContinue($Line, array $Block)
533
+ {
534
+ if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
535
+ {
536
+ if (isset($Block['interrupted']))
537
+ {
538
+ $Block['li']['text'] []= '';
539
+
540
+ unset($Block['interrupted']);
541
+ }
542
+
543
+ unset($Block['li']);
544
+
545
+ $text = isset($matches[1]) ? $matches[1] : '';
546
+
547
+ $Block['li'] = array(
548
+ 'name' => 'li',
549
+ 'handler' => 'li',
550
+ 'text' => array(
551
+ $text,
552
+ ),
553
+ );
554
+
555
+ $Block['element']['text'] []= & $Block['li'];
556
+
557
+ return $Block;
558
+ }
559
+
560
+ if ($Line['text'][0] === '[' and $this->blockReference($Line))
561
+ {
562
+ return $Block;
563
+ }
564
+
565
+ if ( ! isset($Block['interrupted']))
566
+ {
567
+ $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
568
+
569
+ $Block['li']['text'] []= $text;
570
+
571
+ return $Block;
572
+ }
573
+
574
+ if ($Line['indent'] > 0)
575
+ {
576
+ $Block['li']['text'] []= '';
577
+
578
+ $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
579
+
580
+ $Block['li']['text'] []= $text;
581
+
582
+ unset($Block['interrupted']);
583
+
584
+ return $Block;
585
+ }
586
+ }
587
+
588
+ #
589
+ # Quote
590
+
591
+ protected function blockQuote($Line)
592
+ {
593
+ if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
594
+ {
595
+ $Block = array(
596
+ 'element' => array(
597
+ 'name' => 'blockquote',
598
+ 'handler' => 'lines',
599
+ 'text' => (array) $matches[1],
600
+ ),
601
+ );
602
+
603
+ return $Block;
604
+ }
605
+ }
606
+
607
+ protected function blockQuoteContinue($Line, array $Block)
608
+ {
609
+ if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
610
+ {
611
+ if (isset($Block['interrupted']))
612
+ {
613
+ $Block['element']['text'] []= '';
614
+
615
+ unset($Block['interrupted']);
616
+ }
617
+
618
+ $Block['element']['text'] []= $matches[1];
619
+
620
+ return $Block;
621
+ }
622
+
623
+ if ( ! isset($Block['interrupted']))
624
+ {
625
+ $Block['element']['text'] []= $Line['text'];
626
+
627
+ return $Block;
628
+ }
629
+ }
630
+
631
+ #
632
+ # Rule
633
+
634
+ protected function blockRule($Line)
635
+ {
636
+ if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
637
+ {
638
+ $Block = array(
639
+ 'element' => array(
640
+ 'name' => 'hr'
641
+ ),
642
+ );
643
+
644
+ return $Block;
645
+ }
646
+ }
647
+
648
+ #
649
+ # Setext
650
+
651
+ protected function blockSetextHeader($Line, array $Block = null)
652
+ {
653
+ if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
654
+ {
655
+ return;
656
+ }
657
+
658
+ if (chop($Line['text'], $Line['text'][0]) === '')
659
+ {
660
+ $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
661
+
662
+ return $Block;
663
+ }
664
+ }
665
+
666
+ #
667
+ # Markup
668
+
669
+ protected function blockMarkup($Line)
670
+ {
671
+ if ($this->markupEscaped)
672
+ {
673
+ return;
674
+ }
675
+
676
+ if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
677
+ {
678
+ $element = strtolower($matches[1]);
679
+
680
+ if (in_array($element, $this->textLevelElements))
681
+ {
682
+ return;
683
+ }
684
+
685
+ $Block = array(
686
+ 'name' => $matches[1],
687
+ 'depth' => 0,
688
+ 'markup' => $Line['text'],
689
+ );
690
+
691
+ $length = strlen($matches[0]);
692
+
693
+ $remainder = substr($Line['text'], $length);
694
+
695
+ if (trim($remainder) === '')
696
+ {
697
+ if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
698
+ {
699
+ $Block['closed'] = true;
700
+
701
+ $Block['void'] = true;
702
+ }
703
+ }
704
+ else
705
+ {
706
+ if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
707
+ {
708
+ return;
709
+ }
710
+
711
+ if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
712
+ {
713
+ $Block['closed'] = true;
714
+ }
715
+ }
716
+
717
+ return $Block;
718
+ }
719
+ }
720
+
721
+ protected function blockMarkupContinue($Line, array $Block)
722
+ {
723
+ if (isset($Block['closed']))
724
+ {
725
+ return;
726
+ }
727
+
728
+ if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
729
+ {
730
+ $Block['depth'] ++;
731
+ }
732
+
733
+ if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
734
+ {
735
+ if ($Block['depth'] > 0)
736
+ {
737
+ $Block['depth'] --;
738
+ }
739
+ else
740
+ {
741
+ $Block['closed'] = true;
742
+ }
743
+ }
744
+
745
+ if (isset($Block['interrupted']))
746
+ {
747
+ $Block['markup'] .= "\n";
748
+
749
+ unset($Block['interrupted']);
750
+ }
751
+
752
+ $Block['markup'] .= "\n".$Line['body'];
753
+
754
+ return $Block;
755
+ }
756
+
757
+ #
758
+ # Reference
759
+
760
+ protected function blockReference($Line)
761
+ {
762
+ if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
763
+ {
764
+ $id = strtolower($matches[1]);
765
+
766
+ $Data = array(
767
+ 'url' => $matches[2],
768
+ 'title' => null,
769
+ );
770
+
771
+ if (isset($matches[3]))
772
+ {
773
+ $Data['title'] = $matches[3];
774
+ }
775
+
776
+ $this->DefinitionData['Reference'][$id] = $Data;
777
+
778
+ $Block = array(
779
+ 'hidden' => true,
780
+ );
781
+
782
+ return $Block;
783
+ }
784
+ }
785
+
786
+ #
787
+ # Table
788
+
789
+ protected function blockTable($Line, array $Block = null)
790
+ {
791
+ if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
792
+ {
793
+ return;
794
+ }
795
+
796
+ if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
797
+ {
798
+ $alignments = array();
799
+
800
+ $divider = $Line['text'];
801
+
802
+ $divider = trim($divider);
803
+ $divider = trim($divider, '|');
804
+
805
+ $dividerCells = explode('|', $divider);
806
+
807
+ foreach ($dividerCells as $dividerCell)
808
+ {
809
+ $dividerCell = trim($dividerCell);
810
+
811
+ if ($dividerCell === '')
812
+ {
813
+ continue;
814
+ }
815
+
816
+ $alignment = null;
817
+
818
+ if ($dividerCell[0] === ':')
819
+ {
820
+ $alignment = 'left';
821
+ }
822
+
823
+ if (substr($dividerCell, - 1) === ':')
824
+ {
825
+ $alignment = $alignment === 'left' ? 'center' : 'right';
826
+ }
827
+
828
+ $alignments []= $alignment;
829
+ }
830
+
831
+ # ~
832
+
833
+ $HeaderElements = array();
834
+
835
+ $header = $Block['element']['text'];
836
+
837
+ $header = trim($header);
838
+ $header = trim($header, '|');
839
+
840
+ $headerCells = explode('|', $header);
841
+
842
+ foreach ($headerCells as $index => $headerCell)
843
+ {
844
+ $headerCell = trim($headerCell);
845
+
846
+ $HeaderElement = array(
847
+ 'name' => 'th',
848
+ 'text' => $headerCell,
849
+ 'handler' => 'line',
850
+ );
851
+
852
+ if (isset($alignments[$index]))
853
+ {
854
+ $alignment = $alignments[$index];
855
+
856
+ $HeaderElement['attributes'] = array(
857
+ 'style' => 'text-align: '.$alignment.';',
858
+ );
859
+ }
860
+
861
+ $HeaderElements []= $HeaderElement;
862
+ }
863
+
864
+ # ~
865
+
866
+ $Block = array(
867
+ 'alignments' => $alignments,
868
+ 'identified' => true,
869
+ 'element' => array(
870
+ 'name' => 'table',
871
+ 'handler' => 'elements',
872
+ ),
873
+ );
874
+
875
+ $Block['element']['text'] []= array(
876
+ 'name' => 'thead',
877
+ 'handler' => 'elements',
878
+ );
879
+
880
+ $Block['element']['text'] []= array(
881
+ 'name' => 'tbody',
882
+ 'handler' => 'elements',
883
+ 'text' => array(),
884
+ );
885
+
886
+ $Block['element']['text'][0]['text'] []= array(
887
+ 'name' => 'tr',
888
+ 'handler' => 'elements',
889
+ 'text' => $HeaderElements,
890
+ );
891
+
892
+ return $Block;
893
+ }
894
+ }
895
+
896
+ protected function blockTableContinue($Line, array $Block)
897
+ {
898
+ if (isset($Block['interrupted']))
899
+ {
900
+ return;
901
+ }
902
+
903
+ if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
904
+ {
905
+ $Elements = array();
906
+
907
+ $row = $Line['text'];
908
+
909
+ $row = trim($row);
910
+ $row = trim($row, '|');
911
+
912
+ preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
913
+
914
+ foreach ($matches[0] as $index => $cell)
915
+ {
916
+ $cell = trim($cell);
917
+
918
+ $Element = array(
919
+ 'name' => 'td',
920
+ 'handler' => 'line',
921
+ 'text' => $cell,
922
+ );
923
+
924
+ if (isset($Block['alignments'][$index]))
925
+ {
926
+ $Element['attributes'] = array(
927
+ 'style' => 'text-align: '.$Block['alignments'][$index].';',
928
+ );
929
+ }
930
+
931
+ $Elements []= $Element;
932
+ }
933
+
934
+ $Element = array(
935
+ 'name' => 'tr',
936
+ 'handler' => 'elements',
937
+ 'text' => $Elements,
938
+ );
939
+
940
+ $Block['element']['text'][1]['text'] []= $Element;
941
+
942
+ return $Block;
943
+ }
944
+ }
945
+
946
+ #
947
+ # ~
948
+ #
949
+
950
+ protected function paragraph($Line)
951
+ {
952
+ $Block = array(
953
+ 'element' => array(
954
+ 'name' => 'p',
955
+ 'text' => $Line['text'],
956
+ 'handler' => 'line',
957
+ ),
958
+ );
959
+
960
+ return $Block;
961
+ }
962
+
963
+ #
964
+ # Inline Elements
965
+ #
966
+
967
+ protected $InlineTypes = array(
968
+ '"' => array('SpecialCharacter'),
969
+ '!' => array('Image'),
970
+ '&' => array('SpecialCharacter'),
971
+ '*' => array('Emphasis'),
972
+ ':' => array('Url'),
973
+ '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
974
+ '>' => array('SpecialCharacter'),
975
+ '[' => array('Link'),
976
+ '_' => array('Emphasis'),
977
+ '`' => array('Code'),
978
+ '~' => array('Strikethrough'),
979
+ '\\' => array('EscapeSequence'),
980
+ );
981
+
982
+ # ~
983
+
984
+ protected $inlineMarkerList = '!"*_&[:<>`~\\';
985
+
986
+ #
987
+ # ~
988
+ #
989
+
990
+ public function line($text)
991
+ {
992
+ $markup = '';
993
+
994
+ # $excerpt is based on the first occurrence of a marker
995
+
996
+ while ($excerpt = strpbrk($text, $this->inlineMarkerList))
997
+ {
998
+ $marker = $excerpt[0];
999
+
1000
+ $markerPosition = strpos($text, $marker);
1001
+
1002
+ $Excerpt = array('text' => $excerpt, 'context' => $text);
1003
+
1004
+ foreach ($this->InlineTypes[$marker] as $inlineType)
1005
+ {
1006
+ $Inline = $this->{'inline'.$inlineType}($Excerpt);
1007
+
1008
+ if ( ! isset($Inline))
1009
+ {
1010
+ continue;
1011
+ }
1012
+
1013
+ # makes sure that the inline belongs to "our" marker
1014
+
1015
+ if (isset($Inline['position']) and $Inline['position'] > $markerPosition)
1016
+ {
1017
+ continue;
1018
+ }
1019
+
1020
+ # sets a default inline position
1021
+
1022
+ if ( ! isset($Inline['position']))
1023
+ {
1024
+ $Inline['position'] = $markerPosition;
1025
+ }
1026
+
1027
+ # the text that comes before the inline
1028
+ $unmarkedText = substr($text, 0, $Inline['position']);
1029
+
1030
+ # compile the unmarked text
1031
+ $markup .= $this->unmarkedText($unmarkedText);
1032
+
1033
+ # compile the inline
1034
+ $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
1035
+
1036
+ # remove the examined text
1037
+ $text = substr($text, $Inline['position'] + $Inline['extent']);
1038
+
1039
+ continue 2;
1040
+ }
1041
+
1042
+ # the marker does not belong to an inline
1043
+
1044
+ $unmarkedText = substr($text, 0, $markerPosition + 1);
1045
+
1046
+ $markup .= $this->unmarkedText($unmarkedText);
1047
+
1048
+ $text = substr($text, $markerPosition + 1);
1049
+ }
1050
+
1051
+ $markup .= $this->unmarkedText($text);
1052
+
1053
+ return $markup;
1054
+ }
1055
+
1056
+ #
1057
+ # ~
1058
+ #
1059
+
1060
+ protected function inlineCode($Excerpt)
1061
+ {
1062
+ $marker = $Excerpt['text'][0];
1063
+
1064
+ if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
1065
+ {
1066
+ $text = $matches[2];
1067
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
1068
+ $text = preg_replace("/[ ]*\n/", ' ', $text);
1069
+
1070
+ return array(
1071
+ 'extent' => strlen($matches[0]),
1072
+ 'element' => array(
1073
+ 'name' => 'code',
1074
+ 'text' => $text,
1075
+ ),
1076
+ );
1077
+ }
1078
+ }
1079
+
1080
+ protected function inlineEmailTag($Excerpt)
1081
+ {
1082
+ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
1083
+ {
1084
+ $url = $matches[1];
1085
+
1086
+ if ( ! isset($matches[2]))
1087
+ {
1088
+ $url = 'mailto:' . $url;
1089
+ }
1090
+
1091
+ return array(
1092
+ 'extent' => strlen($matches[0]),
1093
+ 'element' => array(
1094
+ 'name' => 'a',
1095
+ 'text' => $matches[1],
1096
+ 'attributes' => array(
1097
+ 'href' => $url,
1098
+ ),
1099
+ ),
1100
+ );
1101
+ }
1102
+ }
1103
+
1104
+ protected function inlineEmphasis($Excerpt)
1105
+ {
1106
+ if ( ! isset($Excerpt['text'][1]))
1107
+ {
1108
+ return;
1109
+ }
1110
+
1111
+ $marker = $Excerpt['text'][0];
1112
+
1113
+ if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
1114
+ {
1115
+ $emphasis = 'strong';
1116
+ }
1117
+ elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
1118
+ {
1119
+ $emphasis = 'em';
1120
+ }
1121
+ else
1122
+ {
1123
+ return;
1124
+ }
1125
+
1126
+ return array(
1127
+ 'extent' => strlen($matches[0]),
1128
+ 'element' => array(
1129
+ 'name' => $emphasis,
1130
+ 'handler' => 'line',
1131
+ 'text' => $matches[1],
1132
+ ),
1133
+ );
1134
+ }
1135
+
1136
+ protected function inlineEscapeSequence($Excerpt)
1137
+ {
1138
+ if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
1139
+ {
1140
+ return array(
1141
+ 'markup' => $Excerpt['text'][1],
1142
+ 'extent' => 2,
1143
+ );
1144
+ }
1145
+ }
1146
+
1147
+ protected function inlineImage($Excerpt)
1148
+ {
1149
+ if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
1150
+ {
1151
+ return;
1152
+ }
1153
+
1154
+ $Excerpt['text']= substr($Excerpt['text'], 1);
1155
+
1156
+ $Link = $this->inlineLink($Excerpt);
1157
+
1158
+ if ($Link === null)
1159
+ {
1160
+ return;
1161
+ }
1162
+
1163
+ $Inline = array(
1164
+ 'extent' => $Link['extent'] + 1,
1165
+ 'element' => array(
1166
+ 'name' => 'img',
1167
+ 'attributes' => array(
1168
+ 'src' => $Link['element']['attributes']['href'],
1169
+ 'alt' => $Link['element']['text'],
1170
+ ),
1171
+ ),
1172
+ );
1173
+
1174
+ $Inline['element']['attributes'] += $Link['element']['attributes'];
1175
+
1176
+ unset($Inline['element']['attributes']['href']);
1177
+
1178
+ return $Inline;
1179
+ }
1180
+
1181
+ protected function inlineLink($Excerpt)
1182
+ {
1183
+ $Element = array(
1184
+ 'name' => 'a',
1185
+ 'handler' => 'line',
1186
+ 'text' => null,
1187
+ 'attributes' => array(
1188
+ 'href' => null,
1189
+ 'title' => null,
1190
+ ),
1191
+ );
1192
+
1193
+ $extent = 0;
1194
+
1195
+ $remainder = $Excerpt['text'];
1196
+
1197
+ if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches))
1198
+ {
1199
+ $Element['text'] = $matches[1];
1200
+
1201
+ $extent += strlen($matches[0]);
1202
+
1203
+ $remainder = substr($remainder, $extent);
1204
+ }
1205
+ else
1206
+ {
1207
+ return;
1208
+ }
1209
+
1210
+ if (preg_match('/^[(]((?:[^ ()]|[(][^ )]+[)])+)(?:[ ]+("[^"]*"|\'[^\']*\'))?[)]/', $remainder, $matches))
1211
+ {
1212
+ $Element['attributes']['href'] = $matches[1];
1213
+
1214
+ if (isset($matches[2]))
1215
+ {
1216
+ $Element['attributes']['title'] = substr($matches[2], 1, - 1);
1217
+ }
1218
+
1219
+ $extent += strlen($matches[0]);
1220
+ }
1221
+ else
1222
+ {
1223
+ if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
1224
+ {
1225
+ $definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
1226
+ $definition = strtolower($definition);
1227
+
1228
+ $extent += strlen($matches[0]);
1229
+ }
1230
+ else
1231
+ {
1232
+ $definition = strtolower($Element['text']);
1233
+ }
1234
+
1235
+ if ( ! isset($this->DefinitionData['Reference'][$definition]))
1236
+ {
1237
+ return;
1238
+ }
1239
+
1240
+ $Definition = $this->DefinitionData['Reference'][$definition];
1241
+
1242
+ $Element['attributes']['href'] = $Definition['url'];
1243
+ $Element['attributes']['title'] = $Definition['title'];
1244
+ }
1245
+
1246
+ $Element['attributes']['href'] = str_replace(array('&', '<'), array('&amp;', '&lt;'), $Element['attributes']['href']);
1247
+
1248
+ return array(
1249
+ 'extent' => $extent,
1250
+ 'element' => $Element,
1251
+ );
1252
+ }
1253
+
1254
+ protected function inlineMarkup($Excerpt)
1255
+ {
1256
+ if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
1257
+ {
1258
+ return;
1259
+ }
1260
+
1261
+ if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
1262
+ {
1263
+ return array(
1264
+ 'markup' => $matches[0],
1265
+ 'extent' => strlen($matches[0]),
1266
+ );
1267
+ }
1268
+
1269
+ if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches))
1270
+ {
1271
+ return array(
1272
+ 'markup' => $matches[0],
1273
+ 'extent' => strlen($matches[0]),
1274
+ );
1275
+ }
1276
+
1277
+ if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
1278
+ {
1279
+ return array(
1280
+ 'markup' => $matches[0],
1281
+ 'extent' => strlen($matches[0]),
1282
+ );
1283
+ }
1284
+ }
1285
+
1286
+ protected function inlineSpecialCharacter($Excerpt)
1287
+ {
1288
+ if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text']))
1289
+ {
1290
+ return array(
1291
+ 'markup' => '&amp;',
1292
+ 'extent' => 1,
1293
+ );
1294
+ }
1295
+
1296
+ $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
1297
+
1298
+ if (isset($SpecialCharacter[$Excerpt['text'][0]]))
1299
+ {
1300
+ return array(
1301
+ 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
1302
+ 'extent' => 1,
1303
+ );
1304
+ }
1305
+ }
1306
+
1307
+ protected function inlineStrikethrough($Excerpt)
1308
+ {
1309
+ if ( ! isset($Excerpt['text'][1]))
1310
+ {
1311
+ return;
1312
+ }
1313
+
1314
+ if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
1315
+ {
1316
+ return array(
1317
+ 'extent' => strlen($matches[0]),
1318
+ 'element' => array(
1319
+ 'name' => 'del',
1320
+ 'text' => $matches[1],
1321
+ 'handler' => 'line',
1322
+ ),
1323
+ );
1324
+ }
1325
+ }
1326
+
1327
+ protected function inlineUrl($Excerpt)
1328
+ {
1329
+ if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
1330
+ {
1331
+ return;
1332
+ }
1333
+
1334
+ if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
1335
+ {
1336
+ $Inline = array(
1337
+ 'extent' => strlen($matches[0][0]),
1338
+ 'position' => $matches[0][1],
1339
+ 'element' => array(
1340
+ 'name' => 'a',
1341
+ 'text' => $matches[0][0],
1342
+ 'attributes' => array(
1343
+ 'href' => $matches[0][0],
1344
+ ),
1345
+ ),
1346
+ );
1347
+
1348
+ return $Inline;
1349
+ }
1350
+ }
1351
+
1352
+ protected function inlineUrlTag($Excerpt)
1353
+ {
1354
+ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches))
1355
+ {
1356
+ $url = str_replace(array('&', '<'), array('&amp;', '&lt;'), $matches[1]);
1357
+
1358
+ return array(
1359
+ 'extent' => strlen($matches[0]),
1360
+ 'element' => array(
1361
+ 'name' => 'a',
1362
+ 'text' => $url,
1363
+ 'attributes' => array(
1364
+ 'href' => $url,
1365
+ ),
1366
+ ),
1367
+ );
1368
+ }
1369
+ }
1370
+
1371
+ # ~
1372
+
1373
+ protected function unmarkedText($text)
1374
+ {
1375
+ if ($this->breaksEnabled)
1376
+ {
1377
+ $text = preg_replace('/[ ]*\n/', "<br />\n", $text);
1378
+ }
1379
+ else
1380
+ {
1381
+ $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "<br />\n", $text);
1382
+ $text = str_replace(" \n", "\n", $text);
1383
+ }
1384
+
1385
+ return $text;
1386
+ }
1387
+
1388
+ #
1389
+ # Handlers
1390
+ #
1391
+
1392
+ protected function element(array $Element)
1393
+ {
1394
+ $markup = '<'.$Element['name'];
1395
+
1396
+ if (isset($Element['attributes']))
1397
+ {
1398
+ foreach ($Element['attributes'] as $name => $value)
1399
+ {
1400
+ if ($value === null)
1401
+ {
1402
+ continue;
1403
+ }
1404
+
1405
+ $markup .= ' '.$name.'="'.$value.'"';
1406
+ }
1407
+ }
1408
+
1409
+ if (isset($Element['text']))
1410
+ {
1411
+ $markup .= '>';
1412
+
1413
+ if (isset($Element['handler']))
1414
+ {
1415
+ $markup .= $this->{$Element['handler']}($Element['text']);
1416
+ }
1417
+ else
1418
+ {
1419
+ $markup .= $Element['text'];
1420
+ }
1421
+
1422
+ $markup .= '</'.$Element['name'].'>';
1423
+ }
1424
+ else
1425
+ {
1426
+ $markup .= ' />';
1427
+ }
1428
+
1429
+ return $markup;
1430
+ }
1431
+
1432
+ protected function elements(array $Elements)
1433
+ {
1434
+ $markup = '';
1435
+
1436
+ foreach ($Elements as $Element)
1437
+ {
1438
+ $markup .= "\n" . $this->element($Element);
1439
+ }
1440
+
1441
+ $markup .= "\n";
1442
+
1443
+ return $markup;
1444
+ }
1445
+
1446
+ # ~
1447
+
1448
+ protected function li($lines)
1449
+ {
1450
+ $markup = $this->lines($lines);
1451
+
1452
+ $trimmedMarkup = trim($markup);
1453
+
1454
+ if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '<p>')
1455
+ {
1456
+ $markup = $trimmedMarkup;
1457
+ $markup = substr($markup, 3);
1458
+
1459
+ $position = strpos($markup, "</p>");
1460
+
1461
+ $markup = substr_replace($markup, '', $position, 4);
1462
+ }
1463
+
1464
+ return $markup;
1465
+ }
1466
+
1467
+ #
1468
+ # Deprecated Methods
1469
+ #
1470
+
1471
+ function parse($text)
1472
+ {
1473
+ $markup = $this->text($text);
1474
+
1475
+ return $markup;
1476
+ }
1477
+
1478
+ #
1479
+ # Static Methods
1480
+ #
1481
+
1482
+ static function instance($name = 'default')
1483
+ {
1484
+ if (isset(self::$instances[$name]))
1485
+ {
1486
+ return self::$instances[$name];
1487
+ }
1488
+
1489
+ $instance = new static();
1490
+
1491
+ self::$instances[$name] = $instance;
1492
+
1493
+ return $instance;
1494
+ }
1495
+
1496
+ private static $instances = array();
1497
+
1498
+ #
1499
+ # Fields
1500
+ #
1501
+
1502
+ protected $DefinitionData;
1503
+
1504
+ #
1505
+ # Read-Only
1506
+
1507
+ protected $specialCharacters = array(
1508
+ '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|',
1509
+ );
1510
+
1511
+ protected $StrongRegex = array(
1512
+ '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s',
1513
+ '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us',
1514
+ );
1515
+
1516
+ protected $EmRegex = array(
1517
+ '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
1518
+ '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
1519
+ );
1520
+
1521
+ protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?';
1522
+
1523
+ protected $voidElements = array(
1524
+ 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source',
1525
+ );
1526
+
1527
+ protected $textLevelElements = array(
1528
+ 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',
1529
+ 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',
1530
+ 'i', 'rp', 'del', 'code', 'strike', 'marquee',
1531
+ 'q', 'rt', 'ins', 'font', 'strong',
1532
+ 's', 'tt', 'sub', 'mark',
1533
+ 'u', 'xm', 'sup', 'nobr',
1534
+ 'var', 'ruby',
1535
+ 'wbr', 'span',
1536
+ 'time',
1537
+ );
1538
+ }
plugin-update-checker/vendor/ParsedownLegacy.php ADDED
@@ -0,0 +1,1535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ #
4
+ #
5
+ # Parsedown
6
+ # http://parsedown.org
7
+ #
8
+ # (c) Emanuil Rusev
9
+ # http://erusev.com
10
+ #
11
+ # For the full license information, view the LICENSE file that was distributed
12
+ # with this source code.
13
+ #
14
+ #
15
+
16
+ class Parsedown
17
+ {
18
+ # ~
19
+
20
+ const version = '1.5.0';
21
+
22
+ # ~
23
+
24
+ function text($text)
25
+ {
26
+ # make sure no definitions are set
27
+ $this->DefinitionData = array();
28
+
29
+ # standardize line breaks
30
+ $text = str_replace(array("\r\n", "\r"), "\n", $text);
31
+
32
+ # remove surrounding line breaks
33
+ $text = trim($text, "\n");
34
+
35
+ # split text into lines
36
+ $lines = explode("\n", $text);
37
+
38
+ # iterate through lines to identify blocks
39
+ $markup = $this->lines($lines);
40
+
41
+ # trim line breaks
42
+ $markup = trim($markup, "\n");
43
+
44
+ return $markup;
45
+ }
46
+
47
+ #
48
+ # Setters
49
+ #
50
+
51
+ function setBreaksEnabled($breaksEnabled)
52
+ {
53
+ $this->breaksEnabled = $breaksEnabled;
54
+
55
+ return $this;
56
+ }
57
+
58
+ protected $breaksEnabled;
59
+
60
+ function setMarkupEscaped($markupEscaped)
61
+ {
62
+ $this->markupEscaped = $markupEscaped;
63
+
64
+ return $this;
65
+ }
66
+
67
+ protected $markupEscaped;
68
+
69
+ function setUrlsLinked($urlsLinked)
70
+ {
71
+ $this->urlsLinked = $urlsLinked;
72
+
73
+ return $this;
74
+ }
75
+
76
+ protected $urlsLinked = true;
77
+
78
+ #
79
+ # Lines
80
+ #
81
+
82
+ protected $BlockTypes = array(
83
+ '#' => array('Header'),
84
+ '*' => array('Rule', 'List'),
85
+ '+' => array('List'),
86
+ '-' => array('SetextHeader', 'Table', 'Rule', 'List'),
87
+ '0' => array('List'),
88
+ '1' => array('List'),
89
+ '2' => array('List'),
90
+ '3' => array('List'),
91
+ '4' => array('List'),
92
+ '5' => array('List'),
93
+ '6' => array('List'),
94
+ '7' => array('List'),
95
+ '8' => array('List'),
96
+ '9' => array('List'),
97
+ ':' => array('Table'),
98
+ '<' => array('Comment', 'Markup'),
99
+ '=' => array('SetextHeader'),
100
+ '>' => array('Quote'),
101
+ '[' => array('Reference'),
102
+ '_' => array('Rule'),
103
+ '`' => array('FencedCode'),
104
+ '|' => array('Table'),
105
+ '~' => array('FencedCode'),
106
+ );
107
+
108
+ # ~
109
+
110
+ protected $DefinitionTypes = array(
111
+ '[' => array('Reference'),
112
+ );
113
+
114
+ # ~
115
+
116
+ protected $unmarkedBlockTypes = array(
117
+ 'Code',
118
+ );
119
+
120
+ #
121
+ # Blocks
122
+ #
123
+
124
+ private function lines(array $lines)
125
+ {
126
+ $CurrentBlock = null;
127
+
128
+ foreach ($lines as $line)
129
+ {
130
+ if (chop($line) === '')
131
+ {
132
+ if (isset($CurrentBlock))
133
+ {
134
+ $CurrentBlock['interrupted'] = true;
135
+ }
136
+
137
+ continue;
138
+ }
139
+
140
+ if (strpos($line, "\t") !== false)
141
+ {
142
+ $parts = explode("\t", $line);
143
+
144
+ $line = $parts[0];
145
+
146
+ unset($parts[0]);
147
+
148
+ foreach ($parts as $part)
149
+ {
150
+ $shortage = 4 - mb_strlen($line, 'utf-8') % 4;
151
+
152
+ $line .= str_repeat(' ', $shortage);
153
+ $line .= $part;
154
+ }
155
+ }
156
+
157
+ $indent = 0;
158
+
159
+ while (isset($line[$indent]) and $line[$indent] === ' ')
160
+ {
161
+ $indent ++;
162
+ }
163
+
164
+ $text = $indent > 0 ? substr($line, $indent) : $line;
165
+
166
+ # ~
167
+
168
+ $Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
169
+
170
+ # ~
171
+
172
+ if (isset($CurrentBlock['incomplete']))
173
+ {
174
+ $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
175
+
176
+ if (isset($Block))
177
+ {
178
+ $CurrentBlock = $Block;
179
+
180
+ continue;
181
+ }
182
+ else
183
+ {
184
+ if (method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
185
+ {
186
+ $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
187
+ }
188
+
189
+ unset($CurrentBlock['incomplete']);
190
+ }
191
+ }
192
+
193
+ # ~
194
+
195
+ $marker = $text[0];
196
+
197
+ # ~
198
+
199
+ $blockTypes = $this->unmarkedBlockTypes;
200
+
201
+ if (isset($this->BlockTypes[$marker]))
202
+ {
203
+ foreach ($this->BlockTypes[$marker] as $blockType)
204
+ {
205
+ $blockTypes []= $blockType;
206
+ }
207
+ }
208
+
209
+ #
210
+ # ~
211
+
212
+ foreach ($blockTypes as $blockType)
213
+ {
214
+ $Block = $this->{'block'.$blockType}($Line, $CurrentBlock);
215
+
216
+ if (isset($Block))
217
+ {
218
+ $Block['type'] = $blockType;
219
+
220
+ if ( ! isset($Block['identified']))
221
+ {
222
+ $Blocks []= $CurrentBlock;
223
+
224
+ $Block['identified'] = true;
225
+ }
226
+
227
+ if (method_exists($this, 'block'.$blockType.'Continue'))
228
+ {
229
+ $Block['incomplete'] = true;
230
+ }
231
+
232
+ $CurrentBlock = $Block;
233
+
234
+ continue 2;
235
+ }
236
+ }
237
+
238
+ # ~
239
+
240
+ if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted']))
241
+ {
242
+ $CurrentBlock['element']['text'] .= "\n".$text;
243
+ }
244
+ else
245
+ {
246
+ $Blocks []= $CurrentBlock;
247
+
248
+ $CurrentBlock = $this->paragraph($Line);
249
+
250
+ $CurrentBlock['identified'] = true;
251
+ }
252
+ }
253
+
254
+ # ~
255
+
256
+ if (isset($CurrentBlock['incomplete']) and method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
257
+ {
258
+ $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
259
+ }
260
+
261
+ # ~
262
+
263
+ $Blocks []= $CurrentBlock;
264
+
265
+ unset($Blocks[0]);
266
+
267
+ # ~
268
+
269
+ $markup = '';
270
+
271
+ foreach ($Blocks as $Block)
272
+ {
273
+ if (isset($Block['hidden']))
274
+ {
275
+ continue;
276
+ }
277
+
278
+ $markup .= "\n";
279
+ $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']);
280
+ }
281
+
282
+ $markup .= "\n";
283
+
284
+ # ~
285
+
286
+ return $markup;
287
+ }
288
+
289
+ #
290
+ # Code
291
+
292
+ protected function blockCode($Line, $Block = null)
293
+ {
294
+ if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted']))
295
+ {
296
+ return;
297
+ }
298
+
299
+ if ($Line['indent'] >= 4)
300
+ {
301
+ $text = substr($Line['body'], 4);
302
+
303
+ $Block = array(
304
+ 'element' => array(
305
+ 'name' => 'pre',
306
+ 'handler' => 'element',
307
+ 'text' => array(
308
+ 'name' => 'code',
309
+ 'text' => $text,
310
+ ),
311
+ ),
312
+ );
313
+
314
+ return $Block;
315
+ }
316
+ }
317
+
318
+ protected function blockCodeContinue($Line, $Block)
319
+ {
320
+ if ($Line['indent'] >= 4)
321
+ {
322
+ if (isset($Block['interrupted']))
323
+ {
324
+ $Block['element']['text']['text'] .= "\n";
325
+
326
+ unset($Block['interrupted']);
327
+ }
328
+
329
+ $Block['element']['text']['text'] .= "\n";
330
+
331
+ $text = substr($Line['body'], 4);
332
+
333
+ $Block['element']['text']['text'] .= $text;
334
+
335
+ return $Block;
336
+ }
337
+ }
338
+
339
+ protected function blockCodeComplete($Block)
340
+ {
341
+ $text = $Block['element']['text']['text'];
342
+
343
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
344
+
345
+ $Block['element']['text']['text'] = $text;
346
+
347
+ return $Block;
348
+ }
349
+
350
+ #
351
+ # Comment
352
+
353
+ protected function blockComment($Line)
354
+ {
355
+ if ($this->markupEscaped)
356
+ {
357
+ return;
358
+ }
359
+
360
+ if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
361
+ {
362
+ $Block = array(
363
+ 'markup' => $Line['body'],
364
+ );
365
+
366
+ if (preg_match('/-->$/', $Line['text']))
367
+ {
368
+ $Block['closed'] = true;
369
+ }
370
+
371
+ return $Block;
372
+ }
373
+ }
374
+
375
+ protected function blockCommentContinue($Line, array $Block)
376
+ {
377
+ if (isset($Block['closed']))
378
+ {
379
+ return;
380
+ }
381
+
382
+ $Block['markup'] .= "\n" . $Line['body'];
383
+
384
+ if (preg_match('/-->$/', $Line['text']))
385
+ {
386
+ $Block['closed'] = true;
387
+ }
388
+
389
+ return $Block;
390
+ }
391
+
392
+ #
393
+ # Fenced Code
394
+
395
+ protected function blockFencedCode($Line)
396
+ {
397
+ if (preg_match('/^(['.$Line['text'][0].']{3,})[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
398
+ {
399
+ $Element = array(
400
+ 'name' => 'code',
401
+ 'text' => '',
402
+ );
403
+
404
+ if (isset($matches[2]))
405
+ {
406
+ $class = 'language-'.$matches[2];
407
+
408
+ $Element['attributes'] = array(
409
+ 'class' => $class,
410
+ );
411
+ }
412
+
413
+ $Block = array(
414
+ 'char' => $Line['text'][0],
415
+ 'element' => array(
416
+ 'name' => 'pre',
417
+ 'handler' => 'element',
418
+ 'text' => $Element,
419
+ ),
420
+ );
421
+
422
+ return $Block;
423
+ }
424
+ }
425
+
426
+ protected function blockFencedCodeContinue($Line, $Block)
427
+ {
428
+ if (isset($Block['complete']))
429
+ {
430
+ return;
431
+ }
432
+
433
+ if (isset($Block['interrupted']))
434
+ {
435
+ $Block['element']['text']['text'] .= "\n";
436
+
437
+ unset($Block['interrupted']);
438
+ }
439
+
440
+ if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text']))
441
+ {
442
+ $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
443
+
444
+ $Block['complete'] = true;
445
+
446
+ return $Block;
447
+ }
448
+
449
+ $Block['element']['text']['text'] .= "\n".$Line['body'];;
450
+
451
+ return $Block;
452
+ }
453
+
454
+ protected function blockFencedCodeComplete($Block)
455
+ {
456
+ $text = $Block['element']['text']['text'];
457
+
458
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
459
+
460
+ $Block['element']['text']['text'] = $text;
461
+
462
+ return $Block;
463
+ }
464
+
465
+ #
466
+ # Header
467
+
468
+ protected function blockHeader($Line)
469
+ {
470
+ if (isset($Line['text'][1]))
471
+ {
472
+ $level = 1;
473
+
474
+ while (isset($Line['text'][$level]) and $Line['text'][$level] === '#')
475
+ {
476
+ $level ++;
477
+ }
478
+
479
+ if ($level > 6)
480
+ {
481
+ return;
482
+ }
483
+
484
+ $text = trim($Line['text'], '# ');
485
+
486
+ $Block = array(
487
+ 'element' => array(
488
+ 'name' => 'h' . min(6, $level),
489
+ 'text' => $text,
490
+ 'handler' => 'line',
491
+ ),
492
+ );
493
+
494
+ return $Block;
495
+ }
496
+ }
497
+
498
+ #
499
+ # List
500
+
501
+ protected function blockList($Line)
502
+ {
503
+ list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]');
504
+
505
+ if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches))
506
+ {
507
+ $Block = array(
508
+ 'indent' => $Line['indent'],
509
+ 'pattern' => $pattern,
510
+ 'element' => array(
511
+ 'name' => $name,
512
+ 'handler' => 'elements',
513
+ ),
514
+ );
515
+
516
+ $Block['li'] = array(
517
+ 'name' => 'li',
518
+ 'handler' => 'li',
519
+ 'text' => array(
520
+ $matches[2],
521
+ ),
522
+ );
523
+
524
+ $Block['element']['text'] []= & $Block['li'];
525
+
526
+ return $Block;
527
+ }
528
+ }
529
+
530
+ protected function blockListContinue($Line, array $Block)
531
+ {
532
+ if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
533
+ {
534
+ if (isset($Block['interrupted']))
535
+ {
536
+ $Block['li']['text'] []= '';
537
+
538
+ unset($Block['interrupted']);
539
+ }
540
+
541
+ unset($Block['li']);
542
+
543
+ $text = isset($matches[1]) ? $matches[1] : '';
544
+
545
+ $Block['li'] = array(
546
+ 'name' => 'li',
547
+ 'handler' => 'li',
548
+ 'text' => array(
549
+ $text,
550
+ ),
551
+ );
552
+
553
+ $Block['element']['text'] []= & $Block['li'];
554
+
555
+ return $Block;
556
+ }
557
+
558
+ if ($Line['text'][0] === '[' and $this->blockReference($Line))
559
+ {
560
+ return $Block;
561
+ }
562
+
563
+ if ( ! isset($Block['interrupted']))
564
+ {
565
+ $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
566
+
567
+ $Block['li']['text'] []= $text;
568
+
569
+ return $Block;
570
+ }
571
+
572
+ if ($Line['indent'] > 0)
573
+ {
574
+ $Block['li']['text'] []= '';
575
+
576
+ $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
577
+
578
+ $Block['li']['text'] []= $text;
579
+
580
+ unset($Block['interrupted']);
581
+
582
+ return $Block;
583
+ }
584
+ }
585
+
586
+ #
587
+ # Quote
588
+
589
+ protected function blockQuote($Line)
590
+ {
591
+ if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
592
+ {
593
+ $Block = array(
594
+ 'element' => array(
595
+ 'name' => 'blockquote',
596
+ 'handler' => 'lines',
597
+ 'text' => (array) $matches[1],
598
+ ),
599
+ );
600
+
601
+ return $Block;
602
+ }
603
+ }
604
+
605
+ protected function blockQuoteContinue($Line, array $Block)
606
+ {
607
+ if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
608
+ {
609
+ if (isset($Block['interrupted']))
610
+ {
611
+ $Block['element']['text'] []= '';
612
+
613
+ unset($Block['interrupted']);
614
+ }
615
+
616
+ $Block['element']['text'] []= $matches[1];
617
+
618
+ return $Block;
619
+ }
620
+
621
+ if ( ! isset($Block['interrupted']))
622
+ {
623
+ $Block['element']['text'] []= $Line['text'];
624
+
625
+ return $Block;
626
+ }
627
+ }
628
+
629
+ #
630
+ # Rule
631
+
632
+ protected function blockRule($Line)
633
+ {
634
+ if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
635
+ {
636
+ $Block = array(
637
+ 'element' => array(
638
+ 'name' => 'hr'
639
+ ),
640
+ );
641
+
642
+ return $Block;
643
+ }
644
+ }
645
+
646
+ #
647
+ # Setext
648
+
649
+ protected function blockSetextHeader($Line, array $Block = null)
650
+ {
651
+ if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
652
+ {
653
+ return;
654
+ }
655
+
656
+ if (chop($Line['text'], $Line['text'][0]) === '')
657
+ {
658
+ $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
659
+
660
+ return $Block;
661
+ }
662
+ }
663
+
664
+ #
665
+ # Markup
666
+
667
+ protected function blockMarkup($Line)
668
+ {
669
+ if ($this->markupEscaped)
670
+ {
671
+ return;
672
+ }
673
+
674
+ if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
675
+ {
676
+ if (in_array($matches[1], $this->textLevelElements))
677
+ {
678
+ return;
679
+ }
680
+
681
+ $Block = array(
682
+ 'name' => $matches[1],
683
+ 'depth' => 0,
684
+ 'markup' => $Line['text'],
685
+ );
686
+
687
+ $length = strlen($matches[0]);
688
+
689
+ $remainder = substr($Line['text'], $length);
690
+
691
+ if (trim($remainder) === '')
692
+ {
693
+ if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
694
+ {
695
+ $Block['closed'] = true;
696
+
697
+ $Block['void'] = true;
698
+ }
699
+ }
700
+ else
701
+ {
702
+ if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
703
+ {
704
+ return;
705
+ }
706
+
707
+ if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
708
+ {
709
+ $Block['closed'] = true;
710
+ }
711
+ }
712
+
713
+ return $Block;
714
+ }
715
+ }
716
+
717
+ protected function blockMarkupContinue($Line, array $Block)
718
+ {
719
+ if (isset($Block['closed']))
720
+ {
721
+ return;
722
+ }
723
+
724
+ if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
725
+ {
726
+ $Block['depth'] ++;
727
+ }
728
+
729
+ if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
730
+ {
731
+ if ($Block['depth'] > 0)
732
+ {
733
+ $Block['depth'] --;
734
+ }
735
+ else
736
+ {
737
+ $Block['closed'] = true;
738
+ }
739
+
740
+ $Block['markup'] .= $matches[1];
741
+ }
742
+
743
+ if (isset($Block['interrupted']))
744
+ {
745
+ $Block['markup'] .= "\n";
746
+
747
+ unset($Block['interrupted']);
748
+ }
749
+
750
+ $Block['markup'] .= "\n".$Line['body'];
751
+
752
+ return $Block;
753
+ }
754
+
755
+ #
756
+ # Reference
757
+
758
+ protected function blockReference($Line)
759
+ {
760
+ if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
761
+ {
762
+ $id = strtolower($matches[1]);
763
+
764
+ $Data = array(
765
+ 'url' => $matches[2],
766
+ 'title' => null,
767
+ );
768
+
769
+ if (isset($matches[3]))
770
+ {
771
+ $Data['title'] = $matches[3];
772
+ }
773
+
774
+ $this->DefinitionData['Reference'][$id] = $Data;
775
+
776
+ $Block = array(
777
+ 'hidden' => true,
778
+ );
779
+
780
+ return $Block;
781
+ }
782
+ }
783
+
784
+ #
785
+ # Table
786
+
787
+ protected function blockTable($Line, array $Block = null)
788
+ {
789
+ if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
790
+ {
791
+ return;
792
+ }
793
+
794
+ if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
795
+ {
796
+ $alignments = array();
797
+
798
+ $divider = $Line['text'];
799
+
800
+ $divider = trim($divider);
801
+ $divider = trim($divider, '|');
802
+
803
+ $dividerCells = explode('|', $divider);
804
+
805
+ foreach ($dividerCells as $dividerCell)
806
+ {
807
+ $dividerCell = trim($dividerCell);
808
+
809
+ if ($dividerCell === '')
810
+ {
811
+ continue;
812
+ }
813
+
814
+ $alignment = null;
815
+
816
+ if ($dividerCell[0] === ':')
817
+ {
818
+ $alignment = 'left';
819
+ }
820
+
821
+ if (substr($dividerCell, - 1) === ':')
822
+ {
823
+ $alignment = $alignment === 'left' ? 'center' : 'right';
824
+ }
825
+
826
+ $alignments []= $alignment;
827
+ }
828
+
829
+ # ~
830
+
831
+ $HeaderElements = array();
832
+
833
+ $header = $Block['element']['text'];
834
+
835
+ $header = trim($header);
836
+ $header = trim($header, '|');
837
+
838
+ $headerCells = explode('|', $header);
839
+
840
+ foreach ($headerCells as $index => $headerCell)
841
+ {
842
+ $headerCell = trim($headerCell);
843
+
844
+ $HeaderElement = array(
845
+ 'name' => 'th',
846
+ 'text' => $headerCell,
847
+ 'handler' => 'line',
848
+ );
849
+
850
+ if (isset($alignments[$index]))
851
+ {
852
+ $alignment = $alignments[$index];
853
+
854
+ $HeaderElement['attributes'] = array(
855
+ 'style' => 'text-align: '.$alignment.';',
856
+ );
857
+ }
858
+
859
+ $HeaderElements []= $HeaderElement;
860
+ }
861
+
862
+ # ~
863
+
864
+ $Block = array(
865
+ 'alignments' => $alignments,
866
+ 'identified' => true,
867
+ 'element' => array(
868
+ 'name' => 'table',
869
+ 'handler' => 'elements',
870
+ ),
871
+ );
872
+
873
+ $Block['element']['text'] []= array(
874
+ 'name' => 'thead',
875
+ 'handler' => 'elements',
876
+ );
877
+
878
+ $Block['element']['text'] []= array(
879
+ 'name' => 'tbody',
880
+ 'handler' => 'elements',
881
+ 'text' => array(),
882
+ );
883
+
884
+ $Block['element']['text'][0]['text'] []= array(
885
+ 'name' => 'tr',
886
+ 'handler' => 'elements',
887
+ 'text' => $HeaderElements,
888
+ );
889
+
890
+ return $Block;
891
+ }
892
+ }
893
+
894
+ protected function blockTableContinue($Line, array $Block)
895
+ {
896
+ if (isset($Block['interrupted']))
897
+ {
898
+ return;
899
+ }
900
+
901
+ if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
902
+ {
903
+ $Elements = array();
904
+
905
+ $row = $Line['text'];
906
+
907
+ $row = trim($row);
908
+ $row = trim($row, '|');
909
+
910
+ preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
911
+
912
+ foreach ($matches[0] as $index => $cell)
913
+ {
914
+ $cell = trim($cell);
915
+
916
+ $Element = array(
917
+ 'name' => 'td',
918
+ 'handler' => 'line',
919
+ 'text' => $cell,
920
+ );
921
+
922
+ if (isset($Block['alignments'][$index]))
923
+ {
924
+ $Element['attributes'] = array(
925
+ 'style' => 'text-align: '.$Block['alignments'][$index].';',
926
+ );
927
+ }
928
+
929
+ $Elements []= $Element;
930
+ }
931
+
932
+ $Element = array(
933
+ 'name' => 'tr',
934
+ 'handler' => 'elements',
935
+ 'text' => $Elements,
936
+ );
937
+
938
+ $Block['element']['text'][1]['text'] []= $Element;
939
+
940
+ return $Block;
941
+ }
942
+ }
943
+
944
+ #
945
+ # ~
946
+ #
947
+
948
+ protected function paragraph($Line)
949
+ {
950
+ $Block = array(
951
+ 'element' => array(
952
+ 'name' => 'p',
953
+ 'text' => $Line['text'],
954
+ 'handler' => 'line',
955
+ ),
956
+ );
957
+
958
+ return $Block;
959
+ }
960
+
961
+ #
962
+ # Inline Elements
963
+ #
964
+
965
+ protected $InlineTypes = array(
966
+ '"' => array('SpecialCharacter'),
967
+ '!' => array('Image'),
968
+ '&' => array('SpecialCharacter'),
969
+ '*' => array('Emphasis'),
970
+ ':' => array('Url'),
971
+ '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
972
+ '>' => array('SpecialCharacter'),
973
+ '[' => array('Link'),
974
+ '_' => array('Emphasis'),
975
+ '`' => array('Code'),
976
+ '~' => array('Strikethrough'),
977
+ '\\' => array('EscapeSequence'),
978
+ );
979
+
980
+ # ~
981
+
982
+ protected $inlineMarkerList = '!"*_&[:<>`~\\';
983
+
984
+ #
985
+ # ~
986
+ #
987
+
988
+ public function line($text)
989
+ {
990
+ $markup = '';
991
+
992
+ $unexaminedText = $text;
993
+
994
+ $markerPosition = 0;
995
+
996
+ while ($excerpt = strpbrk($unexaminedText, $this->inlineMarkerList))
997
+ {
998
+ $marker = $excerpt[0];
999
+
1000
+ $markerPosition += strpos($unexaminedText, $marker);
1001
+
1002
+ $Excerpt = array('text' => $excerpt, 'context' => $text);
1003
+
1004
+ foreach ($this->InlineTypes[$marker] as $inlineType)
1005
+ {
1006
+ $Inline = $this->{'inline'.$inlineType}($Excerpt);
1007
+
1008
+ if ( ! isset($Inline))
1009
+ {
1010
+ continue;
1011
+ }
1012
+
1013
+ if (isset($Inline['position']) and $Inline['position'] > $markerPosition) # position is ahead of marker
1014
+ {
1015
+ continue;
1016
+ }
1017
+
1018
+ if ( ! isset($Inline['position']))
1019
+ {
1020
+ $Inline['position'] = $markerPosition;
1021
+ }
1022
+
1023
+ $unmarkedText = substr($text, 0, $Inline['position']);
1024
+
1025
+ $markup .= $this->unmarkedText($unmarkedText);
1026
+
1027
+ $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
1028
+
1029
+ $text = substr($text, $Inline['position'] + $Inline['extent']);
1030
+
1031
+ $unexaminedText = $text;
1032
+
1033
+ $markerPosition = 0;
1034
+
1035
+ continue 2;
1036
+ }
1037
+
1038
+ $unexaminedText = substr($excerpt, 1);
1039
+
1040
+ $markerPosition ++;
1041
+ }
1042
+
1043
+ $markup .= $this->unmarkedText($text);
1044
+
1045
+ return $markup;
1046
+ }
1047
+
1048
+ #
1049
+ # ~
1050
+ #
1051
+
1052
+ protected function inlineCode($Excerpt)
1053
+ {
1054
+ $marker = $Excerpt['text'][0];
1055
+
1056
+ if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
1057
+ {
1058
+ $text = $matches[2];
1059
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
1060
+ $text = preg_replace("/[ ]*\n/", ' ', $text);
1061
+
1062
+ return array(
1063
+ 'extent' => strlen($matches[0]),
1064
+ 'element' => array(
1065
+ 'name' => 'code',
1066
+ 'text' => $text,
1067
+ ),
1068
+ );
1069
+ }
1070
+ }
1071
+
1072
+ protected function inlineEmailTag($Excerpt)
1073
+ {
1074
+ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
1075
+ {
1076
+ $url = $matches[1];
1077
+
1078
+ if ( ! isset($matches[2]))
1079
+ {
1080
+ $url = 'mailto:' . $url;
1081
+ }
1082
+
1083
+ return array(
1084
+ 'extent' => strlen($matches[0]),
1085
+ 'element' => array(
1086
+ 'name' => 'a',
1087
+ 'text' => $matches[1],
1088
+ 'attributes' => array(
1089
+ 'href' => $url,
1090
+ ),
1091
+ ),
1092
+ );
1093
+ }
1094
+ }
1095
+
1096
+ protected function inlineEmphasis($Excerpt)
1097
+ {
1098
+ if ( ! isset($Excerpt['text'][1]))
1099
+ {
1100
+ return;
1101
+ }
1102
+
1103
+ $marker = $Excerpt['text'][0];
1104
+
1105
+ if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
1106
+ {
1107
+ $emphasis = 'strong';
1108
+ }
1109
+ elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
1110
+ {
1111
+ $emphasis = 'em';
1112
+ }
1113
+ else
1114
+ {
1115
+ return;
1116
+ }
1117
+
1118
+ return array(
1119
+ 'extent' => strlen($matches[0]),
1120
+ 'element' => array(
1121
+ 'name' => $emphasis,
1122
+ 'handler' => 'line',
1123
+ 'text' => $matches[1],
1124
+ ),
1125
+ );
1126
+ }
1127
+
1128
+ protected function inlineEscapeSequence($Excerpt)
1129
+ {
1130
+ if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
1131
+ {
1132
+ return array(
1133
+ 'markup' => $Excerpt['text'][1],
1134
+ 'extent' => 2,
1135
+ );
1136
+ }
1137
+ }
1138
+
1139
+ protected function inlineImage($Excerpt)
1140
+ {
1141
+ if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
1142
+ {
1143
+ return;
1144
+ }
1145
+
1146
+ $Excerpt['text']= substr($Excerpt['text'], 1);
1147
+
1148
+ $Link = $this->inlineLink($Excerpt);
1149
+
1150
+ if ($Link === null)
1151
+ {
1152
+ return;
1153
+ }
1154
+
1155
+ $Inline = array(
1156
+ 'extent' => $Link['extent'] + 1,
1157
+ 'element' => array(
1158
+ 'name' => 'img',
1159
+ 'attributes' => array(
1160
+ 'src' => $Link['element']['attributes']['href'],
1161
+ 'alt' => $Link['element']['text'],
1162
+ ),
1163
+ ),
1164
+ );
1165
+
1166
+ $Inline['element']['attributes'] += $Link['element']['attributes'];
1167
+
1168
+ unset($Inline['element']['attributes']['href']);
1169
+
1170
+ return $Inline;
1171
+ }
1172
+
1173
+ protected function inlineLink($Excerpt)
1174
+ {
1175
+ $Element = array(
1176
+ 'name' => 'a',
1177
+ 'handler' => 'line',
1178
+ 'text' => null,
1179
+ 'attributes' => array(
1180
+ 'href' => null,
1181
+ 'title' => null,
1182
+ ),
1183
+ );
1184
+
1185
+ $extent = 0;
1186
+
1187
+ $remainder = $Excerpt['text'];
1188
+
1189
+ if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches))
1190
+ {
1191
+ $Element['text'] = $matches[1];
1192
+
1193
+ $extent += strlen($matches[0]);
1194
+
1195
+ $remainder = substr($remainder, $extent);
1196
+ }
1197
+ else
1198
+ {
1199
+ return;
1200
+ }
1201
+
1202
+ if (preg_match('/^[(]((?:[^ (]|[(][^ )]+[)])+)(?:[ ]+("[^"]+"|\'[^\']+\'))?[)]/', $remainder, $matches))
1203
+ {
1204
+ $Element['attributes']['href'] = $matches[1];
1205
+
1206
+ if (isset($matches[2]))
1207
+ {
1208
+ $Element['attributes']['title'] = substr($matches[2], 1, - 1);
1209
+ }
1210
+
1211
+ $extent += strlen($matches[0]);
1212
+ }
1213
+ else
1214
+ {
1215
+ if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
1216
+ {
1217
+ $definition = $matches[1] ? $matches[1] : $Element['text'];
1218
+ $definition = strtolower($definition);
1219
+
1220
+ $extent += strlen($matches[0]);
1221
+ }
1222
+ else
1223
+ {
1224
+ $definition = strtolower($Element['text']);
1225
+ }
1226
+
1227
+ if ( ! isset($this->DefinitionData['Reference'][$definition]))
1228
+ {
1229
+ return;
1230
+ }
1231
+
1232
+ $Definition = $this->DefinitionData['Reference'][$definition];
1233
+
1234
+ $Element['attributes']['href'] = $Definition['url'];
1235
+ $Element['attributes']['title'] = $Definition['title'];
1236
+ }
1237
+
1238
+ $Element['attributes']['href'] = str_replace(array('&', '<'), array('&amp;', '&lt;'), $Element['attributes']['href']);
1239
+
1240
+ return array(
1241
+ 'extent' => $extent,
1242
+ 'element' => $Element,
1243
+ );
1244
+ }
1245
+
1246
+ protected function inlineMarkup($Excerpt)
1247
+ {
1248
+ if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
1249
+ {
1250
+ return;
1251
+ }
1252
+
1253
+ if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
1254
+ {
1255
+ return array(
1256
+ 'markup' => $matches[0],
1257
+ 'extent' => strlen($matches[0]),
1258
+ );
1259
+ }
1260
+
1261
+ if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches))
1262
+ {
1263
+ return array(
1264
+ 'markup' => $matches[0],
1265
+ 'extent' => strlen($matches[0]),
1266
+ );
1267
+ }
1268
+
1269
+ if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
1270
+ {
1271
+ return array(
1272
+ 'markup' => $matches[0],
1273
+ 'extent' => strlen($matches[0]),
1274
+ );
1275
+ }
1276
+ }
1277
+
1278
+ protected function inlineSpecialCharacter($Excerpt)
1279
+ {
1280
+ if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text']))
1281
+ {
1282
+ return array(
1283
+ 'markup' => '&amp;',
1284
+ 'extent' => 1,
1285
+ );
1286
+ }
1287
+
1288
+ $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
1289
+
1290
+ if (isset($SpecialCharacter[$Excerpt['text'][0]]))
1291
+ {
1292
+ return array(
1293
+ 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
1294
+ 'extent' => 1,
1295
+ );
1296
+ }
1297
+ }
1298
+
1299
+ protected function inlineStrikethrough($Excerpt)
1300
+ {
1301
+ if ( ! isset($Excerpt['text'][1]))
1302
+ {
1303
+ return;
1304
+ }
1305
+
1306
+ if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
1307
+ {
1308
+ return array(
1309
+ 'extent' => strlen($matches[0]),
1310
+ 'element' => array(
1311
+ 'name' => 'del',
1312
+ 'text' => $matches[1],
1313
+ 'handler' => 'line',
1314
+ ),
1315
+ );
1316
+ }
1317
+ }
1318
+
1319
+ protected function inlineUrl($Excerpt)
1320
+ {
1321
+ if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
1322
+ {
1323
+ return;
1324
+ }
1325
+
1326
+ if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
1327
+ {
1328
+ $Inline = array(
1329
+ 'extent' => strlen($matches[0][0]),
1330
+ 'position' => $matches[0][1],
1331
+ 'element' => array(
1332
+ 'name' => 'a',
1333
+ 'text' => $matches[0][0],
1334
+ 'attributes' => array(
1335
+ 'href' => $matches[0][0],
1336
+ ),
1337
+ ),
1338
+ );
1339
+
1340
+ return $Inline;
1341
+ }
1342
+ }
1343
+
1344
+ protected function inlineUrlTag($Excerpt)
1345
+ {
1346
+ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches))
1347
+ {
1348
+ $url = str_replace(array('&', '<'), array('&amp;', '&lt;'), $matches[1]);
1349
+
1350
+ return array(
1351
+ 'extent' => strlen($matches[0]),
1352
+ 'element' => array(
1353
+ 'name' => 'a',
1354
+ 'text' => $url,
1355
+ 'attributes' => array(
1356
+ 'href' => $url,
1357
+ ),
1358
+ ),
1359
+ );
1360
+ }
1361
+ }
1362
+
1363
+ #
1364
+ # ~
1365
+
1366
+ protected $unmarkedInlineTypes = array("\n" => 'Break', '://' => 'Url');
1367
+
1368
+ # ~
1369
+
1370
+ protected function unmarkedText($text)
1371
+ {
1372
+ if ($this->breaksEnabled)
1373
+ {
1374
+ $text = preg_replace('/[ ]*\n/', "<br />\n", $text);
1375
+ }
1376
+ else
1377
+ {
1378
+ $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "<br />\n", $text);
1379
+ $text = str_replace(" \n", "\n", $text);
1380
+ }
1381
+
1382
+ return $text;
1383
+ }
1384
+
1385
+ #
1386
+ # Handlers
1387
+ #
1388
+
1389
+ protected function element(array $Element)
1390
+ {
1391
+ $markup = '<'.$Element['name'];
1392
+
1393
+ if (isset($Element['attributes']))
1394
+ {
1395
+ foreach ($Element['attributes'] as $name => $value)
1396
+ {
1397
+ if ($value === null)
1398
+ {
1399
+ continue;
1400
+ }
1401
+
1402
+ $markup .= ' '.$name.'="'.$value.'"';
1403
+ }
1404
+ }
1405
+
1406
+ if (isset($Element['text']))
1407
+ {
1408
+ $markup .= '>';
1409
+
1410
+ if (isset($Element['handler']))
1411
+ {
1412
+ $markup .= $this->$Element['handler']($Element['text']);
1413
+ }
1414
+ else
1415
+ {
1416
+ $markup .= $Element['text'];
1417
+ }
1418
+
1419
+ $markup .= '</'.$Element['name'].'>';
1420
+ }
1421
+ else
1422
+ {
1423
+ $markup .= ' />';
1424
+ }
1425
+
1426
+ return $markup;
1427
+ }
1428
+
1429
+ protected function elements(array $Elements)
1430
+ {
1431
+ $markup = '';
1432
+
1433
+ foreach ($Elements as $Element)
1434
+ {
1435
+ $markup .= "\n" . $this->element($Element);
1436
+ }
1437
+
1438
+ $markup .= "\n";
1439
+
1440
+ return $markup;
1441
+ }
1442
+
1443
+ # ~
1444
+
1445
+ protected function li($lines)
1446
+ {
1447
+ $markup = $this->lines($lines);
1448
+
1449
+ $trimmedMarkup = trim($markup);
1450
+
1451
+ if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '<p>')
1452
+ {
1453
+ $markup = $trimmedMarkup;
1454
+ $markup = substr($markup, 3);
1455
+
1456
+ $position = strpos($markup, "</p>");
1457
+
1458
+ $markup = substr_replace($markup, '', $position, 4);
1459
+ }
1460
+
1461
+ return $markup;
1462
+ }
1463
+
1464
+ #
1465
+ # Deprecated Methods
1466
+ #
1467
+
1468
+ function parse($text)
1469
+ {
1470
+ $markup = $this->text($text);
1471
+
1472
+ return $markup;
1473
+ }
1474
+
1475
+ #
1476
+ # Static Methods
1477
+ #
1478
+
1479
+ static function instance($name = 'default')
1480
+ {
1481
+ if (isset(self::$instances[$name]))
1482
+ {
1483
+ return self::$instances[$name];
1484
+ }
1485
+
1486
+ $instance = new self();
1487
+
1488
+ self::$instances[$name] = $instance;
1489
+
1490
+ return $instance;
1491
+ }
1492
+
1493
+ private static $instances = array();
1494
+
1495
+ #
1496
+ # Fields
1497
+ #
1498
+
1499
+ protected $DefinitionData;
1500
+
1501
+ #
1502
+ # Read-Only
1503
+
1504
+ protected $specialCharacters = array(
1505
+ '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|',
1506
+ );
1507
+
1508
+ protected $StrongRegex = array(
1509
+ '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s',
1510
+ '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us',
1511
+ );
1512
+
1513
+ protected $EmRegex = array(
1514
+ '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
1515
+ '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
1516
+ );
1517
+
1518
+ protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?';
1519
+
1520
+ protected $voidElements = array(
1521
+ 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source',
1522
+ );
1523
+
1524
+ protected $textLevelElements = array(
1525
+ 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',
1526
+ 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',
1527
+ 'i', 'rp', 'del', 'code', 'strike', 'marquee',
1528
+ 'q', 'rt', 'ins', 'font', 'strong',
1529
+ 's', 'tt', 'sub', 'mark',
1530
+ 'u', 'xm', 'sup', 'nobr',
1531
+ 'var', 'ruby',
1532
+ 'wbr', 'span',
1533
+ 'time',
1534
+ );
1535
+ }
plugin-update-checker/vendor/readme-parser.php ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * This is a slightly modified version of github.com/markjaquith/WordPress-Plugin-Readme-Parser
5
+ * It uses Parsedown instead of the "Markdown Extra" parser.
6
+ */
7
+
8
+ Class PucReadmeParser {
9
+
10
+ function __construct() {
11
+ // This space intentially blank
12
+ }
13
+
14
+ function parse_readme( $file ) {
15
+ $file_contents = @implode('', @file($file));
16
+ return $this->parse_readme_contents( $file_contents );
17
+ }
18
+
19
+ function parse_readme_contents( $file_contents ) {
20
+ $file_contents = str_replace(array("\r\n", "\r"), "\n", $file_contents);
21
+ $file_contents = trim($file_contents);
22
+ if ( 0 === strpos( $file_contents, "\xEF\xBB\xBF" ) )
23
+ $file_contents = substr( $file_contents, 3 );
24
+
25
+ // Markdown transformations
26
+ $file_contents = preg_replace( "|^###([^#]+)#*?\s*?\n|im", '=$1='."\n", $file_contents );
27
+ $file_contents = preg_replace( "|^##([^#]+)#*?\s*?\n|im", '==$1=='."\n", $file_contents );
28
+ $file_contents = preg_replace( "|^#([^#]+)#*?\s*?\n|im", '===$1==='."\n", $file_contents );
29
+
30
+ // === Plugin Name ===
31
+ // Must be the very first thing.
32
+ if ( !preg_match('|^===(.*)===|', $file_contents, $_name) )
33
+ return array(); // require a name
34
+ $name = trim($_name[1], '=');
35
+ $name = $this->sanitize_text( $name );
36
+
37
+ $file_contents = $this->chop_string( $file_contents, $_name[0] );
38
+
39
+
40
+ // Requires at least: 1.5
41
+ if ( preg_match('|Requires at least:(.*)|i', $file_contents, $_requires_at_least) )
42
+ $requires_at_least = $this->sanitize_text($_requires_at_least[1]);
43
+ else
44
+ $requires_at_least = NULL;
45
+
46
+
47
+ // Tested up to: 2.1
48
+ if ( preg_match('|Tested up to:(.*)|i', $file_contents, $_tested_up_to) )
49
+ $tested_up_to = $this->sanitize_text( $_tested_up_to[1] );
50
+ else
51
+ $tested_up_to = NULL;
52
+
53
+
54
+ // Stable tag: 10.4-ride-the-fire-eagle-danger-day
55
+ if ( preg_match('|Stable tag:(.*)|i', $file_contents, $_stable_tag) )
56
+ $stable_tag = $this->sanitize_text( $_stable_tag[1] );
57
+ else
58
+ $stable_tag = NULL; // we assume trunk, but don't set it here to tell the difference between specified trunk and default trunk
59
+
60
+
61
+ // Tags: some tag, another tag, we like tags
62
+ if ( preg_match('|Tags:(.*)|i', $file_contents, $_tags) ) {
63
+ $tags = preg_split('|,[\s]*?|', trim($_tags[1]));
64
+ foreach ( array_keys($tags) as $t )
65
+ $tags[$t] = $this->sanitize_text( $tags[$t] );
66
+ } else {
67
+ $tags = array();
68
+ }
69
+
70
+
71
+ // Contributors: markjaquith, mdawaffe, zefrank
72
+ $contributors = array();
73
+ if ( preg_match('|Contributors:(.*)|i', $file_contents, $_contributors) ) {
74
+ $temp_contributors = preg_split('|,[\s]*|', trim($_contributors[1]));
75
+ foreach ( array_keys($temp_contributors) as $c ) {
76
+ $tmp_sanitized = $this->user_sanitize( $temp_contributors[$c] );
77
+ if ( strlen(trim($tmp_sanitized)) > 0 )
78
+ $contributors[$c] = $tmp_sanitized;
79
+ unset($tmp_sanitized);
80
+ }
81
+ }
82
+
83
+
84
+ // Donate Link: URL
85
+ if ( preg_match('|Donate link:(.*)|i', $file_contents, $_donate_link) )
86
+ $donate_link = esc_url( $_donate_link[1] );
87
+ else
88
+ $donate_link = NULL;
89
+
90
+
91
+ // togs, conts, etc are optional and order shouldn't matter. So we chop them only after we've grabbed their values.
92
+ foreach ( array('tags', 'contributors', 'requires_at_least', 'tested_up_to', 'stable_tag', 'donate_link') as $chop ) {
93
+ if ( $$chop ) {
94
+ $_chop = '_' . $chop;
95
+ $file_contents = $this->chop_string( $file_contents, ${$_chop}[0] );
96
+ }
97
+ }
98
+
99
+ $file_contents = trim($file_contents);
100
+
101
+
102
+ // short-description fu
103
+ if ( !preg_match('/(^(.*?))^[\s]*=+?[\s]*.+?[\s]*=+?/ms', $file_contents, $_short_description) )
104
+ $_short_description = array( 1 => &$file_contents, 2 => &$file_contents );
105
+ $short_desc_filtered = $this->sanitize_text( $_short_description[2] );
106
+ $short_desc_length = strlen($short_desc_filtered);
107
+ $short_description = substr($short_desc_filtered, 0, 150);
108
+ if ( $short_desc_length > strlen($short_description) )
109
+ $truncated = true;
110
+ else
111
+ $truncated = false;
112
+ if ( $_short_description[1] )
113
+ $file_contents = $this->chop_string( $file_contents, $_short_description[1] ); // yes, the [1] is intentional
114
+
115
+ // == Section ==
116
+ // Break into sections
117
+ // $_sections[0] will be the title of the first section, $_sections[1] will be the content of the first section
118
+ // the array alternates from there: title2, content2, title3, content3... and so forth
119
+ $_sections = preg_split('/^[\s]*==[\s]*(.+?)[\s]*==/m', $file_contents, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
120
+
121
+ $sections = array();
122
+ for ( $i=1; $i <= count($_sections); $i +=2 ) {
123
+ $_sections[$i] = preg_replace('/(^[\s]*)=[\s]+(.+?)[\s]+=/m', '$1<h4>$2</h4>', $_sections[$i]);
124
+ $_sections[$i] = $this->filter_text( $_sections[$i], true );
125
+ $title = $this->sanitize_text( $_sections[$i-1] );
126
+ $sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $_sections[$i]);
127
+ }
128
+
129
+
130
+ // Special sections
131
+ // This is where we nab our special sections, so we can enforce their order and treat them differently, if needed
132
+ // upgrade_notice is not a section, but parse it like it is for now
133
+ $final_sections = array();
134
+ foreach ( array('description', 'installation', 'frequently_asked_questions', 'screenshots', 'changelog', 'change_log', 'upgrade_notice') as $special_section ) {
135
+ if ( isset($sections[$special_section]) ) {
136
+ $final_sections[$special_section] = $sections[$special_section]['content'];
137
+ unset($sections[$special_section]);
138
+ }
139
+ }
140
+ if ( isset($final_sections['change_log']) && empty($final_sections['changelog']) )
141
+ $final_sections['changelog'] = $final_sections['change_log'];
142
+
143
+
144
+ $final_screenshots = array();
145
+ if ( isset($final_sections['screenshots']) ) {
146
+ preg_match_all('|<li>(.*?)</li>|s', $final_sections['screenshots'], $screenshots, PREG_SET_ORDER);
147
+ if ( $screenshots ) {
148
+ foreach ( (array) $screenshots as $ss )
149
+ $final_screenshots[] = $ss[1];
150
+ }
151
+ }
152
+
153
+ // Parse the upgrade_notice section specially:
154
+ // 1.0 => blah, 1.1 => fnord
155
+ $upgrade_notice = array();
156
+ if ( isset($final_sections['upgrade_notice']) ) {
157
+ $split = preg_split( '#<h4>(.*?)</h4>#', $final_sections['upgrade_notice'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
158
+ for ( $i = 0; $i < count( $split ); $i += 2 )
159
+ $upgrade_notice[$this->sanitize_text( $split[$i] )] = substr( $this->sanitize_text( $split[$i + 1] ), 0, 300 );
160
+ unset( $final_sections['upgrade_notice'] );
161
+ }
162
+
163
+ // No description?
164
+ // No problem... we'll just fall back to the old style of description
165
+ // We'll even let you use markup this time!
166
+ $excerpt = false;
167
+ if ( !isset($final_sections['description']) ) {
168
+ $final_sections = array_merge(array('description' => $this->filter_text( $_short_description[2], true )), $final_sections);
169
+ $excerpt = true;
170
+ }
171
+
172
+
173
+ // dump the non-special sections into $remaining_content
174
+ // their order will be determined by their original order in the readme.txt
175
+ $remaining_content = '';
176
+ foreach ( $sections as $s_name => $s_data ) {
177
+ $remaining_content .= "\n<h3>{$s_data['title']}</h3>\n{$s_data['content']}";
178
+ }
179
+ $remaining_content = trim($remaining_content);
180
+
181
+
182
+ // All done!
183
+ // $r['tags'] and $r['contributors'] are simple arrays
184
+ // $r['sections'] is an array with named elements
185
+ $r = array(
186
+ 'name' => $name,
187
+ 'tags' => $tags,
188
+ 'requires_at_least' => $requires_at_least,
189
+ 'tested_up_to' => $tested_up_to,
190
+ 'stable_tag' => $stable_tag,
191
+ 'contributors' => $contributors,
192
+ 'donate_link' => $donate_link,
193
+ 'short_description' => $short_description,
194
+ 'screenshots' => $final_screenshots,
195
+ 'is_excerpt' => $excerpt,
196
+ 'is_truncated' => $truncated,
197
+ 'sections' => $final_sections,
198
+ 'remaining_content' => $remaining_content,
199
+ 'upgrade_notice' => $upgrade_notice
200
+ );
201
+
202
+ return $r;
203
+ }
204
+
205
+ function chop_string( $string, $chop ) { // chop a "prefix" from a string: Agressive! uses strstr not 0 === strpos
206
+ if ( $_string = strstr($string, $chop) ) {
207
+ $_string = substr($_string, strlen($chop));
208
+ return trim($_string);
209
+ } else {
210
+ return trim($string);
211
+ }
212
+ }
213
+
214
+ function user_sanitize( $text, $strict = false ) { // whitelisted chars
215
+ if ( function_exists('user_sanitize') ) // bbPress native
216
+ return user_sanitize( $text, $strict );
217
+
218
+ if ( $strict ) {
219
+ $text = preg_replace('/[^a-z0-9-]/i', '', $text);
220
+ $text = preg_replace('|-+|', '-', $text);
221
+ } else {
222
+ $text = preg_replace('/[^a-z0-9_-]/i', '', $text);
223
+ }
224
+ return $text;
225
+ }
226
+
227
+ function sanitize_text( $text ) { // not fancy
228
+ $text = strip_tags($text);
229
+ $text = esc_html($text);
230
+ $text = trim($text);
231
+ return $text;
232
+ }
233
+
234
+ function filter_text( $text, $markdown = false ) { // fancy, Markdown
235
+ $text = trim($text);
236
+
237
+ $text = call_user_func( array( __CLASS__, 'code_trick' ), $text, $markdown ); // A better parser than Markdown's for: backticks -> CODE
238
+
239
+ if ( $markdown ) { // Parse markdown.
240
+ if ( !class_exists('Parsedown', false) ) {
241
+ require_once(dirname(__FILE__) . '/Parsedown' . (version_compare(PHP_VERSION, '5.3.0', '>=') ? '' : 'Legacy') . '.php');
242
+ }
243
+ $instance = Parsedown::instance();
244
+ $text = $instance->text($text);
245
+ }
246
+
247
+ $allowed = array(
248
+ 'a' => array(
249
+ 'href' => array(),
250
+ 'title' => array(),
251
+ 'rel' => array()),
252
+ 'blockquote' => array('cite' => array()),
253
+ 'br' => array(),
254
+ 'p' => array(),
255
+ 'code' => array(),
256
+ 'pre' => array(),
257
+ 'em' => array(),
258
+ 'strong' => array(),
259
+ 'ul' => array(),
260
+ 'ol' => array(),
261
+ 'li' => array(),
262
+ 'h3' => array(),
263
+ 'h4' => array()
264
+ );
265
+
266
+ $text = balanceTags($text);
267
+
268
+ $text = wp_kses( $text, $allowed );
269
+ $text = trim($text);
270
+ return $text;
271
+ }
272
+
273
+ function code_trick( $text, $markdown ) { // Don't use bbPress native function - it's incompatible with Markdown
274
+ // If doing markdown, first take any user formatted code blocks and turn them into backticks so that
275
+ // markdown will preserve things like underscores in code blocks
276
+ if ( $markdown )
277
+ $text = preg_replace_callback("!(<pre><code>|<code>)(.*?)(</code></pre>|</code>)!s", array( __CLASS__,'decodeit'), $text);
278
+
279
+ $text = str_replace(array("\r\n", "\r"), "\n", $text);
280
+ if ( !$markdown ) {
281
+ // This gets the "inline" code blocks, but can't be used with Markdown.
282
+ $text = preg_replace_callback("|(`)(.*?)`|", array( __CLASS__, 'encodeit'), $text);
283
+ // This gets the "block level" code blocks and converts them to PRE CODE
284
+ $text = preg_replace_callback("!(^|\n)`(.*?)`!s", array( __CLASS__, 'encodeit'), $text);
285
+ } else {
286
+ // Markdown can do inline code, we convert bbPress style block level code to Markdown style
287
+ $text = preg_replace_callback("!(^|\n)([ \t]*?)`(.*?)`!s", array( __CLASS__, 'indent'), $text);
288
+ }
289
+ return $text;
290
+ }
291
+
292
+ function indent( $matches ) {
293
+ $text = $matches[3];
294
+ $text = preg_replace('|^|m', $matches[2] . ' ', $text);
295
+ return $matches[1] . $text;
296
+ }
297
+
298
+ function encodeit( $matches ) {
299
+ if ( function_exists('encodeit') ) // bbPress native
300
+ return encodeit( $matches );
301
+
302
+ $text = trim($matches[2]);
303
+ $text = htmlspecialchars($text, ENT_QUOTES);
304
+ $text = str_replace(array("\r\n", "\r"), "\n", $text);
305
+ $text = preg_replace("|\n\n\n+|", "\n\n", $text);
306
+ $text = str_replace('&amp;lt;', '&lt;', $text);
307
+ $text = str_replace('&amp;gt;', '&gt;', $text);
308
+ $text = "<code>$text</code>";
309
+ if ( "`" != $matches[1] )
310
+ $text = "<pre>$text</pre>";
311
+ return $text;
312
+ }
313
+
314
+ function decodeit( $matches ) {
315
+ if ( function_exists('decodeit') ) // bbPress native
316
+ return decodeit( $matches );
317
+
318
+ $text = $matches[2];
319
+ $trans_table = array_flip(get_html_translation_table(HTML_ENTITIES));
320
+ $text = strtr($text, $trans_table);
321
+ $text = str_replace('<br />', '', $text);
322
+ $text = str_replace('&#38;', '&', $text);
323
+ $text = str_replace('&#39;', "'", $text);
324
+ if ( '<pre><code>' == $matches[1] )
325
+ $text = "\n$text\n";
326
+ return "`$text`";
327
+ }
328
+
329
+ } // end class
330
+
331
+ Class Automattic_Readme extends PucReadmeParser {}
readme.txt CHANGED
@@ -3,8 +3,8 @@ Contributors: pascalbajorat
3
  Donate link: https://www.pascal-bajorat.com/spenden/
4
  Tags: seo, images, Post, admin, google, attachment, optimize, photo, picture, image, media, photos, pictures, alt, title, lazy, load
5
  Requires at least: 3.0
6
- Tested up to: 4.9.3
7
- Stable tag: 3.0.0
8
  License: GPLv3
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
@@ -47,6 +47,10 @@ Want to add lazy load to images in your theme? You only need to do some small mo
47
 
48
  == Changelog ==
49
 
 
 
 
 
50
  = 3.0.0 =
51
  * new interface for woocommerce settings
52
  * fixed compability with woocommerce
@@ -137,4 +141,4 @@ Want to add lazy load to images in your theme? You only need to do some small mo
137
 
138
  == License ==
139
 
140
- GNU General Public License v.3 - http://www.gnu.org/licenses/gpl-3.0.html
3
  Donate link: https://www.pascal-bajorat.com/spenden/
4
  Tags: seo, images, Post, admin, google, attachment, optimize, photo, picture, image, media, photos, pictures, alt, title, lazy, load
5
  Requires at least: 3.0
6
+ Tested up to: 4.9.6
7
+ Stable tag: 3.1.0
8
  License: GPLv3
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
47
 
48
  == Changelog ==
49
 
50
+ = 3.1.0 =
51
+ * serveral bugs are fixed and code was optimized
52
+ * improved image and figure handling - Thanks to BasTaller (@bastaller)
53
+
54
  = 3.0.0 =
55
  * new interface for woocommerce settings
56
  * fixed compability with woocommerce
141
 
142
  == License ==
143
 
144
+ GNU General Public License v.3 - http://www.gnu.org/licenses/gpl-3.0.html