Broken Link Checker - Version 1.11.9

Version Description

  • Fixed Reflected XSS ( props to Tobias Fink for the report, ref: https://github.com/sbaresearch/advisories/tree/public/2019/SBA-ADV-20190913-02_WordPress_Plugin_Broken_Link_Checker )
  • Fixed param escaping to avoid possible XSS attack.
Download this release

Release Info

Developer jdailey
Plugin Icon 128x128 Broken Link Checker
Version 1.11.9
Comparing to
See all releases

Code changes from version 1.11.8 to 1.11.9

Files changed (84) hide show
  1. broken-link-checker.php +1 -1
  2. core/core.php +2 -2
  3. core/init.php +388 -388
  4. css/links-page.css +498 -498
  5. css/options-page.css +242 -242
  6. idn/LICENCE +0 -0
  7. idn/ReadMe.txt +0 -0
  8. idn/idna_convert.class.php +0 -0
  9. idn/transcode_wrapper.php +0 -0
  10. idn/uctc.php +0 -0
  11. images/blue_dot.png +0 -0
  12. images/dailymotion-embed.png +0 -0
  13. images/font-awesome/font-awesome-code.png +0 -0
  14. images/font-awesome/font-awesome-comment-alt.png +0 -0
  15. images/font-awesome/font-awesome-exclamation-sign.png +0 -0
  16. images/font-awesome/font-awesome-link.png +0 -0
  17. images/font-awesome/font-awesome-picture.png +0 -0
  18. images/font-awesome/font-awesome-user.png +0 -0
  19. images/font-awesome/font-awesome-warning-sign.png +0 -0
  20. images/font-awesome/readme.txt +10 -10
  21. images/googlevideo-embed.png +0 -0
  22. images/red_highlight.png +0 -0
  23. images/vimeo-embed.png +0 -0
  24. images/youtube-embed.png +0 -0
  25. images/youtube-iframe.png +0 -0
  26. images/youtube-playlist-embed.png +0 -0
  27. includes/activation.php +114 -114
  28. includes/admin/db-schema.php +96 -96
  29. includes/admin/db-upgrade.php +585 -585
  30. includes/admin/links-page-js.php +945 -945
  31. includes/admin/options-page-js.php +146 -146
  32. includes/admin/search-form.php +116 -116
  33. includes/admin/sidebar.php +13 -13
  34. includes/admin/table-printer.php +1 -1
  35. includes/any-post.php +804 -804
  36. includes/checkers.php +120 -120
  37. includes/config-manager.php +127 -127
  38. includes/containers.php +911 -911
  39. includes/extra-strings.php +0 -0
  40. includes/instances.php +639 -639
  41. includes/link-query.php +870 -866
  42. includes/links.php +0 -0
  43. includes/logger.php +188 -188
  44. includes/module-base.php +80 -80
  45. includes/module-manager.php +860 -860
  46. includes/modules.php +34 -34
  47. includes/parsers.php +365 -365
  48. includes/screen-meta-links.php +312 -312
  49. includes/screen-options/screen-options.js +12 -12
  50. includes/screen-options/screen-options.php +297 -297
  51. includes/token-bucket.php +120 -120
  52. includes/transactions-manager.php +0 -0
  53. includes/utility-class.php +417 -417
  54. includes/wp-mutex.php +57 -57
  55. js/jquery.cookie.js +0 -0
  56. js/sprintf.js +55 -55
  57. languages/broken-link-checker-zh_CN.mo +0 -0
  58. modules/checkers/http.php +0 -0
  59. modules/containers/acf_field.php +0 -0
  60. modules/containers/blogroll.php +307 -307
  61. modules/containers/comment.php +434 -434
  62. modules/containers/custom_field.php +637 -637
  63. modules/containers/dummy.php +75 -75
  64. modules/extras/dailymotion-embed.php +36 -36
  65. modules/extras/embed-parser-base.php +206 -206
  66. modules/extras/googlevideo-embed.php +35 -35
  67. modules/extras/mediafire.php +166 -166
  68. modules/extras/plaintext-url-parser-base.php +153 -153
  69. modules/extras/plaintext-url.php +21 -21
  70. modules/extras/rapidshare.php +213 -213
  71. modules/extras/smart-youtube-embed.php +81 -81
  72. modules/extras/vimeo-embed.php +47 -47
  73. modules/extras/youtube-embed.php +39 -39
  74. modules/extras/youtube-iframe.php +103 -103
  75. modules/extras/youtube-playlist-embed.php +47 -47
  76. modules/extras/youtube.php +285 -285
  77. modules/parsers/acf_field.php +134 -134
  78. modules/parsers/html_link.php +371 -371
  79. modules/parsers/image.php +200 -200
  80. modules/parsers/metadata.php +133 -133
  81. modules/parsers/url_field.php +96 -96
  82. php52_lint.sh +11 -0
  83. readme.txt +107 -42
  84. uninstall.php +0 -0
broken-link-checker.php CHANGED
@@ -3,7 +3,7 @@
3
  Plugin Name: Broken Link Checker
4
  Plugin URI: https://wordpress.org/plugins/broken-link-checker/
5
  Description: Checks your blog for broken links and missing images and notifies you on the dashboard if any are found.
6
- Version: 1.11.8
7
  Author: ManageWP
8
  Author URI: https://managewp.com
9
  Text Domain: broken-link-checker
3
  Plugin Name: Broken Link Checker
4
  Plugin URI: https://wordpress.org/plugins/broken-link-checker/
5
  Description: Checks your blog for broken links and missing images and notifies you on the dashboard if any are found.
6
+ Version: 1.11.9
7
  Author: ManageWP
8
  Author URI: https://managewp.com
9
  Text Domain: broken-link-checker
core/core.php CHANGED
@@ -1765,8 +1765,8 @@ class wsBrokenLinkChecker {
1765
  $post = stripslashes_deep($post); //Ceterum censeo, WP shouldn't mangle superglobals.
1766
  }
1767
 
1768
- $search = isset($post['search']) ? $post['search'] : '';
1769
- $replace = isset($post['replace']) ? $post['replace'] : '';
1770
  $use_regex = !empty($post['regex']);
1771
  $case_sensitive = !empty($post['case_sensitive']);
1772
 
1765
  $post = stripslashes_deep($post); //Ceterum censeo, WP shouldn't mangle superglobals.
1766
  }
1767
 
1768
+ $search = isset($post['search']) ? esc_attr( $post['search'] ) : '';
1769
+ $replace = isset($post['replace']) ? esc_attr( $post['replace'] ) : '';
1770
  $use_regex = !empty($post['regex']);
1771
  $case_sensitive = !empty($post['case_sensitive']);
1772
 
core/init.php CHANGED
@@ -1,389 +1,389 @@
1
- <?php
2
- //To prevent conflicts, only one version of the plugin can be activated at any given time.
3
- if ( defined('BLC_ACTIVE') ){
4
- trigger_error(
5
- 'Another version of Broken Link Checker is already active. Please deactivate it before activating this one.',
6
- E_USER_ERROR
7
- );
8
- } else {
9
-
10
- define('BLC_ACTIVE', true);
11
-
12
- //Fail fast if the WP version is unsupported. The $wp_version variable may be obfuscated by other
13
- //plugins, so use function detection to determine the version. get_post_stati was introduced in WP 3.0.0
14
- if ( !function_exists('get_post_stati') ){
15
- trigger_error(
16
- 'This version of Broken Link Checker requires WordPress 3.0 or later!',
17
- E_USER_ERROR
18
- );
19
- }
20
-
21
- /***********************************************
22
- Debugging stuff
23
- ************************************************/
24
-
25
- //define('BLC_DEBUG', true);
26
-
27
-
28
-
29
- /***********************************************
30
- Constants
31
- ************************************************/
32
-
33
- /*
34
- For performance, some internal APIs used for retrieving multiple links, instances or containers
35
- can take an optional "$purpose" argument. Those APIs will try to use this argument to pre-load
36
- any DB data required for the specified purpose ahead of time.
37
-
38
- For example, if you're loading a bunch of link containers for the purposes of parsing them and
39
- thus set $purpose to BLC_FOR_PARSING, the relevant container managers will (if applicable) precache
40
- the parse-able fields in each returned container object. Still, setting $purpose to any particular
41
- value does not *guarantee* any data will be preloaded - it's only a suggestion that it should.
42
-
43
- The currently supported values for the $purpose argument are :
44
- */
45
- define('BLC_FOR_EDITING', 'edit');
46
- define('BLC_FOR_PARSING', 'parse');
47
- define('BLC_FOR_DISPLAY', 'display');
48
-
49
- define('BLC_DATABASE_VERSION', 9);
50
-
51
- /***********************************************
52
- Configuration
53
- ************************************************/
54
-
55
- //Load and initialize the plugin's configuration
56
- require BLC_DIRECTORY . '/includes/config-manager.php';
57
-
58
- global $blc_config_manager;
59
- $blc_config_manager = new blcConfigurationManager(
60
- //Save the plugin's configuration into this DB option
61
- 'wsblc_options',
62
- //Initialize default settings
63
- array(
64
- 'max_execution_time' => 7*60, //(in seconds) How long the worker instance may run, at most.
65
- 'check_threshold' => 72, //(in hours) Check each link every 72 hours.
66
-
67
- 'recheck_count' => 3, //How many times a broken link should be re-checked.
68
- 'recheck_threshold' => 30*60, //(in seconds) Re-check broken links after 30 minutes.
69
-
70
- 'run_in_dashboard' => true, //Run the link checker algo. continuously while the Dashboard is open.
71
- 'run_via_cron' => true, //Run it hourly via WordPress pseudo-cron.
72
-
73
- 'mark_broken_links' => true, //Whether to add the broken_link class to broken links in posts.
74
- 'broken_link_css' => ".broken_link, a.broken_link {\n\ttext-decoration: line-through;\n}",
75
- 'nofollow_broken_links' => false, //Whether to add rel="nofollow" to broken links in posts.
76
-
77
- 'mark_removed_links' => false, //Whether to add the removed_link class when un-linking a link.
78
- 'removed_link_css' => ".removed_link, a.removed_link {\n\ttext-decoration: line-through;\n}",
79
-
80
- 'exclusion_list' => array(), //Links that contain a substring listed in this array won't be checked.
81
-
82
- 'send_email_notifications' => true, //Whether to send the admin email notifications about broken links
83
- 'send_authors_email_notifications' => false, //Whether to send post authors notifications about broken links in their posts.
84
- 'notification_email_address' => '', //If set, send email notifications to this address instead of the admin.
85
- 'notification_schedule' => 'daily', //How often (at most) notifications will be sent. Possible values : 'daily', 'weekly'
86
- 'last_notification_sent' => 0, //When the last email notification was sent (Unix timestamp)
87
-
88
- 'suggestions_enabled' => true, //Whether to suggest alternative URLs for broken links.
89
-
90
- 'warnings_enabled' => true, //Try to automatically detect temporary problems and false positives,
91
- //and report them as "Warnings" instead of broken links.
92
-
93
- 'server_load_limit' => null, //Stop parsing stuff & checking links if the 1-minute load average
94
- //goes over this value. Only works on Linux servers. 0 = no limit.
95
- 'enable_load_limit' => true, //Enable/disable load monitoring.
96
-
97
- 'custom_fields' => array(), //List of custom fields that can contain URLs and should be checked.
98
- 'acf_fields' => array(), //List of custom fields that can contain URLs and should be checked.
99
- 'enabled_post_statuses' => array('publish'), //Only check posts that match one of these statuses
100
-
101
- 'autoexpand_widget' => true, //Autoexpand the Dashboard widget if broken links are detected
102
- 'dashboard_widget_capability' => 'edit_others_posts', //Only display the widget to users who have this capability
103
- 'show_link_count_bubble' => true, //Display a notification bubble in the menu when broken links are found
104
-
105
- 'table_layout' => 'flexible', //The layout of the link table. Possible values : 'classic', 'flexible'
106
- 'table_compact' => true, //Compact table mode on/off
107
- 'table_visible_columns' => array('new-url', 'status', 'used-in', 'new-link-text',),
108
- 'table_links_per_page' => 30,
109
- 'table_color_code_status' => true, //Color-code link status text
110
-
111
- 'need_resynch' => false, //[Internal flag] True if there are unparsed items.
112
- 'current_db_version' => 0, //The currently set-up version of the plugin's tables
113
-
114
- 'timeout' => 30, //(in seconds) Links that take longer than this to respond will be treated as broken.
115
-
116
- 'highlight_permanent_failures' => false,//Highlight links that have appear to be permanently broken (in Tools -> Broken Links).
117
- 'failure_duration_threshold' => 3, //(days) Assume a link is permanently broken if it still hasn't
118
- //recovered after this many days.
119
- 'logging_enabled' => false,
120
- 'log_file' => '',
121
- 'custom_log_file_enabled' => false,
122
-
123
- 'installation_complete' => false,
124
- 'installation_flag_cleared_on' => 0,
125
- 'installation_flag_set_on' => 0,
126
-
127
- 'user_has_donated' => false, //Whether the user has donated to the plugin.
128
- 'donation_flag_fixed' => false,
129
-
130
- //Visible link actions.
131
- 'show_link_actions' => array('blc-deredirect-action' => false),
132
- )
133
- );
134
-
135
- /***********************************************
136
- Logging
137
- ************************************************/
138
-
139
- include BLC_DIRECTORY . '/includes/logger.php';
140
-
141
- global $blclog;
142
- if ($blc_config_manager->get('logging_enabled', false) && is_writable($blc_config_manager->get('log_file'))) {
143
- $blclog = new blcFileLogger($blc_config_manager->get('log_file'));
144
- } else {
145
- $blclog = new blcDummyLogger;
146
- }
147
-
148
- /*
149
- if ( defined('BLC_DEBUG') && constant('BLC_DEBUG') ){
150
- //Load FirePHP for debug logging
151
- if ( !class_exists('FB') && file_exists(BLC_DIRECTORY . '/FirePHPCore/fb.php4') ) {
152
- require_once BLC_DIRECTORY . '/FirePHPCore/fb.php4';
153
- }
154
- //FB::setEnabled(false);
155
- }
156
- //to comment out all calls : (^[^\/]*)(FB::) -> $1\/\/$2
157
- //to uncomment : \/\/(\s*FB::) -> $1
158
- //*/
159
-
160
- /***********************************************
161
- Global functions
162
- ************************************************/
163
-
164
- /**
165
- * Get the configuration object used by Broken Link Checker.
166
- *
167
- * @return blcConfigurationManager
168
- */
169
- function blc_get_configuration(){
170
- return $GLOBALS['blc_config_manager'];
171
- }
172
-
173
- /**
174
- * Notify the link checker that there are unsynched items
175
- * that might contain links (e.g. a new or edited post).
176
- *
177
- * @return void
178
- */
179
- function blc_got_unsynched_items(){
180
- $conf = blc_get_configuration();
181
-
182
- if ( !$conf->options['need_resynch'] ){
183
- $conf->options['need_resynch'] = true;
184
- $conf->save_options();
185
- }
186
- }
187
-
188
- /**
189
- * (Re)create synchronization records for all containers and mark them all as unparsed.
190
- *
191
- * @param bool $forced If true, the plugin will recreate all synch. records from scratch.
192
- * @return void
193
- */
194
- function blc_resynch( $forced = false ){
195
- global $wpdb, $blclog; /* @var wpdb $wpdb */
196
-
197
- if ( $forced ){
198
- $blclog->info('... Forced resynchronization initiated');
199
-
200
- //Drop all synchronization records
201
- $wpdb->query("TRUNCATE {$wpdb->prefix}blc_synch");
202
- } else {
203
- $blclog->info('... Resynchronization initiated');
204
- }
205
-
206
- //Remove invalid DB entries
207
- blc_cleanup_database();
208
-
209
- //(Re)create and update synch. records for all container types.
210
- $blclog->info('... (Re)creating container records');
211
- blcContainerHelper::resynch($forced);
212
-
213
- $blclog->info('... Setting resync. flags');
214
- blc_got_unsynched_items();
215
-
216
- //All done.
217
- $blclog->info('Database resynchronization complete.');
218
- }
219
-
220
- /**
221
- * Delete synch. records, instances and links that refer to missing or invalid items.
222
- *
223
- * @return void
224
- */
225
- function blc_cleanup_database(){
226
- global $blclog;
227
-
228
- //Delete synch. records for container types that don't exist
229
- $blclog->info('... Deleting invalid container records');
230
- blcContainerHelper::cleanup_containers();
231
-
232
- //Delete invalid instances
233
- $blclog->info('... Deleting invalid link instances');
234
- blc_cleanup_instances();
235
-
236
- //Delete orphaned links
237
- $blclog->info('... Deleting orphaned links');
238
- blc_cleanup_links();
239
- }
240
-
241
- /***********************************************
242
- Utility hooks
243
- ************************************************/
244
-
245
- /**
246
- * Add a weekly Cron schedule for email notifications
247
- * and a bimonthly schedule for database maintenance.
248
- *
249
- * @param array $schedules Existing Cron schedules.
250
- * @return array
251
- */
252
- function blc_cron_schedules($schedules){
253
- if ( !isset($schedules['weekly']) ){
254
- $schedules['weekly'] = array(
255
- 'interval' => 604800, //7 days
256
- 'display' => __('Once Weekly')
257
- );
258
- }
259
- if ( !isset($schedules['bimonthly']) ){
260
- $schedules['bimonthly'] = array(
261
- 'interval' => 15*24*2600, //15 days
262
- 'display' => __('Twice a Month')
263
- );
264
- }
265
-
266
- return $schedules;
267
- }
268
- add_filter('cron_schedules', 'blc_cron_schedules');
269
-
270
- /***********************************************
271
- Main functionality
272
- ************************************************/
273
-
274
- //Execute the installation/upgrade script when the plugin is activated.
275
- function blc_activation_hook(){
276
- require BLC_DIRECTORY . '/includes/activation.php';
277
- }
278
- register_activation_hook(BLC_PLUGIN_FILE, 'blc_activation_hook');
279
-
280
- //Load the plugin if installed successfully
281
- if ( $blc_config_manager->options['installation_complete'] ){
282
- function blc_init(){
283
- global $blc_module_manager, $blc_config_manager, $ws_link_checker;
284
-
285
- static $init_done = false;
286
- if ( $init_done ){
287
- return;
288
- }
289
- $init_done = true;
290
-
291
- //Ensure the database is up to date
292
- if ($blc_config_manager->options['current_db_version'] != BLC_DATABASE_VERSION) {
293
- require_once BLC_DIRECTORY . '/includes/admin/db-upgrade.php';
294
- blcDatabaseUpgrader::upgrade_database(); //Also updates the DB ver. in options['current_db_version'].
295
- }
296
-
297
- //Load the base classes and utilities
298
- require_once BLC_DIRECTORY . '/includes/links.php';
299
- require_once BLC_DIRECTORY . '/includes/link-query.php';
300
- require_once BLC_DIRECTORY . '/includes/instances.php';
301
- require_once BLC_DIRECTORY . '/includes/utility-class.php';
302
-
303
- //Load the module subsystem
304
- require_once BLC_DIRECTORY . '/includes/modules.php';
305
-
306
- //Load the modules that want to be executed in all contexts
307
- $blc_module_manager->load_modules();
308
-
309
- if ( is_admin() || defined('DOING_CRON') ){
310
-
311
- //It's an admin-side or Cron request. Load the core.
312
- require_once BLC_DIRECTORY . '/core/core.php';
313
- $ws_link_checker = new wsBrokenLinkChecker( BLC_PLUGIN_FILE, $blc_config_manager );
314
-
315
- } else {
316
-
317
- //This is user-side request, so we don't need to load the core.
318
- //We might need to inject the CSS for removed links, though.
319
- if ( $blc_config_manager->options['mark_removed_links'] && !empty($blc_config_manager->options['removed_link_css']) ){
320
- function blc_print_removed_link_css(){
321
- global $blc_config_manager;
322
- echo '<style type="text/css">',$blc_config_manager->options['removed_link_css'],'</style>';
323
- }
324
- add_action('wp_head', 'blc_print_removed_link_css');
325
- }
326
- }
327
- }
328
- add_action('init', 'blc_init', 2000);
329
- } else {
330
- //Display installation errors (if any) on the Dashboard.
331
- function blc_print_installation_errors(){
332
- global $blc_config_manager, $wpdb; /** @var wpdb $wpdb */
333
- if ( $blc_config_manager->options['installation_complete'] ) {
334
- return;
335
- }
336
-
337
- $messages = array(
338
- '<strong>' . __('Broken Link Checker installation failed. Try deactivating and then reactivating the plugin.', 'broken-link-checker') . '</strong>',
339
- );
340
-
341
- if ( is_multisite() && is_plugin_active_for_network(plugin_basename(BLC_PLUGIN_FILE)) ) {
342
- $messages[] = __('Please activate the plugin separately on each site. Network activation is not supported.', 'broken-link-checker');
343
- $messages[] = '';
344
- }
345
-
346
- if ( ! $blc_config_manager->db_option_loaded ) {
347
- $messages[] = sprintf(
348
- '<strong>Failed to load plugin settings from the "%s" option.</strong>',
349
- $blc_config_manager->option_name
350
- );
351
- $messages[] = '';
352
-
353
- $serialized_config = $wpdb->get_var(
354
- sprintf(
355
- 'SELECT option_value FROM `%s` WHERE option_name = "%s"',
356
- $wpdb->options,
357
- $blc_config_manager->option_name
358
- )
359
- );
360
-
361
- if ( $serialized_config === null ) {
362
- $messages[] = "Option doesn't exist in the {$wpdb->options} table.";
363
- } else {
364
- $messages[] = "Option exists in the {$wpdb->options} table and has the following value:";
365
- $messages[] = '';
366
- $messages[] = '<textarea cols="120" rows="20">' . htmlentities($serialized_config) . '</textarea>';
367
- }
368
-
369
- } else {
370
- $logger = new blcCachedOptionLogger('blc_installation_log');
371
- $messages = array_merge(
372
- $messages,
373
- array(
374
- 'installation_complete = ' . (isset($blc_config_manager->options['installation_complete']) ? intval($blc_config_manager->options['installation_complete']) : 'no value'),
375
- 'installation_flag_cleared_on = ' . $blc_config_manager->options['installation_flag_cleared_on'],
376
- 'installation_flag_set_on = ' . $blc_config_manager->options['installation_flag_set_on'],
377
- '',
378
- '<em>Installation log follows :</em>'
379
- ),
380
- $logger->get_messages()
381
- );
382
- }
383
-
384
- echo "<div class='error'><p>", implode("<br>\n", $messages), "</p></div>";
385
- }
386
- add_action('admin_notices', 'blc_print_installation_errors');
387
- }
388
-
389
  }
1
+ <?php
2
+ //To prevent conflicts, only one version of the plugin can be activated at any given time.
3
+ if ( defined('BLC_ACTIVE') ){
4
+ trigger_error(
5
+ 'Another version of Broken Link Checker is already active. Please deactivate it before activating this one.',
6
+ E_USER_ERROR
7
+ );
8
+ } else {
9
+
10
+ define('BLC_ACTIVE', true);
11
+
12
+ //Fail fast if the WP version is unsupported. The $wp_version variable may be obfuscated by other
13
+ //plugins, so use function detection to determine the version. get_post_stati was introduced in WP 3.0.0
14
+ if ( !function_exists('get_post_stati') ){
15
+ trigger_error(
16
+ 'This version of Broken Link Checker requires WordPress 3.0 or later!',
17
+ E_USER_ERROR
18
+ );
19
+ }
20
+
21
+ /***********************************************
22
+ Debugging stuff
23
+ ************************************************/
24
+
25
+ //define('BLC_DEBUG', true);
26
+
27
+
28
+
29
+ /***********************************************
30
+ Constants
31
+ ************************************************/
32
+
33
+ /*
34
+ For performance, some internal APIs used for retrieving multiple links, instances or containers
35
+ can take an optional "$purpose" argument. Those APIs will try to use this argument to pre-load
36
+ any DB data required for the specified purpose ahead of time.
37
+
38
+ For example, if you're loading a bunch of link containers for the purposes of parsing them and
39
+ thus set $purpose to BLC_FOR_PARSING, the relevant container managers will (if applicable) precache
40
+ the parse-able fields in each returned container object. Still, setting $purpose to any particular
41
+ value does not *guarantee* any data will be preloaded - it's only a suggestion that it should.
42
+
43
+ The currently supported values for the $purpose argument are :
44
+ */
45
+ define('BLC_FOR_EDITING', 'edit');
46
+ define('BLC_FOR_PARSING', 'parse');
47
+ define('BLC_FOR_DISPLAY', 'display');
48
+
49
+ define('BLC_DATABASE_VERSION', 9);
50
+
51
+ /***********************************************
52
+ Configuration
53
+ ************************************************/
54
+
55
+ //Load and initialize the plugin's configuration
56
+ require BLC_DIRECTORY . '/includes/config-manager.php';
57
+
58
+ global $blc_config_manager;
59
+ $blc_config_manager = new blcConfigurationManager(
60
+ //Save the plugin's configuration into this DB option
61
+ 'wsblc_options',
62
+ //Initialize default settings
63
+ array(
64
+ 'max_execution_time' => 7*60, //(in seconds) How long the worker instance may run, at most.
65
+ 'check_threshold' => 72, //(in hours) Check each link every 72 hours.
66
+
67
+ 'recheck_count' => 3, //How many times a broken link should be re-checked.
68
+ 'recheck_threshold' => 30*60, //(in seconds) Re-check broken links after 30 minutes.
69
+
70
+ 'run_in_dashboard' => true, //Run the link checker algo. continuously while the Dashboard is open.
71
+ 'run_via_cron' => true, //Run it hourly via WordPress pseudo-cron.
72
+
73
+ 'mark_broken_links' => true, //Whether to add the broken_link class to broken links in posts.
74
+ 'broken_link_css' => ".broken_link, a.broken_link {\n\ttext-decoration: line-through;\n}",
75
+ 'nofollow_broken_links' => false, //Whether to add rel="nofollow" to broken links in posts.
76
+
77
+ 'mark_removed_links' => false, //Whether to add the removed_link class when un-linking a link.
78
+ 'removed_link_css' => ".removed_link, a.removed_link {\n\ttext-decoration: line-through;\n}",
79
+
80
+ 'exclusion_list' => array(), //Links that contain a substring listed in this array won't be checked.
81
+
82
+ 'send_email_notifications' => true, //Whether to send the admin email notifications about broken links
83
+ 'send_authors_email_notifications' => false, //Whether to send post authors notifications about broken links in their posts.
84
+ 'notification_email_address' => '', //If set, send email notifications to this address instead of the admin.
85
+ 'notification_schedule' => 'daily', //How often (at most) notifications will be sent. Possible values : 'daily', 'weekly'
86
+ 'last_notification_sent' => 0, //When the last email notification was sent (Unix timestamp)
87
+
88
+ 'suggestions_enabled' => true, //Whether to suggest alternative URLs for broken links.
89
+
90
+ 'warnings_enabled' => true, //Try to automatically detect temporary problems and false positives,
91
+ //and report them as "Warnings" instead of broken links.
92
+
93
+ 'server_load_limit' => null, //Stop parsing stuff & checking links if the 1-minute load average
94
+ //goes over this value. Only works on Linux servers. 0 = no limit.
95
+ 'enable_load_limit' => true, //Enable/disable load monitoring.
96
+
97
+ 'custom_fields' => array(), //List of custom fields that can contain URLs and should be checked.
98
+ 'acf_fields' => array(), //List of custom fields that can contain URLs and should be checked.
99
+ 'enabled_post_statuses' => array('publish'), //Only check posts that match one of these statuses
100
+
101
+ 'autoexpand_widget' => true, //Autoexpand the Dashboard widget if broken links are detected
102
+ 'dashboard_widget_capability' => 'edit_others_posts', //Only display the widget to users who have this capability
103
+ 'show_link_count_bubble' => true, //Display a notification bubble in the menu when broken links are found
104
+
105
+ 'table_layout' => 'flexible', //The layout of the link table. Possible values : 'classic', 'flexible'
106
+ 'table_compact' => true, //Compact table mode on/off
107
+ 'table_visible_columns' => array('new-url', 'status', 'used-in', 'new-link-text',),
108
+ 'table_links_per_page' => 30,
109
+ 'table_color_code_status' => true, //Color-code link status text
110
+
111
+ 'need_resynch' => false, //[Internal flag] True if there are unparsed items.
112
+ 'current_db_version' => 0, //The currently set-up version of the plugin's tables
113
+
114
+ 'timeout' => 30, //(in seconds) Links that take longer than this to respond will be treated as broken.
115
+
116
+ 'highlight_permanent_failures' => false,//Highlight links that have appear to be permanently broken (in Tools -> Broken Links).
117
+ 'failure_duration_threshold' => 3, //(days) Assume a link is permanently broken if it still hasn't
118
+ //recovered after this many days.
119
+ 'logging_enabled' => false,
120
+ 'log_file' => '',
121
+ 'custom_log_file_enabled' => false,
122
+
123
+ 'installation_complete' => false,
124
+ 'installation_flag_cleared_on' => 0,
125
+ 'installation_flag_set_on' => 0,
126
+
127
+ 'user_has_donated' => false, //Whether the user has donated to the plugin.
128
+ 'donation_flag_fixed' => false,
129
+
130
+ //Visible link actions.
131
+ 'show_link_actions' => array('blc-deredirect-action' => false),
132
+ )
133
+ );
134
+
135
+ /***********************************************
136
+ Logging
137
+ ************************************************/
138
+
139
+ include BLC_DIRECTORY . '/includes/logger.php';
140
+
141
+ global $blclog;
142
+ if ($blc_config_manager->get('logging_enabled', false) && is_writable($blc_config_manager->get('log_file'))) {
143
+ $blclog = new blcFileLogger($blc_config_manager->get('log_file'));
144
+ } else {
145
+ $blclog = new blcDummyLogger;
146
+ }
147
+
148
+ /*
149
+ if ( defined('BLC_DEBUG') && constant('BLC_DEBUG') ){
150
+ //Load FirePHP for debug logging
151
+ if ( !class_exists('FB') && file_exists(BLC_DIRECTORY . '/FirePHPCore/fb.php4') ) {
152
+ require_once BLC_DIRECTORY . '/FirePHPCore/fb.php4';
153
+ }
154
+ //FB::setEnabled(false);
155
+ }
156
+ //to comment out all calls : (^[^\/]*)(FB::) -> $1\/\/$2
157
+ //to uncomment : \/\/(\s*FB::) -> $1
158
+ //*/
159
+
160
+ /***********************************************
161
+ Global functions
162
+ ************************************************/
163
+
164
+ /**
165
+ * Get the configuration object used by Broken Link Checker.
166
+ *
167
+ * @return blcConfigurationManager
168
+ */
169
+ function blc_get_configuration(){
170
+ return $GLOBALS['blc_config_manager'];
171
+ }
172
+
173
+ /**
174
+ * Notify the link checker that there are unsynched items
175
+ * that might contain links (e.g. a new or edited post).
176
+ *
177
+ * @return void
178
+ */
179
+ function blc_got_unsynched_items(){
180
+ $conf = blc_get_configuration();
181
+
182
+ if ( !$conf->options['need_resynch'] ){
183
+ $conf->options['need_resynch'] = true;
184
+ $conf->save_options();
185
+ }
186
+ }
187
+
188
+ /**
189
+ * (Re)create synchronization records for all containers and mark them all as unparsed.
190
+ *
191
+ * @param bool $forced If true, the plugin will recreate all synch. records from scratch.
192
+ * @return void
193
+ */
194
+ function blc_resynch( $forced = false ){
195
+ global $wpdb, $blclog; /* @var wpdb $wpdb */
196
+
197
+ if ( $forced ){
198
+ $blclog->info('... Forced resynchronization initiated');
199
+
200
+ //Drop all synchronization records
201
+ $wpdb->query("TRUNCATE {$wpdb->prefix}blc_synch");
202
+ } else {
203
+ $blclog->info('... Resynchronization initiated');
204
+ }
205
+
206
+ //Remove invalid DB entries
207
+ blc_cleanup_database();
208
+
209
+ //(Re)create and update synch. records for all container types.
210
+ $blclog->info('... (Re)creating container records');
211
+ blcContainerHelper::resynch($forced);
212
+
213
+ $blclog->info('... Setting resync. flags');
214
+ blc_got_unsynched_items();
215
+
216
+ //All done.
217
+ $blclog->info('Database resynchronization complete.');
218
+ }
219
+
220
+ /**
221
+ * Delete synch. records, instances and links that refer to missing or invalid items.
222
+ *
223
+ * @return void
224
+ */
225
+ function blc_cleanup_database(){
226
+ global $blclog;
227
+
228
+ //Delete synch. records for container types that don't exist
229
+ $blclog->info('... Deleting invalid container records');
230
+ blcContainerHelper::cleanup_containers();
231
+
232
+ //Delete invalid instances
233
+ $blclog->info('... Deleting invalid link instances');
234
+ blc_cleanup_instances();
235
+
236
+ //Delete orphaned links
237
+ $blclog->info('... Deleting orphaned links');
238
+ blc_cleanup_links();
239
+ }
240
+
241
+ /***********************************************
242
+ Utility hooks
243
+ ************************************************/
244
+
245
+ /**
246
+ * Add a weekly Cron schedule for email notifications
247
+ * and a bimonthly schedule for database maintenance.
248
+ *
249
+ * @param array $schedules Existing Cron schedules.
250
+ * @return array
251
+ */
252
+ function blc_cron_schedules($schedules){
253
+ if ( !isset($schedules['weekly']) ){
254
+ $schedules['weekly'] = array(
255
+ 'interval' => 604800, //7 days
256
+ 'display' => __('Once Weekly')
257
+ );
258
+ }
259
+ if ( !isset($schedules['bimonthly']) ){
260
+ $schedules['bimonthly'] = array(
261
+ 'interval' => 15*24*2600, //15 days
262
+ 'display' => __('Twice a Month')
263
+ );
264
+ }
265
+
266
+ return $schedules;
267
+ }
268
+ add_filter('cron_schedules', 'blc_cron_schedules');
269
+
270
+ /***********************************************
271
+ Main functionality
272
+ ************************************************/
273
+
274
+ //Execute the installation/upgrade script when the plugin is activated.
275
+ function blc_activation_hook(){
276
+ require BLC_DIRECTORY . '/includes/activation.php';
277
+ }
278
+ register_activation_hook(BLC_PLUGIN_FILE, 'blc_activation_hook');
279
+
280
+ //Load the plugin if installed successfully
281
+ if ( $blc_config_manager->options['installation_complete'] ){
282
+ function blc_init(){
283
+ global $blc_module_manager, $blc_config_manager, $ws_link_checker;
284
+
285
+ static $init_done = false;
286
+ if ( $init_done ){
287
+ return;
288
+ }
289
+ $init_done = true;
290
+
291
+ //Ensure the database is up to date
292
+ if ($blc_config_manager->options['current_db_version'] != BLC_DATABASE_VERSION) {
293
+ require_once BLC_DIRECTORY . '/includes/admin/db-upgrade.php';
294
+ blcDatabaseUpgrader::upgrade_database(); //Also updates the DB ver. in options['current_db_version'].
295
+ }
296
+
297
+ //Load the base classes and utilities
298
+ require_once BLC_DIRECTORY . '/includes/links.php';
299
+ require_once BLC_DIRECTORY . '/includes/link-query.php';
300
+ require_once BLC_DIRECTORY . '/includes/instances.php';
301
+ require_once BLC_DIRECTORY . '/includes/utility-class.php';
302
+
303
+ //Load the module subsystem
304
+ require_once BLC_DIRECTORY . '/includes/modules.php';
305
+
306
+ //Load the modules that want to be executed in all contexts
307
+ $blc_module_manager->load_modules();
308
+
309
+ if ( is_admin() || defined('DOING_CRON') ){
310
+
311
+ //It's an admin-side or Cron request. Load the core.
312
+ require_once BLC_DIRECTORY . '/core/core.php';
313
+ $ws_link_checker = new wsBrokenLinkChecker( BLC_PLUGIN_FILE, $blc_config_manager );
314
+
315
+ } else {
316
+
317
+ //This is user-side request, so we don't need to load the core.
318
+ //We might need to inject the CSS for removed links, though.
319
+ if ( $blc_config_manager->options['mark_removed_links'] && !empty($blc_config_manager->options['removed_link_css']) ){
320
+ function blc_print_removed_link_css(){
321
+ global $blc_config_manager;
322
+ echo '<style type="text/css">',$blc_config_manager->options['removed_link_css'],'</style>';
323
+ }
324
+ add_action('wp_head', 'blc_print_removed_link_css');
325
+ }
326
+ }
327
+ }
328
+ add_action('init', 'blc_init', 2000);
329
+ } else {
330
+ //Display installation errors (if any) on the Dashboard.
331
+ function blc_print_installation_errors(){
332
+ global $blc_config_manager, $wpdb; /** @var wpdb $wpdb */
333
+ if ( $blc_config_manager->options['installation_complete'] ) {
334
+ return;
335
+ }
336
+
337
+ $messages = array(
338
+ '<strong>' . __('Broken Link Checker installation failed. Try deactivating and then reactivating the plugin.', 'broken-link-checker') . '</strong>',
339
+ );
340
+
341
+ if ( is_multisite() && is_plugin_active_for_network(plugin_basename(BLC_PLUGIN_FILE)) ) {
342
+ $messages[] = __('Please activate the plugin separately on each site. Network activation is not supported.', 'broken-link-checker');
343
+ $messages[] = '';
344
+ }
345
+
346
+ if ( ! $blc_config_manager->db_option_loaded ) {
347
+ $messages[] = sprintf(
348
+ '<strong>Failed to load plugin settings from the "%s" option.</strong>',
349
+ $blc_config_manager->option_name
350
+ );
351
+ $messages[] = '';
352
+
353
+ $serialized_config = $wpdb->get_var(
354
+ sprintf(
355
+ 'SELECT option_value FROM `%s` WHERE option_name = "%s"',
356
+ $wpdb->options,
357
+ $blc_config_manager->option_name
358
+ )
359
+ );
360
+
361
+ if ( $serialized_config === null ) {
362
+ $messages[] = "Option doesn't exist in the {$wpdb->options} table.";
363
+ } else {
364
+ $messages[] = "Option exists in the {$wpdb->options} table and has the following value:";
365
+ $messages[] = '';
366
+ $messages[] = '<textarea cols="120" rows="20">' . htmlentities($serialized_config) . '</textarea>';
367
+ }
368
+
369
+ } else {
370
+ $logger = new blcCachedOptionLogger('blc_installation_log');
371
+ $messages = array_merge(
372
+ $messages,
373
+ array(
374
+ 'installation_complete = ' . (isset($blc_config_manager->options['installation_complete']) ? intval($blc_config_manager->options['installation_complete']) : 'no value'),
375
+ 'installation_flag_cleared_on = ' . $blc_config_manager->options['installation_flag_cleared_on'],
376
+ 'installation_flag_set_on = ' . $blc_config_manager->options['installation_flag_set_on'],
377
+ '',
378
+ '<em>Installation log follows :</em>'
379
+ ),
380
+ $logger->get_messages()
381
+ );
382
+ }
383
+
384
+ echo "<div class='error'><p>", implode("<br>\n", $messages), "</p></div>";
385
+ }
386
+ add_action('admin_notices', 'blc_print_installation_errors');
387
+ }
388
+
389
  }
css/links-page.css CHANGED
@@ -1,499 +1,499 @@
1
- /* Link table layout */
2
-
3
- table#blc-links {
4
- width: 100%;
5
- table-layout: fixed;
6
- }
7
-
8
- tr.blc-link-details {
9
- display: none;
10
- }
11
-
12
- .blc-detail-container {
13
- display: block;
14
- width: 100%;
15
- }
16
-
17
- .blc-detail-block {
18
- width: 50%;
19
- }
20
-
21
- /* Column headers */
22
-
23
- th.column-new-url {
24
- width: 33%;
25
- }
26
-
27
- th.column-status {
28
- width: 12em;
29
- }
30
-
31
- th.column-new-link-text {
32
-
33
- }
34
-
35
- th.column-used-in {
36
-
37
- }
38
-
39
- th.column-source {
40
- width: 33%;
41
- }
42
-
43
- th.column-link-text {
44
- width: 24%;
45
- }
46
-
47
- th.column-url {
48
- width: 35%;
49
- }
50
-
51
- th.column-last-checked {
52
- width: 10em;
53
- }
54
-
55
- th.column-broken-for {
56
- width: 10em;
57
- }
58
-
59
- th.column-instance-count {
60
- width: 10em;
61
- }
62
-
63
- /* Cells */
64
-
65
- td.column-new-url,
66
- td.column-used-in
67
- {
68
- /*
69
- overflow: hidden;
70
- white-space: nowrap;
71
- text-overflow: ellipsis;
72
- -o-text-overflow: ellipsis;
73
- */
74
- }
75
-
76
- td.column-new-url .row-actions,
77
- td.column-url .row-actions
78
- {
79
- margin-left: 16px;
80
- }
81
-
82
- td.column-new-url .mini-status {
83
- margin-left: 16px;
84
- color: black;
85
- }
86
-
87
- table.mini-status {
88
- border-spacing: 0;
89
- }
90
-
91
- /* Styles for broken links, redirects and other link states or types */
92
-
93
- .blc-redirect .blc-link-url {
94
- background-image: url("../images/blue_dot.png");
95
- }
96
-
97
- .link-status-error .blc-link-url {
98
- background-image: url("../images/font-awesome/font-awesome-exclamation-sign.png");
99
- }
100
-
101
- .link-status-warning .blc-link-url {
102
- background-image: url("../images/font-awesome/font-awesome-warning-sign.png");
103
- }
104
-
105
- .blc-excluded-link {
106
- background-color: #E2E2E2;
107
- }
108
-
109
- .blc-permanently-broken {
110
-
111
- }
112
-
113
- .blc-permanently-broken-hl {
114
- background-image: url("../images/red_highlight.png");
115
- }
116
-
117
-
118
- /* The "Status" column */
119
- td.column-status {
120
- cursor: pointer;
121
- }
122
-
123
- .mini-status, .mini-status th, .mini-status td {
124
- border: 0;
125
- font-size: 1em;
126
- padding: 0;
127
- color: gray;
128
- }
129
-
130
- .mini-status div {
131
- display: inline-block;
132
- }
133
-
134
- .mini-status .status-text {
135
- color: black;
136
- }
137
-
138
- .link-status-unknown td.column-status .http-code {
139
- display: none;
140
- }
141
-
142
-
143
- /* Status colors */
144
- .color-code-link-status .mini-status .http-code,
145
- .color-code-link-status .mini-status .status-text
146
- {
147
- font-weight: bold;
148
- }
149
-
150
- .color-code-link-status .link-status-unknown td.column-status .status-text,
151
- .color-code-link-status .link-status-unknown td.column-status .http-code
152
- {
153
- color: gray;
154
- font-weight: normal;
155
- }
156
-
157
- .color-code-link-status .link-status-ok td.column-status .status-text,
158
- .color-code-link-status .link-status-ok td.column-status .http-code
159
- {
160
- color: green;
161
- }
162
-
163
- .color-code-link-status .link-status-info td.column-status .status-text,
164
- .color-code-link-status .link-status-info td.column-status .http-code
165
- {
166
- color: blue;
167
- }
168
-
169
- .color-code-link-status .link-status-warning td.column-status .status-text,
170
- .color-code-link-status .link-status-warning td.column-status .http-code
171
- {
172
- color: #FF8C00; /*#FFA500*/
173
- }
174
-
175
- .color-code-link-status .link-status-error td.column-status .status-text,
176
- .color-code-link-status .link-status-error td.column-status .http-code
177
- {
178
- color: red;
179
- }
180
-
181
-
182
- /* "Compact" view */
183
-
184
- .compact td.column-url,
185
- .compact td.column-status,
186
- .compact td.column-link-text,
187
- .compact td.column-used-in,
188
- .compact td.column-new-url,
189
- .compact td.column-source,
190
- .compact td.column-new-link-text,
191
- .compact td.column-redirect-url
192
- {
193
- overflow: hidden;
194
- -o-text-overflow: ellipsis;
195
- text-overflow: ellipsis;
196
- white-space: nowrap;
197
- word-wrap: normal;
198
- }
199
-
200
- .compact .link-last-checked,
201
- .compact .link-broken-for,
202
- .compact .link-text
203
- {
204
- display: none;
205
- }
206
-
207
-
208
- /* Only show the "Details" link in the compact view. */
209
- #blc-links .column-status .row-actions {
210
- display: none;
211
- }
212
- #blc-links.compact .column-status .row-actions {
213
- display: block;
214
- }
215
-
216
- /* Misc table styles */
217
-
218
- .blc-link-url {
219
- padding-left: 16px;
220
- overflow: hidden;
221
-
222
- background-image: none;
223
- background-position: left center;
224
- background-repeat: no-repeat;
225
- }
226
-
227
- td.column-new-url { /* The URL never wraps */
228
- word-wrap: normal;
229
- white-space: nowrap;
230
- text-overflow: ellipsis;
231
- -o-text-overflow: ellipsis;
232
- overflow-x: hidden;
233
- }
234
-
235
- td.column-new-url .row-actions { /* However, the action links below the URL can wrap. */
236
- word-wrap: normal;
237
- white-space: normal;
238
- }
239
-
240
- .blc-link-editor {
241
- font-size: 1em;
242
- width: 95%;
243
- margin-left: 12px;
244
- margin-top: -1px;
245
- }
246
-
247
- .blc-url-editor-buttons {
248
- margin-left: 12px;
249
- margin-top: 2px;
250
- display: none;
251
- width: 95%;
252
- }
253
-
254
- img.waiting {
255
- float:right;
256
- padding:4px 8px 0;
257
- vertical-align:top;
258
- }
259
-
260
- td.column-link-text, td.column-new-link-text {
261
- cursor: pointer;
262
- }
263
-
264
- .blc-small-image {
265
- vertical-align: middle;
266
- }
267
-
268
-
269
- /* Inline editor */
270
-
271
- .blc-inline-editor label {
272
- display: block;
273
- margin: 0.2em 0;
274
- }
275
-
276
- .blc-inline-editor .blc-input-text-wrap {
277
- display: block;
278
- margin-left: 5em;
279
- }
280
-
281
- .blc-inline-editor .blc-input-text-wrap input[type="text"] {
282
- width: 100%;
283
- }
284
-
285
- .blc-inline-editor .blc-input-text-wrap textarea {
286
- width: 100%;
287
- }
288
-
289
-
290
- .blc-inline-editor label span.title {
291
- display: block;
292
- float: left;
293
- width: 5em;
294
- }
295
-
296
- .blc-inline-editor span.title {
297
- line-height: 1.8em;
298
- }
299
-
300
- .blc-inline-editor-content > h4:first-child {
301
- margin-top: 0.4em;
302
- }
303
-
304
- /* Inline editor: suggestion list */
305
- ul.blc-suggestion-list {
306
- list-style: disc outside;
307
- }
308
-
309
- ul.blc-suggestion-list li {
310
- margin-left: 1.5em;
311
- }
312
-
313
- .blc-suggestion-details {
314
- display: inline-block;
315
- width: 465px;
316
-
317
- overflow: hidden;
318
- white-space: nowrap;
319
- text-overflow: ellipsis;
320
- word-wrap: normal;
321
-
322
- vertical-align: top;
323
- }
324
-
325
- .blc-suggestion-list input.blc-use-url-button {
326
- float: right;
327
- max-width: 110px;
328
- margin-top: 10px;
329
- }
330
-
331
- .blc-suggestion-list code.blc-suggestion-url {
332
- display: block;
333
-
334
- overflow: hidden;
335
- text-overflow: ellipsis;
336
-
337
- white-space: nowrap;
338
- word-wrap: normal;
339
- }
340
-
341
- .blc-suggestion-list .blc-suggestion-name {
342
- display: block;
343
- }
344
-
345
-
346
- .blc-inline-editor-buttons {
347
- clear: both;
348
- margin: 0.5em 0 0;
349
- padding: 0.5em;
350
- }
351
-
352
- .blc-inline-editor-content {
353
- max-width: 600px;
354
- }
355
-
356
-
357
- /* Bulk edit form */
358
- #bulk-edit {
359
- display: none;
360
- }
361
-
362
- #bulk-edit-wrap {
363
- max-width: 600px;
364
- padding-left: 0.3em;
365
- }
366
-
367
- #bulk-edit fieldset {
368
- font-size: 12px;
369
- }
370
-
371
- #bulk-edit h4 {
372
- margin: 0.4em 0 0.8em;
373
- /*display: none;*/
374
- }
375
-
376
- #bulk-edit label {
377
- display: block;
378
- margin-bottom: 0.2em;
379
- margin-left: 0;
380
- margin-right: 0;
381
- margin-top: 0.2em;
382
- }
383
-
384
- #bulk-edit .title {
385
- display: block;
386
- float: left;
387
- width: 15%;
388
- font-size: 12px;
389
- line-height: 1.8em;
390
- }
391
-
392
- #bulk-edit input.text {
393
- display: block;
394
- width: 84%;
395
- }
396
-
397
- #bulk-edit-options label {
398
- float: left;
399
- margin-right: 2em;
400
- }
401
-
402
- #bulk-edit p.submit {
403
- padding-top: 0.5em;
404
- }
405
-
406
- /* Search form */
407
-
408
- .blc-search-container {
409
- background : white !important;
410
- border: 3px solid #EEEEEE;
411
- padding: 12px;
412
-
413
- border-radius: 6px;
414
- -moz-border-radius: 6px;
415
- -webkit-border-radius: 6px;
416
- }
417
-
418
- .blc-search-container .ui-dialog-titlebar {
419
- display: none;
420
- margin: 0;
421
- }
422
-
423
- #search-links-dialog {
424
- display: none;
425
- }
426
-
427
- #search-links-dialog label, #search-links-dialog input.text, #search-links-dialog select { display:block; }
428
-
429
- #search-links-dialog input.text,
430
- #search-links-dialog select{
431
- margin-bottom: 12px;
432
- width: 290px;
433
- }
434
-
435
- #search-links-dialog select#s_filter {
436
- width: auto;
437
- }
438
-
439
- #search-links-dialog fieldset {
440
- padding:0;
441
- border:0;
442
- margin-top:25px;
443
- }
444
-
445
- #blc-search-button-row {
446
- text-align: center;
447
- }
448
-
449
- #blc-search-button-row input {
450
- margin-left: 8px;
451
- margin-right: 8px;
452
- margin-top: 8px;
453
- }
454
-
455
- .blc-inline-form {
456
- display: inline;
457
- }
458
-
459
- div.search-box{
460
- float: right;
461
- margin-top: -5px;
462
- margin-right: 0;
463
- margin-bottom: 0;
464
- margin-left: 0;
465
- }
466
-
467
- #s_link_type optgroup {
468
- font-style: normal;
469
- font-size: 13px;
470
- }
471
-
472
- #s_link_type optgroup option {
473
- margin-left: 1em;
474
- }
475
-
476
- /* Filter-related styles */
477
- .base-filter-all .blc-dismiss-action {
478
- display: none;
479
- }
480
-
481
- /* Miscellaneous styles */
482
-
483
- #blc-more-plugins-link-wrap,
484
- #blc-plugin-news-link-wrap {
485
- background: #00C31F none;
486
- }
487
-
488
- #screen-meta-links #blc-more-plugins-link,
489
- #screen-meta-links #blc-plugin-news-link {
490
- font-weight: bold;
491
- color: #DEFFD8;
492
- text-shadow: none;
493
- }
494
-
495
- #screen-meta-links #blc-more-plugins-link-wrap a.show-settings:hover,
496
- #screen-meta-links #blc-plugin-news-link-wrap a.show-settings:hover
497
- {
498
- color: white;
499
  }
1
+ /* Link table layout */
2
+
3
+ table#blc-links {
4
+ width: 100%;
5
+ table-layout: fixed;
6
+ }
7
+
8
+ tr.blc-link-details {
9
+ display: none;
10
+ }
11
+
12
+ .blc-detail-container {
13
+ display: block;
14
+ width: 100%;
15
+ }
16
+
17
+ .blc-detail-block {
18
+ width: 50%;
19
+ }
20
+
21
+ /* Column headers */
22
+
23
+ th.column-new-url {
24
+ width: 33%;
25
+ }
26
+
27
+ th.column-status {
28
+ width: 12em;
29
+ }
30
+
31
+ th.column-new-link-text {
32
+
33
+ }
34
+
35
+ th.column-used-in {
36
+
37
+ }
38
+
39
+ th.column-source {
40
+ width: 33%;
41
+ }
42
+
43
+ th.column-link-text {
44
+ width: 24%;
45
+ }
46
+
47
+ th.column-url {
48
+ width: 35%;
49
+ }
50
+
51
+ th.column-last-checked {
52
+ width: 10em;
53
+ }
54
+
55
+ th.column-broken-for {
56
+ width: 10em;
57
+ }
58
+
59
+ th.column-instance-count {
60
+ width: 10em;
61
+ }
62
+
63
+ /* Cells */
64
+
65
+ td.column-new-url,
66
+ td.column-used-in
67
+ {
68
+ /*
69
+ overflow: hidden;
70
+ white-space: nowrap;
71
+ text-overflow: ellipsis;
72
+ -o-text-overflow: ellipsis;
73
+ */
74
+ }
75
+
76
+ td.column-new-url .row-actions,
77
+ td.column-url .row-actions
78
+ {
79
+ margin-left: 16px;
80
+ }
81
+
82
+ td.column-new-url .mini-status {
83
+ margin-left: 16px;
84
+ color: black;
85
+ }
86
+
87
+ table.mini-status {
88
+ border-spacing: 0;
89
+ }
90
+
91
+ /* Styles for broken links, redirects and other link states or types */
92
+
93
+ .blc-redirect .blc-link-url {
94
+ background-image: url("../images/blue_dot.png");
95
+ }
96
+
97
+ .link-status-error .blc-link-url {
98
+ background-image: url("../images/font-awesome/font-awesome-exclamation-sign.png");
99
+ }
100
+
101
+ .link-status-warning .blc-link-url {
102
+ background-image: url("../images/font-awesome/font-awesome-warning-sign.png");
103
+ }
104
+
105
+ .blc-excluded-link {
106
+ background-color: #E2E2E2;
107
+ }
108
+
109
+ .blc-permanently-broken {
110
+
111
+ }
112
+
113
+ .blc-permanently-broken-hl {
114
+ background-image: url("../images/red_highlight.png");
115
+ }
116
+
117
+
118
+ /* The "Status" column */
119
+ td.column-status {
120
+ cursor: pointer;
121
+ }
122
+
123
+ .mini-status, .mini-status th, .mini-status td {
124
+ border: 0;
125
+ font-size: 1em;
126
+ padding: 0;
127
+ color: gray;
128
+ }
129
+
130
+ .mini-status div {
131
+ display: inline-block;
132
+ }
133
+
134
+ .mini-status .status-text {
135
+ color: black;
136
+ }
137
+
138
+ .link-status-unknown td.column-status .http-code {
139
+ display: none;
140
+ }
141
+
142
+
143
+ /* Status colors */
144
+ .color-code-link-status .mini-status .http-code,
145
+ .color-code-link-status .mini-status .status-text
146
+ {
147
+ font-weight: bold;
148
+ }
149
+
150
+ .color-code-link-status .link-status-unknown td.column-status .status-text,
151
+ .color-code-link-status .link-status-unknown td.column-status .http-code
152
+ {
153
+ color: gray;
154
+ font-weight: normal;
155
+ }
156
+
157
+ .color-code-link-status .link-status-ok td.column-status .status-text,
158
+ .color-code-link-status .link-status-ok td.column-status .http-code
159
+ {
160
+ color: green;
161
+ }
162
+
163
+ .color-code-link-status .link-status-info td.column-status .status-text,
164
+ .color-code-link-status .link-status-info td.column-status .http-code
165
+ {
166
+ color: blue;
167
+ }
168
+
169
+ .color-code-link-status .link-status-warning td.column-status .status-text,
170
+ .color-code-link-status .link-status-warning td.column-status .http-code
171
+ {
172
+ color: #FF8C00; /*#FFA500*/
173
+ }
174
+
175
+ .color-code-link-status .link-status-error td.column-status .status-text,
176
+ .color-code-link-status .link-status-error td.column-status .http-code
177
+ {
178
+ color: red;
179
+ }
180
+
181
+
182
+ /* "Compact" view */
183
+
184
+ .compact td.column-url,
185
+ .compact td.column-status,
186
+ .compact td.column-link-text,
187
+ .compact td.column-used-in,
188
+ .compact td.column-new-url,
189
+ .compact td.column-source,
190
+ .compact td.column-new-link-text,
191
+ .compact td.column-redirect-url
192
+ {
193
+ overflow: hidden;
194
+ -o-text-overflow: ellipsis;
195
+ text-overflow: ellipsis;
196
+ white-space: nowrap;
197
+ word-wrap: normal;
198
+ }
199
+
200
+ .compact .link-last-checked,
201
+ .compact .link-broken-for,
202
+ .compact .link-text
203
+ {
204
+ display: none;
205
+ }
206
+
207
+
208
+ /* Only show the "Details" link in the compact view. */
209
+ #blc-links .column-status .row-actions {
210
+ display: none;
211
+ }
212
+ #blc-links.compact .column-status .row-actions {
213
+ display: block;
214
+ }
215
+
216
+ /* Misc table styles */
217
+
218
+ .blc-link-url {
219
+ padding-left: 16px;
220
+ overflow: hidden;
221
+
222
+ background-image: none;
223
+ background-position: left center;
224
+ background-repeat: no-repeat;
225
+ }
226
+
227
+ td.column-new-url { /* The URL never wraps */
228
+ word-wrap: normal;
229
+ white-space: nowrap;
230
+ text-overflow: ellipsis;
231
+ -o-text-overflow: ellipsis;
232
+ overflow-x: hidden;
233
+ }
234
+
235
+ td.column-new-url .row-actions { /* However, the action links below the URL can wrap. */
236
+ word-wrap: normal;
237
+ white-space: normal;
238
+ }
239
+
240
+ .blc-link-editor {
241
+ font-size: 1em;
242
+ width: 95%;
243
+ margin-left: 12px;
244
+ margin-top: -1px;
245
+ }
246
+
247
+ .blc-url-editor-buttons {
248
+ margin-left: 12px;
249
+ margin-top: 2px;
250
+ display: none;
251
+ width: 95%;
252
+ }
253
+
254
+ img.waiting {
255
+ float:right;
256
+ padding:4px 8px 0;
257
+ vertical-align:top;
258
+ }
259
+
260
+ td.column-link-text, td.column-new-link-text {
261
+ cursor: pointer;
262
+ }
263
+
264
+ .blc-small-image {
265
+ vertical-align: middle;
266
+ }
267
+
268
+
269
+ /* Inline editor */
270
+
271
+ .blc-inline-editor label {
272
+ display: block;
273
+ margin: 0.2em 0;
274
+ }
275
+
276
+ .blc-inline-editor .blc-input-text-wrap {
277
+ display: block;
278
+ margin-left: 5em;
279
+ }
280
+
281
+ .blc-inline-editor .blc-input-text-wrap input[type="text"] {
282
+ width: 100%;
283
+ }
284
+
285
+ .blc-inline-editor .blc-input-text-wrap textarea {
286
+ width: 100%;
287
+ }
288
+
289
+
290
+ .blc-inline-editor label span.title {
291
+ display: block;
292
+ float: left;
293
+ width: 5em;
294
+ }
295
+
296
+ .blc-inline-editor span.title {
297
+ line-height: 1.8em;
298
+ }
299
+
300
+ .blc-inline-editor-content > h4:first-child {
301
+ margin-top: 0.4em;
302
+ }
303
+
304
+ /* Inline editor: suggestion list */
305
+ ul.blc-suggestion-list {
306
+ list-style: disc outside;
307
+ }
308
+
309
+ ul.blc-suggestion-list li {
310
+ margin-left: 1.5em;
311
+ }
312
+
313
+ .blc-suggestion-details {
314
+ display: inline-block;
315
+ width: 465px;
316
+
317
+ overflow: hidden;
318
+ white-space: nowrap;
319
+ text-overflow: ellipsis;
320
+ word-wrap: normal;
321
+
322
+ vertical-align: top;
323
+ }
324
+
325
+ .blc-suggestion-list input.blc-use-url-button {
326
+ float: right;
327
+ max-width: 110px;
328
+ margin-top: 10px;
329
+ }
330
+
331
+ .blc-suggestion-list code.blc-suggestion-url {
332
+ display: block;
333
+
334
+ overflow: hidden;
335
+ text-overflow: ellipsis;
336
+
337
+ white-space: nowrap;
338
+ word-wrap: normal;
339
+ }
340
+
341
+ .blc-suggestion-list .blc-suggestion-name {
342
+ display: block;
343
+ }
344
+
345
+
346
+ .blc-inline-editor-buttons {
347
+ clear: both;
348
+ margin: 0.5em 0 0;
349
+ padding: 0.5em;
350
+ }
351
+
352
+ .blc-inline-editor-content {
353
+ max-width: 600px;
354
+ }
355
+
356
+
357
+ /* Bulk edit form */
358
+ #bulk-edit {
359
+ display: none;
360
+ }
361
+
362
+ #bulk-edit-wrap {
363
+ max-width: 600px;
364
+ padding-left: 0.3em;
365
+ }
366
+
367
+ #bulk-edit fieldset {
368
+ font-size: 12px;
369
+ }
370
+
371
+ #bulk-edit h4 {
372
+ margin: 0.4em 0 0.8em;
373
+ /*display: none;*/
374
+ }
375
+
376
+ #bulk-edit label {
377
+ display: block;
378
+ margin-bottom: 0.2em;
379
+ margin-left: 0;
380
+ margin-right: 0;
381
+ margin-top: 0.2em;
382
+ }
383
+
384
+ #bulk-edit .title {
385
+ display: block;
386
+ float: left;
387
+ width: 15%;
388
+ font-size: 12px;
389
+ line-height: 1.8em;
390
+ }
391
+
392
+ #bulk-edit input.text {
393
+ display: block;
394
+ width: 84%;
395
+ }
396
+
397
+ #bulk-edit-options label {
398
+ float: left;
399
+ margin-right: 2em;
400
+ }
401
+
402
+ #bulk-edit p.submit {
403
+ padding-top: 0.5em;
404
+ }
405
+
406
+ /* Search form */
407
+
408
+ .blc-search-container {
409
+ background : white !important;
410
+ border: 3px solid #EEEEEE;
411
+ padding: 12px;
412
+
413
+ border-radius: 6px;
414
+ -moz-border-radius: 6px;
415
+ -webkit-border-radius: 6px;
416
+ }
417
+
418
+ .blc-search-container .ui-dialog-titlebar {
419
+ display: none;
420
+ margin: 0;
421
+ }
422
+
423
+ #search-links-dialog {
424
+ display: none;
425
+ }
426
+
427
+ #search-links-dialog label, #search-links-dialog input.text, #search-links-dialog select { display:block; }
428
+
429
+ #search-links-dialog input.text,
430
+ #search-links-dialog select{
431
+ margin-bottom: 12px;
432
+ width: 290px;
433
+ }
434
+
435
+ #search-links-dialog select#s_filter {
436
+ width: auto;
437
+ }
438
+
439
+ #search-links-dialog fieldset {
440
+ padding:0;
441
+ border:0;
442
+ margin-top:25px;
443
+ }
444
+
445
+ #blc-search-button-row {
446
+ text-align: center;
447
+ }
448
+
449
+ #blc-search-button-row input {
450
+ margin-left: 8px;
451
+ margin-right: 8px;
452
+ margin-top: 8px;
453
+ }
454
+
455
+ .blc-inline-form {
456
+ display: inline;
457
+ }
458
+
459
+ div.search-box{
460
+ float: right;
461
+ margin-top: -5px;
462
+ margin-right: 0;
463
+ margin-bottom: 0;
464
+ margin-left: 0;
465
+ }
466
+
467
+ #s_link_type optgroup {
468
+ font-style: normal;
469
+ font-size: 13px;
470
+ }
471
+
472
+ #s_link_type optgroup option {
473
+ margin-left: 1em;
474
+ }
475
+
476
+ /* Filter-related styles */
477
+ .base-filter-all .blc-dismiss-action {
478
+ display: none;
479
+ }
480
+
481
+ /* Miscellaneous styles */
482
+
483
+ #blc-more-plugins-link-wrap,
484
+ #blc-plugin-news-link-wrap {
485
+ background: #00C31F none;
486
+ }
487
+
488
+ #screen-meta-links #blc-more-plugins-link,
489
+ #screen-meta-links #blc-plugin-news-link {
490
+ font-weight: bold;
491
+ color: #DEFFD8;
492
+ text-shadow: none;
493
+ }
494
+
495
+ #screen-meta-links #blc-more-plugins-link-wrap a.show-settings:hover,
496
+ #screen-meta-links #blc-plugin-news-link-wrap a.show-settings:hover
497
+ {
498
+ color: white;
499
  }
css/options-page.css CHANGED
@@ -1,243 +1,243 @@
1
- /*
2
- Sidebar
3
- */
4
-
5
- #blc-sidebar {
6
- clear: right;
7
- float: right;
8
- position: relative;
9
- width: 255px;
10
- }
11
-
12
- #blc-admin-content {
13
- clear: left;
14
- float: left;
15
- margin-right: -275px;
16
- width: 100%;
17
- }
18
-
19
- #blc-admin-content > * {
20
- margin-right: 267px;
21
- }
22
-
23
- #advertising {
24
- border-color: green !important;
25
- border-width: 2px;
26
- }
27
-
28
- #advertising h3 {
29
- color: green;
30
- }
31
-
32
- #advertising .inside {
33
- text-align: left;
34
- }
35
-
36
- .ws-ame-ad-copy {
37
- font-size: 1.2em;
38
- font-style: italic;
39
- }
40
- .ws-ame-ad-link {
41
- font-size: 1.1em;
42
- font-weight: bold;
43
- }
44
-
45
- #themefuse-ad .inside,
46
- #managewp-ad .inside,
47
- #embedplus-ad .inside
48
- {
49
- padding: 2px 0 0 0;
50
- margin: 0;
51
- text-align: center;
52
- }
53
-
54
- #embedplus-ad .inside {
55
- padding-top: 0;
56
- }
57
-
58
- #embedplus-ad {
59
- border-style: none;
60
- background-color: transparent;
61
- box-shadow: none;
62
- }
63
-
64
-
65
- #link_checker_options .form-table th {
66
- width: 25%;
67
- min-width: 110px;
68
- max-width: 200px;
69
- }
70
-
71
- #blc-debug-info-toggle {
72
- font-size: smaller;
73
- }
74
-
75
- .blc-debug-item-ok {
76
- background-color: #d7ffa2;
77
- }
78
- .blc-debug-item-warning {
79
- background-color: #fcffa2;
80
- }
81
- .blc-debug-item-error {
82
- background-color: #ffc4c4;
83
- }
84
-
85
- #blc-debug-info {
86
- display: none;
87
-
88
- text-align: left;
89
-
90
- border-width: 1px;
91
- border-color: gray;
92
- border-style: solid;
93
-
94
- border-spacing: 0;
95
- border-collapse: collapse;
96
- }
97
-
98
- #blc-debug-info th, #blc-debug-info td {
99
- padding: 6px;
100
- font-weight: normal;
101
- text-shadow: none;
102
-
103
- border-width: 1px ;
104
- border-color: silver;
105
- border-style: solid;
106
-
107
- border-collapse: collapse;
108
- }
109
-
110
- .blc-toggle-link {
111
- /*padding-left: 20px; */
112
- }
113
-
114
- .module-container {
115
- margin: 1em 0;
116
- font-size: 12px;
117
- line-height: 140%;
118
- }
119
-
120
- .module-extra-settings {
121
- margin-top: 0.5em;
122
- }
123
-
124
- .form-table td p:first-child, .form-table td .module-container:first-child {
125
- margin-top: 0.2em;
126
- }
127
-
128
- .module-requires-pro {
129
- color: gray;
130
- }
131
-
132
- #blc-tabs {
133
- margin-top: 0.5em;
134
- }
135
-
136
- /* Tab navigation */
137
- ul.ui-tabs-nav {
138
- margin-bottom: -1px;
139
- height: 31px;
140
- padding-left: 1.5em;
141
-
142
- overflow: hidden;
143
- white-space: nowrap;
144
- padding-right: 3.5em;
145
- }
146
-
147
- ul.ui-tabs-nav li {
148
- display: inline-block;
149
- height: 29px;
150
- margin: 0 0.5em 0 0;
151
-
152
- border: 1px solid #DFDFDF;
153
-
154
- background: none repeat scroll 0 0 #F4F4F4;
155
-
156
- border-top-right-radius: 6px;
157
- border-top-left-radius: 6px;
158
-
159
- -moz-border-radius-topright: 6px;
160
- -moz-border-radius-topleft: 6px;
161
-
162
- -webkit-border-top-right-radius: 6px;
163
- -webkit-border-top-left-radius: 6px;
164
-
165
- font-weight: bold;
166
- text-shadow: 0 1px 0 #FFFFFF;
167
-
168
- max-width: 20%;
169
- overflow: hidden;
170
- text-align: center;
171
- }
172
-
173
- #tab-button-which {
174
- max-width: 25%;
175
- }
176
-
177
- ul.ui-tabs-nav li.ui-tabs-selected,
178
- ul.ui-tabs-nav li.ui-tabs-active
179
- {
180
- background: white;
181
- color: black;
182
- border-bottom-color: white;
183
- }
184
-
185
- ul.ui-tabs-nav li a {
186
- display: inline-block;
187
- height: 17px;
188
- text-decoration: none;
189
- color: #C1C1C1;
190
- padding: 0.5em 1em 0.6em 1em;
191
- }
192
-
193
- ul.ui-tabs-nav li a:focus {
194
- outline: none;
195
- }
196
-
197
- ul.ui-tabs-nav li.ui-tabs-selected a,
198
- ul.ui-tabs-nav li.ui-tabs-active a {
199
- color: black;
200
- outline: none;
201
- }
202
-
203
- /* Tab panels */
204
-
205
- .ui-tabs .blc-section {
206
- border: 1px solid #DFDFDF;
207
- border-top-width: 1px;
208
-
209
- padding-bottom: 1em;
210
-
211
- background: white;
212
-
213
- border-radius: 6px;
214
- -moz-border-radius: 6px;
215
- -webkit-border-radius: 6px;
216
-
217
- border-top-right-radius: 6px;
218
- border-bottom-right-radius: 6px;
219
- border-bottom-left-radius: 6px;
220
-
221
- -moz-border-radius-topright: 6px;
222
- -moz-border-radius-bottomright: 6px;
223
- -moz-border-radius-bottomleft: 6px;
224
-
225
- -webkit-border-top-right-radius: 6px;
226
- -webkit-border-bottom-right-radius: 6px;
227
- -webkit-border-bottom-left-radius: 6px;
228
- }
229
-
230
- .blc-section table.form-table th {
231
- padding-left: 10px;
232
- }
233
-
234
- /* Right sidebar */
235
-
236
- #blc-settings-wrap .hndle {
237
- cursor: default;
238
- }
239
-
240
- /* Miscellaneous */
241
- td:target, label:target {
242
- background: #ffffaa;
243
  }
1
+ /*
2
+ Sidebar
3
+ */
4
+
5
+ #blc-sidebar {
6
+ clear: right;
7
+ float: right;
8
+ position: relative;
9
+ width: 255px;
10
+ }
11
+
12
+ #blc-admin-content {
13
+ clear: left;
14
+ float: left;
15
+ margin-right: -275px;
16
+ width: 100%;
17
+ }
18
+
19
+ #blc-admin-content > * {
20
+ margin-right: 267px;
21
+ }
22
+
23
+ #advertising {
24
+ border-color: green !important;
25
+ border-width: 2px;
26
+ }
27
+
28
+ #advertising h3 {
29
+ color: green;
30
+ }
31
+
32
+ #advertising .inside {
33
+ text-align: left;
34
+ }
35
+
36
+ .ws-ame-ad-copy {
37
+ font-size: 1.2em;
38
+ font-style: italic;
39
+ }
40
+ .ws-ame-ad-link {
41
+ font-size: 1.1em;
42
+ font-weight: bold;
43
+ }
44
+
45
+ #themefuse-ad .inside,
46
+ #managewp-ad .inside,
47
+ #embedplus-ad .inside
48
+ {
49
+ padding: 2px 0 0 0;
50
+ margin: 0;
51
+ text-align: center;
52
+ }
53
+
54
+ #embedplus-ad .inside {
55
+ padding-top: 0;
56
+ }
57
+
58
+ #embedplus-ad {
59
+ border-style: none;
60
+ background-color: transparent;
61
+ box-shadow: none;
62
+ }
63
+
64
+
65
+ #link_checker_options .form-table th {
66
+ width: 25%;
67
+ min-width: 110px;
68
+ max-width: 200px;
69
+ }
70
+
71
+ #blc-debug-info-toggle {
72
+ font-size: smaller;
73
+ }
74
+
75
+ .blc-debug-item-ok {
76
+ background-color: #d7ffa2;
77
+ }
78
+ .blc-debug-item-warning {
79
+ background-color: #fcffa2;
80
+ }
81
+ .blc-debug-item-error {
82
+ background-color: #ffc4c4;
83
+ }
84
+
85
+ #blc-debug-info {
86
+ display: none;
87
+
88
+ text-align: left;
89
+
90
+ border-width: 1px;
91
+ border-color: gray;
92
+ border-style: solid;
93
+
94
+ border-spacing: 0;
95
+ border-collapse: collapse;
96
+ }
97
+
98
+ #blc-debug-info th, #blc-debug-info td {
99
+ padding: 6px;
100
+ font-weight: normal;
101
+ text-shadow: none;
102
+
103
+ border-width: 1px ;
104
+ border-color: silver;
105
+ border-style: solid;
106
+
107
+ border-collapse: collapse;
108
+ }
109
+
110
+ .blc-toggle-link {
111
+ /*padding-left: 20px; */
112
+ }
113
+
114
+ .module-container {
115
+ margin: 1em 0;
116
+ font-size: 12px;
117
+ line-height: 140%;
118
+ }
119
+
120
+ .module-extra-settings {
121
+ margin-top: 0.5em;
122
+ }
123
+
124
+ .form-table td p:first-child, .form-table td .module-container:first-child {
125
+ margin-top: 0.2em;
126
+ }
127
+
128
+ .module-requires-pro {
129
+ color: gray;
130
+ }
131
+
132
+ #blc-tabs {
133
+ margin-top: 0.5em;
134
+ }
135
+
136
+ /* Tab navigation */
137
+ ul.ui-tabs-nav {
138
+ margin-bottom: -1px;
139
+ height: 31px;
140
+ padding-left: 1.5em;
141
+
142
+ overflow: hidden;
143
+ white-space: nowrap;
144
+ padding-right: 3.5em;
145
+ }
146
+
147
+ ul.ui-tabs-nav li {
148
+ display: inline-block;
149
+ height: 29px;
150
+ margin: 0 0.5em 0 0;
151
+
152
+ border: 1px solid #DFDFDF;
153
+
154
+ background: none repeat scroll 0 0 #F4F4F4;
155
+
156
+ border-top-right-radius: 6px;
157
+ border-top-left-radius: 6px;
158
+
159
+ -moz-border-radius-topright: 6px;
160
+ -moz-border-radius-topleft: 6px;
161
+
162
+ -webkit-border-top-right-radius: 6px;
163
+ -webkit-border-top-left-radius: 6px;
164
+
165
+ font-weight: bold;
166
+ text-shadow: 0 1px 0 #FFFFFF;
167
+
168
+ max-width: 20%;
169
+ overflow: hidden;
170
+ text-align: center;
171
+ }
172
+
173
+ #tab-button-which {
174
+ max-width: 25%;
175
+ }
176
+
177
+ ul.ui-tabs-nav li.ui-tabs-selected,
178
+ ul.ui-tabs-nav li.ui-tabs-active
179
+ {
180
+ background: white;
181
+ color: black;
182
+ border-bottom-color: white;
183
+ }
184
+
185
+ ul.ui-tabs-nav li a {
186
+ display: inline-block;
187
+ height: 17px;
188
+ text-decoration: none;
189
+ color: #C1C1C1;
190
+ padding: 0.5em 1em 0.6em 1em;
191
+ }
192
+
193
+ ul.ui-tabs-nav li a:focus {
194
+ outline: none;
195
+ }
196
+
197
+ ul.ui-tabs-nav li.ui-tabs-selected a,
198
+ ul.ui-tabs-nav li.ui-tabs-active a {
199
+ color: black;
200
+ outline: none;
201
+ }
202
+
203
+ /* Tab panels */
204
+
205
+ .ui-tabs .blc-section {
206
+ border: 1px solid #DFDFDF;
207
+ border-top-width: 1px;
208
+
209
+ padding-bottom: 1em;
210
+
211
+ background: white;
212
+
213
+ border-radius: 6px;
214
+ -moz-border-radius: 6px;
215
+ -webkit-border-radius: 6px;
216
+
217
+ border-top-right-radius: 6px;
218
+ border-bottom-right-radius: 6px;
219
+ border-bottom-left-radius: 6px;
220
+
221
+ -moz-border-radius-topright: 6px;
222
+ -moz-border-radius-bottomright: 6px;
223
+ -moz-border-radius-bottomleft: 6px;
224
+
225
+ -webkit-border-top-right-radius: 6px;
226
+ -webkit-border-bottom-right-radius: 6px;
227
+ -webkit-border-bottom-left-radius: 6px;
228
+ }
229
+
230
+ .blc-section table.form-table th {
231
+ padding-left: 10px;
232
+ }
233
+
234
+ /* Right sidebar */
235
+
236
+ #blc-settings-wrap .hndle {
237
+ cursor: default;
238
+ }
239
+
240
+ /* Miscellaneous */
241
+ td:target, label:target {
242
+ background: #ffffaa;
243
  }
idn/LICENCE CHANGED
File without changes
idn/ReadMe.txt CHANGED
File without changes
idn/idna_convert.class.php CHANGED
File without changes
idn/transcode_wrapper.php CHANGED
File without changes
idn/uctc.php CHANGED
File without changes
images/blue_dot.png CHANGED
File without changes
images/dailymotion-embed.png CHANGED
File without changes
images/font-awesome/font-awesome-code.png CHANGED
File without changes
images/font-awesome/font-awesome-comment-alt.png CHANGED
File without changes
images/font-awesome/font-awesome-exclamation-sign.png CHANGED
File without changes
images/font-awesome/font-awesome-link.png CHANGED
File without changes
images/font-awesome/font-awesome-picture.png CHANGED
File without changes
images/font-awesome/font-awesome-user.png CHANGED
File without changes
images/font-awesome/font-awesome-warning-sign.png CHANGED
File without changes
images/font-awesome/readme.txt CHANGED
@@ -1,10 +1,10 @@
1
- This directory contains icons from the Font Awesome 3.2.1 icon font:
2
- http://fortawesome.github.io/Font-Awesome/
3
-
4
- The Font Awesome font is licensed under SIL OFL 1.1:
5
- http://scripts.sil.org/OFL
6
-
7
- ------------------------------------------------------------------------------
8
-
9
- The icons have been converted to PNG and in some cases minor adjustments have
10
- been made, such as adding a background colour or a drop shadow.
1
+ This directory contains icons from the Font Awesome 3.2.1 icon font:
2
+ http://fortawesome.github.io/Font-Awesome/
3
+
4
+ The Font Awesome font is licensed under SIL OFL 1.1:
5
+ http://scripts.sil.org/OFL
6
+
7
+ ------------------------------------------------------------------------------
8
+
9
+ The icons have been converted to PNG and in some cases minor adjustments have
10
+ been made, such as adding a background colour or a drop shadow.
images/googlevideo-embed.png CHANGED
File without changes
images/red_highlight.png CHANGED
File without changes
images/vimeo-embed.png CHANGED
File without changes
images/youtube-embed.png CHANGED
File without changes
images/youtube-iframe.png CHANGED
File without changes
images/youtube-playlist-embed.png CHANGED
File without changes
includes/activation.php CHANGED
@@ -1,114 +1,114 @@
1
- <?php
2
-
3
- global $blclog, $blc_config_manager, $wpdb;
4
- $queryCnt = $wpdb->num_queries;
5
-
6
- //Completing the installation/upgrade is required for the plugin to work, so make sure
7
- //the script doesn't get aborted by (for example) the browser timing out.
8
- set_time_limit(300); //5 minutes should be plenty, anything more would probably indicate an infinite loop or a deadlock
9
- ignore_user_abort(true);
10
-
11
- //Log installation progress to a DB option
12
- $blclog = new blcCachedOptionLogger('blc_installation_log');
13
- register_shutdown_function(array(&$blclog, 'save')); //Make sure the log is saved even if the plugin crashes
14
-
15
- $blclog->clear();
16
- $blclog->info( sprintf('Plugin activated at %s.', date_i18n('Y-m-d H:i:s')) );
17
- $activation_start = microtime(true);
18
-
19
- //Reset the "installation_complete" flag
20
- $blc_config_manager->options['installation_complete'] = false;
21
- $blc_config_manager->options['installation_flag_cleared_on'] = date('c') . ' (' . microtime(true) . ')';
22
- //Note the time of the first installation (not very accurate, but still useful)
23
- if ( empty($blc_config_manager->options['first_installation_timestamp']) ){
24
- $blc_config_manager->options['first_installation_timestamp'] = time();
25
- }
26
- $blc_config_manager->save_options();
27
- $blclog->info('Installation/update begins.');
28
-
29
- //Load the base classes and utilities
30
- require_once BLC_DIRECTORY . '/includes/links.php';
31
- require_once BLC_DIRECTORY . '/includes/link-query.php';
32
- require_once BLC_DIRECTORY . '/includes/instances.php';
33
- require_once BLC_DIRECTORY . '/includes/utility-class.php';
34
-
35
- //Load the module subsystem
36
- require_once BLC_DIRECTORY . '/includes/modules.php';
37
- $moduleManager = blcModuleManager::getInstance();
38
-
39
- //If upgrading, activate/deactivate custom field and comment containers based on old ver. settings
40
- if ( isset($blc_config_manager->options['check_comment_links']) ){
41
- if ( !$blc_config_manager->options['check_comment_links'] ){
42
- $moduleManager->deactivate('comment');
43
- }
44
- unset($blc_config_manager->options['check_comment_links']);
45
- }
46
- if ( empty($blc_config_manager->options['custom_fields']) ){
47
- $moduleManager->deactivate('custom_field');
48
- }
49
- if ( empty($blc_config_manager->options['acf_fields']) ){
50
- $moduleManager->deactivate('acf_field');
51
- }
52
-
53
- //Prepare the database.
54
- $blclog->info('Upgrading the database...');
55
- $upgrade_start = microtime(true);
56
- require_once BLC_DIRECTORY . '/includes/admin/db-upgrade.php';
57
- blcDatabaseUpgrader::upgrade_database();
58
- $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $upgrade_start));
59
-
60
- //Remove invalid DB entries
61
- $blclog->info('Cleaning up the database...');
62
- $cleanup_start = microtime(true);
63
- blc_cleanup_database();
64
- $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $cleanup_start));
65
-
66
- //Notify modules that the plugin has been activated. This will cause container
67
- //modules to create and update synch. records for all new/modified posts and other items.
68
- $blclog->info('Notifying modules...');
69
- $notification_start = microtime(true);
70
- $moduleManager->plugin_activated();
71
- blc_got_unsynched_items();
72
- $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $notification_start));
73
-
74
- //Turn off load limiting if it's not available on this server.
75
- $blclog->info('Updating server load limit settings...');
76
- $load = blcUtility::get_server_load();
77
- if ( empty($load) ){
78
- $blc_config_manager->options['enable_load_limit'] = false;
79
- $blclog->info('Disable load limit. Cannot retrieve current load average.');
80
- } elseif ( $blc_config_manager->options['enable_load_limit'] && !isset($blc_config_manager->options['server_load_limit']) ) {
81
- $fifteen_minutes = floatval(end($load));
82
- $default_load_limit = round(max(min($fifteen_minutes * 2, $fifteen_minutes + 2), 4));
83
- $blc_config_manager->options['server_load_limit'] = $default_load_limit;
84
-
85
- $blclog->info(sprintf(
86
- 'Set server load limit to %.2f. Current load average is %.2f',
87
- $default_load_limit,
88
- $fifteen_minutes
89
- ));
90
- }
91
-
92
- //And optimize my DB tables, too (for good measure)
93
- $blclog->info('Optimizing the database...');
94
- $optimize_start = microtime(true);
95
- blcUtility::optimize_database();
96
- $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $optimize_start));
97
-
98
- $blclog->info('Completing installation...');
99
- $blc_config_manager->options['installation_complete'] = true;
100
- $blc_config_manager->options['installation_flag_set_on'] = date('c') . ' (' . microtime(true) . ')';
101
- if ( $blc_config_manager->save_options() ){
102
- $blclog->info('Configuration saved.');
103
- } else {
104
- $blclog->error('Error saving plugin configuration!');
105
- };
106
-
107
- $blclog->info(sprintf(
108
- 'Installation/update completed at %s with %d queries executed.',
109
- date_i18n('Y-m-d H:i:s'),
110
- $wpdb->num_queries - $queryCnt
111
- ));
112
- $blclog->info(sprintf('Total time: %.3f seconds', microtime(true) - $activation_start));
113
- $blclog->save();
114
-
1
+ <?php
2
+
3
+ global $blclog, $blc_config_manager, $wpdb;
4
+ $queryCnt = $wpdb->num_queries;
5
+
6
+ //Completing the installation/upgrade is required for the plugin to work, so make sure
7
+ //the script doesn't get aborted by (for example) the browser timing out.
8
+ set_time_limit(300); //5 minutes should be plenty, anything more would probably indicate an infinite loop or a deadlock
9
+ ignore_user_abort(true);
10
+
11
+ //Log installation progress to a DB option
12
+ $blclog = new blcCachedOptionLogger('blc_installation_log');
13
+ register_shutdown_function(array(&$blclog, 'save')); //Make sure the log is saved even if the plugin crashes
14
+
15
+ $blclog->clear();
16
+ $blclog->info( sprintf('Plugin activated at %s.', date_i18n('Y-m-d H:i:s')) );
17
+ $activation_start = microtime(true);
18
+
19
+ //Reset the "installation_complete" flag
20
+ $blc_config_manager->options['installation_complete'] = false;
21
+ $blc_config_manager->options['installation_flag_cleared_on'] = date('c') . ' (' . microtime(true) . ')';
22
+ //Note the time of the first installation (not very accurate, but still useful)
23
+ if ( empty($blc_config_manager->options['first_installation_timestamp']) ){
24
+ $blc_config_manager->options['first_installation_timestamp'] = time();
25
+ }
26
+ $blc_config_manager->save_options();
27
+ $blclog->info('Installation/update begins.');
28
+
29
+ //Load the base classes and utilities
30
+ require_once BLC_DIRECTORY . '/includes/links.php';
31
+ require_once BLC_DIRECTORY . '/includes/link-query.php';
32
+ require_once BLC_DIRECTORY . '/includes/instances.php';
33
+ require_once BLC_DIRECTORY . '/includes/utility-class.php';
34
+
35
+ //Load the module subsystem
36
+ require_once BLC_DIRECTORY . '/includes/modules.php';
37
+ $moduleManager = blcModuleManager::getInstance();
38
+
39
+ //If upgrading, activate/deactivate custom field and comment containers based on old ver. settings
40
+ if ( isset($blc_config_manager->options['check_comment_links']) ){
41
+ if ( !$blc_config_manager->options['check_comment_links'] ){
42
+ $moduleManager->deactivate('comment');
43
+ }
44
+ unset($blc_config_manager->options['check_comment_links']);
45
+ }
46
+ if ( empty($blc_config_manager->options['custom_fields']) ){
47
+ $moduleManager->deactivate('custom_field');
48
+ }
49
+ if ( empty($blc_config_manager->options['acf_fields']) ){
50
+ $moduleManager->deactivate('acf_field');
51
+ }
52
+
53
+ //Prepare the database.
54
+ $blclog->info('Upgrading the database...');
55
+ $upgrade_start = microtime(true);
56
+ require_once BLC_DIRECTORY . '/includes/admin/db-upgrade.php';
57
+ blcDatabaseUpgrader::upgrade_database();
58
+ $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $upgrade_start));
59
+
60
+ //Remove invalid DB entries
61
+ $blclog->info('Cleaning up the database...');
62
+ $cleanup_start = microtime(true);
63
+ blc_cleanup_database();
64
+ $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $cleanup_start));
65
+
66
+ //Notify modules that the plugin has been activated. This will cause container
67
+ //modules to create and update synch. records for all new/modified posts and other items.
68
+ $blclog->info('Notifying modules...');
69
+ $notification_start = microtime(true);
70
+ $moduleManager->plugin_activated();
71
+ blc_got_unsynched_items();
72
+ $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $notification_start));
73
+
74
+ //Turn off load limiting if it's not available on this server.
75
+ $blclog->info('Updating server load limit settings...');
76
+ $load = blcUtility::get_server_load();
77
+ if ( empty($load) ){
78
+ $blc_config_manager->options['enable_load_limit'] = false;
79
+ $blclog->info('Disable load limit. Cannot retrieve current load average.');
80
+ } elseif ( $blc_config_manager->options['enable_load_limit'] && !isset($blc_config_manager->options['server_load_limit']) ) {
81
+ $fifteen_minutes = floatval(end($load));
82
+ $default_load_limit = round(max(min($fifteen_minutes * 2, $fifteen_minutes + 2), 4));
83
+ $blc_config_manager->options['server_load_limit'] = $default_load_limit;
84
+
85
+ $blclog->info(sprintf(
86
+ 'Set server load limit to %.2f. Current load average is %.2f',
87
+ $default_load_limit,
88
+ $fifteen_minutes
89
+ ));
90
+ }
91
+
92
+ //And optimize my DB tables, too (for good measure)
93
+ $blclog->info('Optimizing the database...');
94
+ $optimize_start = microtime(true);
95
+ blcUtility::optimize_database();
96
+ $blclog->info(sprintf('--- Total: %.3f seconds', microtime(true) - $optimize_start));
97
+
98
+ $blclog->info('Completing installation...');
99
+ $blc_config_manager->options['installation_complete'] = true;
100
+ $blc_config_manager->options['installation_flag_set_on'] = date('c') . ' (' . microtime(true) . ')';
101
+ if ( $blc_config_manager->save_options() ){
102
+ $blclog->info('Configuration saved.');
103
+ } else {
104
+ $blclog->error('Error saving plugin configuration!');
105
+ };
106
+
107
+ $blclog->info(sprintf(
108
+ 'Installation/update completed at %s with %d queries executed.',
109
+ date_i18n('Y-m-d H:i:s'),
110
+ $wpdb->num_queries - $queryCnt
111
+ ));
112
+ $blclog->info(sprintf('Total time: %.3f seconds', microtime(true) - $activation_start));
113
+ $blclog->save();
114
+
includes/admin/db-schema.php CHANGED
@@ -1,96 +1,96 @@
1
- <?php
2
-
3
- if( !function_exists('blc_get_db_schema') ){
4
-
5
- function blc_get_db_schema(){
6
- global $wpdb;
7
-
8
- //Use the character set and collation that's configured for WP tables
9
- $charset_collate = '';
10
- if ( !empty($wpdb->charset) ){
11
- //Some German installs use "utf-8" (invalid) instead of "utf8" (valid). None of
12
- //the charset ids supported by MySQL contain dashes, so we can safely strip them.
13
- //See http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html
14
- $charset = str_replace('-', '', $wpdb->charset);
15
-
16
- $charset_collate = "DEFAULT CHARACTER SET {$charset}";
17
- }
18
- if ( !empty($wpdb->collate) ){
19
- $charset_collate .= " COLLATE {$wpdb->collate}";
20
- }
21
-
22
- $blc_db_schema = <<<EOM
23
-
24
- CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_filters` (
25
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
26
- `name` varchar(100) NOT NULL,
27
- `params` text NOT NULL,
28
-
29
- PRIMARY KEY (`id`)
30
- ) {$charset_collate};
31
-
32
- CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_instances` (
33
- `instance_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
34
- `link_id` int(10) unsigned NOT NULL,
35
- `container_id` int(10) unsigned NOT NULL,
36
- `container_type` varchar(40) NOT NULL DEFAULT 'post',
37
- `link_text` text NOT NULL DEFAULT '',
38
- `parser_type` varchar(40) NOT NULL DEFAULT 'link',
39
- `container_field` varchar(250) NOT NULL DEFAULT '',
40
- `link_context` varchar(250) NOT NULL DEFAULT '',
41
- `raw_url` text NOT NULL,
42
-
43
- PRIMARY KEY (`instance_id`),
44
- KEY `link_id` (`link_id`),
45
- KEY `source_id` (`container_type`, `container_id`),
46
- KEY `parser_type` (`parser_type`)
47
- ) {$charset_collate};
48
-
49
- CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_links` (
50
- `link_id` int(20) unsigned NOT NULL AUTO_INCREMENT,
51
- `url` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
52
- `first_failure` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
53
- `last_check` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
54
- `last_success` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
55
- `last_check_attempt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
56
- `check_count` int(4) unsigned NOT NULL DEFAULT '0',
57
- `final_url` text CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
58
- `redirect_count` smallint(5) unsigned NOT NULL DEFAULT '0',
59
- `log` text NOT NULL,
60
- `http_code` smallint(6) NOT NULL DEFAULT '0',
61
- `status_code` varchar(100) DEFAULT '',
62
- `status_text` varchar(250) DEFAULT '',
63
- `request_duration` float NOT NULL DEFAULT '0',
64
- `timeout` tinyint(1) unsigned NOT NULL DEFAULT '0',
65
- `broken` tinyint(1) unsigned NOT NULL DEFAULT '0',
66
- `warning` tinyint(1) unsigned NOT NULL DEFAULT '0',
67
- `may_recheck` tinyint(1) NOT NULL DEFAULT '1',
68
- `being_checked` tinyint(1) NOT NULL DEFAULT '0',
69
-
70
- `result_hash` varchar(200) NOT NULL DEFAULT '',
71
- `false_positive` tinyint(1) NOT NULL DEFAULT '0',
72
- `dismissed` tinyint(1) NOT NULL DEFAULT '0',
73
-
74
- PRIMARY KEY (`link_id`),
75
- KEY `url` (`url`(150)),
76
- KEY `final_url` (`final_url`(150)),
77
- KEY `http_code` (`http_code`),
78
- KEY `broken` (`broken`)
79
- ) {$charset_collate};
80
-
81
- CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_synch` (
82
- `container_id` int(20) unsigned NOT NULL,
83
- `container_type` varchar(40) NOT NULL,
84
- `synched` tinyint(2) unsigned NOT NULL,
85
- `last_synch` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
86
-
87
- PRIMARY KEY (`container_type`,`container_id`),
88
- KEY `synched` (`synched`)
89
- ) {$charset_collate};
90
-
91
- EOM;
92
-
93
- return $blc_db_schema;
94
- }
95
-
96
- }
1
+ <?php
2
+
3
+ if( !function_exists('blc_get_db_schema') ){
4
+
5
+ function blc_get_db_schema(){
6
+ global $wpdb;
7
+
8
+ //Use the character set and collation that's configured for WP tables
9
+ $charset_collate = '';
10
+ if ( !empty($wpdb->charset) ){
11
+ //Some German installs use "utf-8" (invalid) instead of "utf8" (valid). None of
12
+ //the charset ids supported by MySQL contain dashes, so we can safely strip them.
13
+ //See http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html
14
+ $charset = str_replace('-', '', $wpdb->charset);
15
+
16
+ $charset_collate = "DEFAULT CHARACTER SET {$charset}";
17
+ }
18
+ if ( !empty($wpdb->collate) ){
19
+ $charset_collate .= " COLLATE {$wpdb->collate}";
20
+ }
21
+
22
+ $blc_db_schema = <<<EOM
23
+
24
+ CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_filters` (
25
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
26
+ `name` varchar(100) NOT NULL,
27
+ `params` text NOT NULL,
28
+
29
+ PRIMARY KEY (`id`)
30
+ ) {$charset_collate};
31
+
32
+ CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_instances` (
33
+ `instance_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
34
+ `link_id` int(10) unsigned NOT NULL,
35
+ `container_id` int(10) unsigned NOT NULL,
36
+ `container_type` varchar(40) NOT NULL DEFAULT 'post',
37
+ `link_text` text NOT NULL DEFAULT '',
38
+ `parser_type` varchar(40) NOT NULL DEFAULT 'link',
39
+ `container_field` varchar(250) NOT NULL DEFAULT '',
40
+ `link_context` varchar(250) NOT NULL DEFAULT '',
41
+ `raw_url` text NOT NULL,
42
+
43
+ PRIMARY KEY (`instance_id`),
44
+ KEY `link_id` (`link_id`),
45
+ KEY `source_id` (`container_type`, `container_id`),
46
+ KEY `parser_type` (`parser_type`)
47
+ ) {$charset_collate};
48
+
49
+ CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_links` (
50
+ `link_id` int(20) unsigned NOT NULL AUTO_INCREMENT,
51
+ `url` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
52
+ `first_failure` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
53
+ `last_check` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
54
+ `last_success` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
55
+ `last_check_attempt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
56
+ `check_count` int(4) unsigned NOT NULL DEFAULT '0',
57
+ `final_url` text CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
58
+ `redirect_count` smallint(5) unsigned NOT NULL DEFAULT '0',
59
+ `log` text NOT NULL,
60
+ `http_code` smallint(6) NOT NULL DEFAULT '0',
61
+ `status_code` varchar(100) DEFAULT '',
62
+ `status_text` varchar(250) DEFAULT '',
63
+ `request_duration` float NOT NULL DEFAULT '0',
64
+ `timeout` tinyint(1) unsigned NOT NULL DEFAULT '0',
65
+ `broken` tinyint(1) unsigned NOT NULL DEFAULT '0',
66
+ `warning` tinyint(1) unsigned NOT NULL DEFAULT '0',
67
+ `may_recheck` tinyint(1) NOT NULL DEFAULT '1',
68
+ `being_checked` tinyint(1) NOT NULL DEFAULT '0',
69
+
70
+ `result_hash` varchar(200) NOT NULL DEFAULT '',
71
+ `false_positive` tinyint(1) NOT NULL DEFAULT '0',
72
+ `dismissed` tinyint(1) NOT NULL DEFAULT '0',
73
+
74
+ PRIMARY KEY (`link_id`),
75
+ KEY `url` (`url`(150)),
76
+ KEY `final_url` (`final_url`(150)),
77
+ KEY `http_code` (`http_code`),
78
+ KEY `broken` (`broken`)
79
+ ) {$charset_collate};
80
+
81
+ CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}blc_synch` (
82
+ `container_id` int(20) unsigned NOT NULL,
83
+ `container_type` varchar(40) NOT NULL,
84
+ `synched` tinyint(2) unsigned NOT NULL,
85
+ `last_synch` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
86
+
87
+ PRIMARY KEY (`container_type`,`container_id`),
88
+ KEY `synched` (`synched`)
89
+ ) {$charset_collate};
90
+
91
+ EOM;
92
+
93
+ return $blc_db_schema;
94
+ }
95
+
96
+ }
includes/admin/db-upgrade.php CHANGED
@@ -1,585 +1,585 @@
1
- <?php
2
-
3
- class blcDatabaseUpgrader {
4
-
5
- /**
6
- * Create and/or upgrade the plugin's database tables.
7
- *
8
- * @return bool
9
- */
10
- public static function upgrade_database(){
11
- global $blclog;
12
-
13
- $conf = blc_get_configuration();
14
- $current = $conf->options['current_db_version'];
15
-
16
- if ( ($current != 0) && ( $current < 4 ) ){
17
- //The 4th DB version makes a lot of backwards-incompatible changes to the main
18
- //BLC tables, so instead of upgrading we just throw them away and recreate.
19
- if ( !blcDatabaseUpgrader::drop_tables() ){
20
- return false;
21
- };
22
- $current = 0;
23
- }
24
-
25
- //Create/update the plugin's tables
26
- if ( !blcDatabaseUpgrader::make_schema_current() ) {
27
- return false;
28
- }
29
-
30
- if ( $current != 0 ){
31
-
32
- if ( $current < 5 ){
33
- blcDatabaseUpgrader::upgrade_095();
34
- }
35
-
36
- }
37
-
38
- $conf->options['current_db_version'] = BLC_DATABASE_VERSION;
39
- $conf->save_options();
40
- $blclog->info('Database successfully upgraded.');
41
-
42
- return true;
43
- }
44
-
45
- /**
46
- * Create or update the plugin's DB tables.
47
- *
48
- * @return bool
49
- */
50
- static function make_schema_current(){
51
- global $blclog;
52
-
53
- $start = microtime(true);
54
- if ( !function_exists('blc_get_db_schema') ){
55
- require 'db-schema.php';
56
- }
57
- list($dummy, $query_log) = blcTableDelta::delta(blc_get_db_schema());
58
-
59
- $have_errors = false;
60
- foreach($query_log as $item){
61
- if ( $item['success'] ){
62
- $blclog->info(' [OK] ' . $item['query'] . sprintf(' (%.3f seconds)', $item['query_time']));
63
- } else {
64
- $blclog->error(' [ ] ' . $item['query']);
65
- $blclog->error(' Database error : ' . $item['error_message']);
66
- $have_errors = true;
67
- }
68
- }
69
- $blclog->info(sprintf('Schema update took %.3f seconds', microtime(true) - $start));
70
-
71
- $blclog->info('Database schema updated.');
72
- return !$have_errors;
73
- }
74
-
75
- /**
76
- * Drop the plugin's tables.
77
- *
78
- * @return bool
79
- */
80
- static function drop_tables(){
81
- global $wpdb, $blclog; /** @var wpdb $wpdb */
82
-
83
- $blclog->info('Deleting the plugin\'s database tables');
84
- $tables = array(
85
- $wpdb->prefix . 'blc_linkdata',
86
- $wpdb->prefix . 'blc_postdata',
87
- $wpdb->prefix . 'blc_instances',
88
- $wpdb->prefix . 'blc_synch',
89
- $wpdb->prefix . 'blc_links',
90
- );
91
-
92
- $q = "DROP TABLE IF EXISTS " . implode(', ', $tables);
93
- $rez = $wpdb->query( $q );
94
-
95
- if ( $rez === false ){
96
- $error = sprintf(
97
- __("Failed to delete old DB tables. Database error : %s", 'broken-link-checker'),
98
- $wpdb->last_error
99
- );
100
-
101
- $blclog->error($error);
102
- /*
103
- //FIXME: In very rare cases, DROP TABLE IF EXISTS throws an error when the table(s) don't exist.
104
- return false;
105
- //*/
106
- }
107
- $blclog->info('Done.');
108
-
109
- return true;
110
- }
111
-
112
- static function upgrade_095($trigger_errors = false){
113
- global $wpdb; /** @var wpdb $wpdb */
114
-
115
- //Prior to 0.9.5 all supported post types were internally represented using
116
- //a common 'post' container type. The current version creates a unique container
117
- //type to each post type.
118
-
119
- //Update synch records and instances to reflect this change
120
- $q = "
121
- UPDATE
122
- {$wpdb->prefix}blc_synch AS synch
123
- LEFT JOIN {$wpdb->posts} AS posts ON (posts.ID = synch.container_id)
124
- SET
125
- synch.container_type = posts.post_type
126
- WHERE
127
- synch.container_type = 'post' AND posts.post_type IS NOT NULL";
128
- $wpdb->query($q);
129
-
130
- $q = "
131
- UPDATE
132
- {$wpdb->prefix}blc_instances AS instances
133
- LEFT JOIN {$wpdb->posts} AS posts ON (posts.ID = instances.container_id)
134
- SET
135
- instances.container_type = posts.post_type
136
- WHERE
137
- instances.container_type = 'post' AND posts.post_type IS NOT NULL";
138
- $wpdb->query($q);
139
- }
140
-
141
- }
142
-
143
- class blcTableDelta {
144
-
145
- /**
146
- * Parse one or more CREATE TABLE queries and generate a list of SQL queries that need
147
- * to be executed to make the current database schema match those queries. Will also
148
- * execute those queries by default.
149
- *
150
- * This function returns an array with two items. The first is a list of human-readable
151
- * messages explaining what database changes were/would be made. The second array item
152
- * is an array of the generated SQL queries and (if $execute was True) their results.
153
- *
154
- * Each item of this second array is itself an associative array with these keys :
155
- * 'query' - the generated query.
156
- * 'success' - True if the query was executed successfully, False if it caused an error.
157
- * 'error_message' - the MySQL error message (only meaningful when 'success' = false).
158
- *
159
- * The 'success' and 'error_message' keys will only be present if $execute was set to True.
160
- *
161
- * @param string $queries One or more CREATE TABLE queries separated by a semicolon.
162
- * @param bool $execute Whether to apply the schema changes. Defaults to true.
163
- * @param bool $drop_columns Whether to drop columns not present in the input. Defaults to true.
164
- * @param bool $drop_indexes Whether to drop indexes not present in the input. Defaults to true.
165
- * @return array
166
- */
167
- static function delta($queries, $execute = true, $drop_columns = true, $drop_indexes = true){
168
- global $wpdb, $blclog; /** @var wpdb $wpdb */
169
-
170
- // Separate individual queries into an array
171
- if ( !is_array($queries) ) {
172
- $queries = explode( ';', $queries );
173
- if ('' == $queries[count($queries) - 1]) array_pop($queries);
174
- }
175
-
176
- $cqueries = array(); // Creation Queries
177
- $for_update = array();
178
-
179
- // Create a tablename index for an array ($cqueries) of queries
180
- foreach($queries as $qry) {
181
- if (preg_match("|CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([^\s(]+)|i", $qry, $matches)) {
182
- $table = trim( $matches[1], '`' );
183
- $cqueries[$table] = $qry;
184
- $for_update[$table] = 'Create table `'.$table.'`';
185
- }
186
- }
187
-
188
- // Check to see which tables and fields exist
189
- $start_show_tables = microtime(true);
190
- if ($tables = $wpdb->get_col('SHOW TABLES;')) {
191
- $blclog->info(sprintf('... SHOW TABLES (%.3f seconds)', microtime(true) - $start_show_tables));
192
-
193
- // For every table in the database
194
- foreach ($tables as $table) {
195
-
196
- // If a table query exists for the database table...
197
- if ( array_key_exists($table, $cqueries) ) {
198
-
199
- // Clear the field and index arrays
200
- $cfields = $indices = array();
201
-
202
- // Get all of the field names in the query from between the parens
203
- preg_match("|\((.*)\)|ms", $cqueries[$table], $match2);
204
- $qryline = trim($match2[1]);
205
-
206
- // Separate field lines into an array
207
- $flds = preg_split('@[\r\n]+@', $qryline);
208
-
209
- //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($flds, true)."</pre><hr/>";
210
-
211
- // For every field line specified in the query
212
- foreach ($flds as $fld) {
213
- $definition = blcTableDelta::parse_create_definition($fld);
214
-
215
- if ( $definition ){
216
- if ( $definition['index'] ){
217
- $indices[ $definition['index_definition'] ] = $definition; //Index
218
- } else {
219
- $cfields[ $definition['name'] ] = $definition; //Column
220
- }
221
- }
222
- }
223
-
224
- //echo "Detected fields : <br>"; print_r($cfields);
225
-
226
- // Fetch the table column structure from the database
227
- $start = microtime(true);
228
- $tablefields = $wpdb->get_results("SHOW FULL COLUMNS FROM {$table};");
229
- $blclog->info(sprintf('... SHOW FULL COLUMNS FROM %s %.3f seconds', $table, microtime(true) - $start));
230
-
231
- // For every field in the table
232
- foreach ($tablefields as $tablefield) {
233
- $field_name = strtolower($tablefield->Field); //Field names are case-insensitive in MySQL
234
-
235
- // If the table field exists in the field array...
236
- if (array_key_exists($field_name, $cfields)) {
237
- $definition = $cfields[$field_name];
238
-
239
- // Is actual field definition different from that in the query?
240
- $different =
241
- ( $tablefield->Type != $definition['data_type'] ) ||
242
- ( $definition['collation'] && ($tablefield->Collation != $definition['collation']) ) ||
243
- ( $definition['null_allowed'] && ($tablefield->Null == 'NO') ) ||
244
- ( !$definition['null_allowed'] && ($tablefield->Null == 'YES') ) ||
245
- ( $tablefield->Default !== $definition['default'] );
246
-
247
- // Add a query to change the column type
248
- if ( $different ) {
249
- $cqueries[] = "ALTER TABLE `{$table}` MODIFY COLUMN `{$field_name}` {$definition['column_definition']}";
250
- $for_update[$table.'.'.$field_name] = "Changed type of {$table}.{$field_name} from {$tablefield->Type} to {$definition['column_definition']}";
251
- }
252
-
253
- // Remove the field from the array (so it's not added)
254
- unset($cfields[$field_name]);
255
- } else {
256
- // This field exists in the table, but not in the creation queries? Drop it.
257
- if ( $drop_columns ){
258
- $cqueries[] = "ALTER TABLE `{$table}` DROP COLUMN `$field_name`";
259
- $for_update[$table.'.'.$field_name] = 'Removed column '.$table.'.'.$field_name;
260
- }
261
- }
262
- }
263
-
264
- // For every remaining field specified for the table
265
- foreach ($cfields as $field_name => $definition) {
266
- // Push a query line into $cqueries that adds the field to that table
267
- $cqueries[] = "ALTER TABLE `{$table}` ADD COLUMN `$field_name` {$definition['column_definition']}";
268
- $for_update[$table.'.'.$field_name] = 'Added column '.$table.'.'.$field_name;
269
- }
270
-
271
- // Index stuff goes here
272
- //echo 'Detected indexes : <br>'; print_r($indices);
273
-
274
- // Fetch the table index structure from the database
275
- $start = microtime(true);
276
- $tableindices = $wpdb->get_results("SHOW INDEX FROM `{$table}`;");
277
- $blclog->info(sprintf('... SHOW INDEX FROM %s %.3f seconds', $table, microtime(true) - $start));
278
-
279
- if ($tableindices) {
280
- // Clear the index array
281
- $index_ary = array();
282
-
283
- // For every index in the table
284
- foreach ($tableindices as $tableindex) {
285
- // Add the index to the index data array
286
- $keyname = strtolower($tableindex->Key_name);
287
- $index_ary[$keyname]['name'] = $keyname;
288
-
289
- $index_ary[$keyname]['columns'][] = array(
290
- 'column_name' => strtolower($tableindex->Column_name),
291
- 'length' => $tableindex->Sub_part
292
- );
293
-
294
- if ( !isset($index_ary[$keyname]['index_modifier']) ){
295
- if ( $keyname == 'primary' ){
296
- $index_ary[$keyname]['index_modifier'] = 'primary';
297
- } else if ( $tableindex->Non_unique == 0 ){
298
- $index_ary[$keyname]['index_modifier'] = 'unique';
299
- }
300
- }
301
- }
302
-
303
- // For each actual index in the index array
304
- foreach ($index_ary as $index_name => $index_data) {
305
- // Build a create string to compare to the query
306
- $index_string = blcTableDelta::generate_index_string($index_data);
307
- if ( array_key_exists($index_string, $indices) ){
308
- //echo "Found index $index_string<br>";
309
- unset($indices[$index_string]);
310
- } else {
311
- //echo "Didn't find index $index_string<br>";
312
- if ( $drop_indexes ){
313
- if ( $index_name == 'primary' ){
314
- $cqueries[] = "ALTER TABLE `{$table}` DROP PRIMARY KEY";
315
- } else {
316
- $cqueries[] = "ALTER TABLE `{$table}` DROP KEY `$index_name`";
317
- }
318
- $for_update[$table.'.'.$index_name] = 'Removed index '.$table.'.'.$index_name;
319
- }
320
- }
321
- }
322
- }
323
-
324
- // For every remaining index specified for the table
325
- foreach ( $indices as $index ) {
326
- // Push a query line into $cqueries that adds the index to that table
327
- $cqueries[] = "ALTER TABLE `{$table}` ADD {$index['index_definition']}";
328
- $for_update[$table.'.'.$index['name']] = 'Added index '.$table.' '.$index['index_definition'];
329
- }
330
-
331
- // Remove the original table creation query from processing
332
- unset($cqueries[$table]);
333
- unset($for_update[$table]);
334
- } else {
335
- // This table exists in the database, but not in the creation queries?
336
- }
337
- }
338
- }
339
-
340
- //echo "Execute queries : <br>"; print_r($cqueries);
341
- $query_log = array();
342
- foreach ($cqueries as $query) {
343
- $log_item = array('query' => $query,);
344
- if ( $execute ) {
345
- $start = microtime(true);
346
- $log_item['success'] = ($wpdb->query($query) !== false);
347
- $log_item['error_message'] = $wpdb->last_error;
348
- $log_item['query_time'] = microtime(true) - $start;
349
- }
350
- $query_log[] = $log_item;
351
- }
352
-
353
- return array($for_update, $query_log);
354
- }
355
-
356
- /**
357
- * Parse a a single column or index definition.
358
- *
359
- * This function can parse many (but not all) types of syntax used to define columns
360
- * and indexes in a "CREATE TABLE" query.
361
- *
362
- * @param string $line
363
- * @return array
364
- */
365
- static function parse_create_definition($line){
366
- $line = preg_replace('@[,\r\n\s]+$@', '', $line); //Strip the ", " line separator
367
-
368
- $pieces = preg_split('@\s+|(?=\()@', $line, -1, PREG_SPLIT_NO_EMPTY);
369
- if ( empty($pieces) ){
370
- return null;
371
- }
372
-
373
- $token = strtolower(array_shift($pieces));
374
-
375
- $index_modifier = '';
376
- $index = false;
377
-
378
- //Determine if this line defines an index
379
- if ( in_array($token, array('primary', 'unique', 'fulltext')) ){
380
- $index_modifier = $token;
381
- $index = true;
382
- $token = strtolower(array_shift($pieces));
383
- }
384
-
385
- if ( in_array($token, array('index', 'key')) ){
386
- $index = true;
387
- $token = strtolower(array_shift($pieces));
388
- }
389
-
390
- //Determine column/index name
391
- $name = '';
392
- if ( $index ){
393
- //Names are optional for indexes; the INDEX/etc keyword can be immediately
394
- //followed by a column list (or index_type, but we're ignoring that possibility).
395
- if ( strpos($token, '(') === false ){
396
- $name = $token;
397
- } else {
398
- if ( $index_modifier == 'primary' ){
399
- $name = 'primary';
400
- }
401
- array_unshift($pieces, $token);
402
- }
403
- } else {
404
- $name = $token;
405
- }
406
- $name = strtolower(trim($name, '`'));
407
-
408
- $definition = compact('name', 'index', 'index_modifier');
409
-
410
- //Parse the rest of the line
411
- $remainder = implode(' ', $pieces);
412
- if ( $index ){
413
- $definition['columns'] = blcTableDelta::parse_index_column_list($remainder);
414
-
415
- //If the index doesn't have a name, use the name of the first column
416
- //(this is what MySQL does, but only when there isn't already an index with that name).
417
- if ( empty($definition['name']) ){
418
- $definition['name'] = $definition['columns'][0]['column_name'];
419
- }
420
- //Rebuild the index def. in a normalized form
421
- $definition['index_definition'] = blcTableDelta::generate_index_string($definition);
422
-
423
- } else {
424
- $column_def = blcTableDelta::parse_column_definition($remainder);
425
- $definition = array_merge($definition, $column_def);
426
- }
427
-
428
- return $definition;
429
- }
430
-
431
- /**
432
- * Parse the list of columns included in an index.
433
- *
434
- * This function returns a list of column descriptors. Each descriptor is
435
- * an associative array with the keys 'column_name', 'length' and 'order'.
436
- *
437
- * @param string $line
438
- * @return array Array of index columns
439
- */
440
- static function parse_index_column_list($line){
441
- $line = preg_replace('@^\s*\(|\)\s*$@', '', $line); //Strip the braces that surround the column list
442
- $pieces = preg_split('@\s*,\s*@', $line);
443
-
444
- $columns = array();
445
- foreach($pieces as $piece){
446
- if ( preg_match('@`?(?P<column_name>[^\s`]+)`?(?:\s*\(\s*(?P<length>\d+)\s*\))?(?:\s+(?P<order>ASC|DESC))?@i', $piece, $matches) ){
447
-
448
- $column = array(
449
- 'column_name' => strtolower($matches['column_name']),
450
- 'length' => null,
451
- 'order' => null //unused; included for completeness
452
- );
453
-
454
- if ( isset($matches['length']) && is_numeric($matches['length']) ){
455
- $column['length'] = intval($matches['length']);
456
- }
457
- if ( isset($matches['order']) && !empty($matches['order']) ){
458
- $column['order'] = strtolower($matches['order']);
459
- }
460
-
461
- $columns[] = $column;
462
- };
463
- }
464
-
465
- return $columns;
466
- }
467
-
468
- /**
469
- * Parse column datatype and flags.
470
- *
471
- *
472
- * @param string $line
473
- * @return array
474
- */
475
- static function parse_column_definition($line){
476
- $line = trim($line);
477
-
478
- //Extract datatype. This regexp is not entirely reliable - for example, it won't work
479
- //with enum fields where one of values contains brackets "()".
480
- $data_type = '';
481
- $regexp = '
482
- @
483
- (?P<type_name>^\w+)
484
-
485
- # followed by an optional length or a list of enum values
486
- (?:\s*
487
- \(
488
- \s* (?P<length>[^()]+) \s*
489
- \)
490
- )?
491
-
492
- # various type modifiers/keywords
493
- (?P<keywords>
494
- (?:\s+
495
- (?: BINARY | UNSIGNED | ZEROFILL )
496
- )*
497
- )?
498
- @xi';
499
-
500
- if ( preg_match($regexp, $line, $matches) ){
501
- $data_type = strtolower($matches['type_name']);
502
- if ( !empty($matches['length']) ){
503
- $data_type .= '(' . trim($matches['length']) . ')';
504
- }
505
- if ( !empty($matches['keywords']) ){
506
- $data_type .= preg_replace('@\s+@', ' ', $matches['keywords']); //Collapse spaces
507
- }
508
- $line = substr($line, strlen($data_type));
509
- }
510
-
511
- //Extract flags
512
- $null_allowed = !preg_match('@\sNOT\s+NULL\b@i', $line);
513
- $auto_increment = preg_match('@\sAUTO_INCREMENT\b@i', $line);
514
-
515
- //Got a default value?
516
- $default = null;
517
- if ( preg_match("@\sDEFAULT\s+('[^']*'|\"[^\"]*\"|\d+)@i", $line, $matches) ){
518
- $default = trim($matches[1], '"\'');
519
- }
520
-
521
- //Custom character set and/or collation?
522
- $charset = $collation = null;
523
- if ( preg_match('@ (?:\s CHARACTER \s+ SET \s+ (?P<charset>[^\s()]+) )? (?:\s COLLATE \s+ (?P<collation>[^\s()]+) )? @xi', $line, $matches) ){
524
- if ( isset($matches['charset']) ){
525
- $charset = $matches['charset'];
526
- }
527
- if ( isset($matches['collation']) ){
528
- $collation = $matches['collation'];
529
- }
530
- }
531
-
532
- //Generate the normalized column definition
533
- $column_definition = $data_type;
534
- if ( !empty($charset) ){
535
- $column_definition .= " CHARACTER SET {$charset}";
536
- }
537
- if ( !empty($collation) ){
538
- $column_definition .= " COLLATE {$collation}";
539
- }
540
- if ( !$null_allowed ){
541
- $column_definition .= " NOT NULL";
542
- }
543
- if ( !is_null($default) ){
544
- $column_definition .= " DEFAULT '{$default}'";
545
- }
546
- if ( $auto_increment ){
547
- $column_definition .= " AUTO_INCREMENT";
548
- }
549
-
550
- return compact('data_type', 'null_allowed', 'auto_increment', 'default', 'charset', 'collation', 'column_definition');
551
- }
552
-
553
- /**
554
- * Generate an index's definition string from its parsed representation.
555
- *
556
- * @param array $definition The return value of blcTableDelta::parse_create_definition()
557
- * @return string
558
- */
559
- static function generate_index_string($definition){
560
-
561
- //Rebuild the index def. in a normalized form
562
- $index_definition = '';
563
- if ( !empty($definition['index_modifier']) ){
564
- $index_definition .= strtoupper($definition['index_modifier']) . ' ';
565
- }
566
- $index_definition .= 'KEY';
567
- if ( empty($definition['index_modifier']) || ($definition['index_modifier'] != 'primary') ){
568
- $index_definition .= ' `' . $definition['name'].'`';
569
- }
570
-
571
- $column_strings = array();
572
- foreach($definition['columns'] as $column){
573
- $c = '`' . $column['column_name'] . '`';
574
- if ( $column['length'] ){
575
- $c .= '('.$column['length'].')';
576
- }
577
- $column_strings[] = $c;
578
- }
579
-
580
- $index_definition .= ' (' . implode(', ', $column_strings) . ')';
581
- return $index_definition;
582
- }
583
-
584
- }
585
-
1
+ <?php
2
+
3
+ class blcDatabaseUpgrader {
4
+
5
+ /**
6
+ * Create and/or upgrade the plugin's database tables.
7
+ *
8
+ * @return bool
9
+ */
10
+ public static function upgrade_database(){
11
+ global $blclog;
12
+
13
+ $conf = blc_get_configuration();
14
+ $current = $conf->options['current_db_version'];
15
+
16
+ if ( ($current != 0) && ( $current < 4 ) ){
17
+ //The 4th DB version makes a lot of backwards-incompatible changes to the main
18
+ //BLC tables, so instead of upgrading we just throw them away and recreate.
19
+ if ( !blcDatabaseUpgrader::drop_tables() ){
20
+ return false;
21
+ };
22
+ $current = 0;
23
+ }
24
+
25
+ //Create/update the plugin's tables
26
+ if ( !blcDatabaseUpgrader::make_schema_current() ) {
27
+ return false;
28
+ }
29
+
30
+ if ( $current != 0 ){
31
+
32
+ if ( $current < 5 ){
33
+ blcDatabaseUpgrader::upgrade_095();
34
+ }
35
+
36
+ }
37
+
38
+ $conf->options['current_db_version'] = BLC_DATABASE_VERSION;
39
+ $conf->save_options();
40
+ $blclog->info('Database successfully upgraded.');
41
+
42
+ return true;
43
+ }
44
+
45
+ /**
46
+ * Create or update the plugin's DB tables.
47
+ *
48
+ * @return bool
49
+ */
50
+ static function make_schema_current(){
51
+ global $blclog;
52
+
53
+ $start = microtime(true);
54
+ if ( !function_exists('blc_get_db_schema') ){
55
+ require 'db-schema.php';
56
+ }
57
+ list($dummy, $query_log) = blcTableDelta::delta(blc_get_db_schema());
58
+
59
+ $have_errors = false;
60
+ foreach($query_log as $item){
61
+ if ( $item['success'] ){
62
+ $blclog->info(' [OK] ' . $item['query'] . sprintf(' (%.3f seconds)', $item['query_time']));
63
+ } else {
64
+ $blclog->error(' [ ] ' . $item['query']);
65
+ $blclog->error(' Database error : ' . $item['error_message']);
66
+ $have_errors = true;
67
+ }
68
+ }
69
+ $blclog->info(sprintf('Schema update took %.3f seconds', microtime(true) - $start));
70
+
71
+ $blclog->info('Database schema updated.');
72
+ return !$have_errors;
73
+ }
74
+
75
+ /**
76
+ * Drop the plugin's tables.
77
+ *
78
+ * @return bool
79
+ */
80
+ static function drop_tables(){
81
+ global $wpdb, $blclog; /** @var wpdb $wpdb */
82
+
83
+ $blclog->info('Deleting the plugin\'s database tables');
84
+ $tables = array(
85
+ $wpdb->prefix . 'blc_linkdata',
86
+ $wpdb->prefix . 'blc_postdata',
87
+ $wpdb->prefix . 'blc_instances',
88
+ $wpdb->prefix . 'blc_synch',
89
+ $wpdb->prefix . 'blc_links',
90
+ );
91
+
92
+ $q = "DROP TABLE IF EXISTS " . implode(', ', $tables);
93
+ $rez = $wpdb->query( $q );
94
+
95
+ if ( $rez === false ){
96
+ $error = sprintf(
97
+ __("Failed to delete old DB tables. Database error : %s", 'broken-link-checker'),
98
+ $wpdb->last_error
99
+ );
100
+
101
+ $blclog->error($error);
102
+ /*
103
+ //FIXME: In very rare cases, DROP TABLE IF EXISTS throws an error when the table(s) don't exist.
104
+ return false;
105
+ //*/
106
+ }
107
+ $blclog->info('Done.');
108
+
109
+ return true;
110
+ }
111
+
112
+ static function upgrade_095($trigger_errors = false){
113
+ global $wpdb; /** @var wpdb $wpdb */
114
+
115
+ //Prior to 0.9.5 all supported post types were internally represented using
116
+ //a common 'post' container type. The current version creates a unique container
117
+ //type to each post type.
118
+
119
+ //Update synch records and instances to reflect this change
120
+ $q = "
121
+ UPDATE
122
+ {$wpdb->prefix}blc_synch AS synch
123
+ LEFT JOIN {$wpdb->posts} AS posts ON (posts.ID = synch.container_id)
124
+ SET
125
+ synch.container_type = posts.post_type
126
+ WHERE
127
+ synch.container_type = 'post' AND posts.post_type IS NOT NULL";
128
+ $wpdb->query($q);
129
+
130
+ $q = "
131
+ UPDATE
132
+ {$wpdb->prefix}blc_instances AS instances
133
+ LEFT JOIN {$wpdb->posts} AS posts ON (posts.ID = instances.container_id)
134
+ SET
135
+ instances.container_type = posts.post_type
136
+ WHERE
137
+ instances.container_type = 'post' AND posts.post_type IS NOT NULL";
138
+ $wpdb->query($q);
139
+ }
140
+
141
+ }
142
+
143
+ class blcTableDelta {
144
+
145
+ /**
146
+ * Parse one or more CREATE TABLE queries and generate a list of SQL queries that need
147
+ * to be executed to make the current database schema match those queries. Will also
148
+ * execute those queries by default.
149
+ *
150
+ * This function returns an array with two items. The first is a list of human-readable
151
+ * messages explaining what database changes were/would be made. The second array item
152
+ * is an array of the generated SQL queries and (if $execute was True) their results.
153
+ *
154
+ * Each item of this second array is itself an associative array with these keys :
155
+ * 'query' - the generated query.
156
+ * 'success' - True if the query was executed successfully, False if it caused an error.
157
+ * 'error_message' - the MySQL error message (only meaningful when 'success' = false).
158
+ *
159
+ * The 'success' and 'error_message' keys will only be present if $execute was set to True.
160
+ *
161
+ * @param string $queries One or more CREATE TABLE queries separated by a semicolon.
162
+ * @param bool $execute Whether to apply the schema changes. Defaults to true.
163
+ * @param bool $drop_columns Whether to drop columns not present in the input. Defaults to true.
164
+ * @param bool $drop_indexes Whether to drop indexes not present in the input. Defaults to true.
165
+ * @return array
166
+ */
167
+ static function delta($queries, $execute = true, $drop_columns = true, $drop_indexes = true){
168
+ global $wpdb, $blclog; /** @var wpdb $wpdb */
169
+
170
+ // Separate individual queries into an array
171
+ if ( !is_array($queries) ) {
172
+ $queries = explode( ';', $queries );
173
+ if ('' == $queries[count($queries) - 1]) array_pop($queries);
174
+ }
175
+
176
+ $cqueries = array(); // Creation Queries
177
+ $for_update = array();
178
+
179
+ // Create a tablename index for an array ($cqueries) of queries
180
+ foreach($queries as $qry) {
181
+ if (preg_match("|CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([^\s(]+)|i", $qry, $matches)) {
182
+ $table = trim( $matches[1], '`' );
183
+ $cqueries[$table] = $qry;
184
+ $for_update[$table] = 'Create table `'.$table.'`';
185
+ }
186
+ }
187
+
188
+ // Check to see which tables and fields exist
189
+ $start_show_tables = microtime(true);
190
+ if ($tables = $wpdb->get_col('SHOW TABLES;')) {
191
+ $blclog->info(sprintf('... SHOW TABLES (%.3f seconds)', microtime(true) - $start_show_tables));
192
+
193
+ // For every table in the database
194
+ foreach ($tables as $table) {
195
+
196
+ // If a table query exists for the database table...
197
+ if ( array_key_exists($table, $cqueries) ) {
198
+
199
+ // Clear the field and index arrays
200
+ $cfields = $indices = array();
201
+
202
+ // Get all of the field names in the query from between the parens
203
+ preg_match("|\((.*)\)|ms", $cqueries[$table], $match2);
204
+ $qryline = trim($match2[1]);
205
+
206
+ // Separate field lines into an array
207
+ $flds = preg_split('@[\r\n]+@', $qryline);
208
+
209
+ //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($flds, true)."</pre><hr/>";
210
+
211
+ // For every field line specified in the query
212
+ foreach ($flds as $fld) {
213
+ $definition = blcTableDelta::parse_create_definition($fld);
214
+
215
+ if ( $definition ){
216
+ if ( $definition['index'] ){
217
+ $indices[ $definition['index_definition'] ] = $definition; //Index
218
+ } else {
219
+ $cfields[ $definition['name'] ] = $definition; //Column
220
+ }
221
+ }
222
+ }
223
+
224
+ //echo "Detected fields : <br>"; print_r($cfields);
225
+
226
+ // Fetch the table column structure from the database
227
+ $start = microtime(true);
228
+ $tablefields = $wpdb->get_results("SHOW FULL COLUMNS FROM {$table};");
229
+ $blclog->info(sprintf('... SHOW FULL COLUMNS FROM %s %.3f seconds', $table, microtime(true) - $start));
230
+
231
+ // For every field in the table
232
+ foreach ($tablefields as $tablefield) {
233
+ $field_name = strtolower($tablefield->Field); //Field names are case-insensitive in MySQL
234
+
235
+ // If the table field exists in the field array...
236
+ if (array_key_exists($field_name, $cfields)) {
237
+ $definition = $cfields[$field_name];
238
+
239
+ // Is actual field definition different from that in the query?
240
+ $different =
241
+ ( $tablefield->Type != $definition['data_type'] ) ||
242
+ ( $definition['collation'] && ($tablefield->Collation != $definition['collation']) ) ||
243
+ ( $definition['null_allowed'] && ($tablefield->Null == 'NO') ) ||
244
+ ( !$definition['null_allowed'] && ($tablefield->Null == 'YES') ) ||
245
+ ( $tablefield->Default !== $definition['default'] );
246
+
247
+ // Add a query to change the column type
248
+ if ( $different ) {
249
+ $cqueries[] = "ALTER TABLE `{$table}` MODIFY COLUMN `{$field_name}` {$definition['column_definition']}";
250
+ $for_update[$table.'.'.$field_name] = "Changed type of {$table}.{$field_name} from {$tablefield->Type} to {$definition['column_definition']}";
251
+ }
252
+
253
+ // Remove the field from the array (so it's not added)
254
+ unset($cfields[$field_name]);
255
+ } else {
256
+ // This field exists in the table, but not in the creation queries? Drop it.
257
+ if ( $drop_columns ){
258
+ $cqueries[] = "ALTER TABLE `{$table}` DROP COLUMN `$field_name`";
259
+ $for_update[$table.'.'.$field_name] = 'Removed column '.$table.'.'.$field_name;
260
+ }
261
+ }
262
+ }
263
+
264
+ // For every remaining field specified for the table
265
+ foreach ($cfields as $field_name => $definition) {
266
+ // Push a query line into $cqueries that adds the field to that table
267
+ $cqueries[] = "ALTER TABLE `{$table}` ADD COLUMN `$field_name` {$definition['column_definition']}";
268
+ $for_update[$table.'.'.$field_name] = 'Added column '.$table.'.'.$field_name;
269
+ }
270
+
271
+ // Index stuff goes here
272
+ //echo 'Detected indexes : <br>'; print_r($indices);
273
+
274
+ // Fetch the table index structure from the database
275
+ $start = microtime(true);
276
+ $tableindices = $wpdb->get_results("SHOW INDEX FROM `{$table}`;");
277
+ $blclog->info(sprintf('... SHOW INDEX FROM %s %.3f seconds', $table, microtime(true) - $start));
278
+
279
+ if ($tableindices) {
280
+ // Clear the index array
281
+ $index_ary = array();
282
+
283
+ // For every index in the table
284
+ foreach ($tableindices as $tableindex) {
285
+ // Add the index to the index data array
286
+ $keyname = strtolower($tableindex->Key_name);
287
+ $index_ary[$keyname]['name'] = $keyname;
288
+
289
+ $index_ary[$keyname]['columns'][] = array(
290
+ 'column_name' => strtolower($tableindex->Column_name),
291
+ 'length' => $tableindex->Sub_part
292
+ );
293
+
294
+ if ( !isset($index_ary[$keyname]['index_modifier']) ){
295
+ if ( $keyname == 'primary' ){
296
+ $index_ary[$keyname]['index_modifier'] = 'primary';
297
+ } else if ( $tableindex->Non_unique == 0 ){
298
+ $index_ary[$keyname]['index_modifier'] = 'unique';
299
+ }
300
+ }
301
+ }
302
+
303
+ // For each actual index in the index array
304
+ foreach ($index_ary as $index_name => $index_data) {
305
+ // Build a create string to compare to the query
306
+ $index_string = blcTableDelta::generate_index_string($index_data);
307
+ if ( array_key_exists($index_string, $indices) ){
308
+ //echo "Found index $index_string<br>";
309
+ unset($indices[$index_string]);
310
+ } else {
311
+ //echo "Didn't find index $index_string<br>";
312
+ if ( $drop_indexes ){
313
+ if ( $index_name == 'primary' ){
314
+ $cqueries[] = "ALTER TABLE `{$table}` DROP PRIMARY KEY";
315
+ } else {
316
+ $cqueries[] = "ALTER TABLE `{$table}` DROP KEY `$index_name`";
317
+ }
318
+ $for_update[$table.'.'.$index_name] = 'Removed index '.$table.'.'.$index_name;
319
+ }
320
+ }
321
+ }
322
+ }
323
+
324
+ // For every remaining index specified for the table
325
+ foreach ( $indices as $index ) {
326
+ // Push a query line into $cqueries that adds the index to that table
327
+ $cqueries[] = "ALTER TABLE `{$table}` ADD {$index['index_definition']}";
328
+ $for_update[$table.'.'.$index['name']] = 'Added index '.$table.' '.$index['index_definition'];
329
+ }
330
+
331
+ // Remove the original table creation query from processing
332
+ unset($cqueries[$table]);
333
+ unset($for_update[$table]);
334
+ } else {
335
+ // This table exists in the database, but not in the creation queries?
336
+ }
337
+ }
338
+ }
339
+
340
+ //echo "Execute queries : <br>"; print_r($cqueries);
341
+ $query_log = array();
342
+ foreach ($cqueries as $query) {
343
+ $log_item = array('query' => $query,);
344
+ if ( $execute ) {
345
+ $start = microtime(true);
346
+ $log_item['success'] = ($wpdb->query($query) !== false);
347
+ $log_item['error_message'] = $wpdb->last_error;
348
+ $log_item['query_time'] = microtime(true) - $start;
349
+ }
350
+ $query_log[] = $log_item;
351
+ }
352
+
353
+ return array($for_update, $query_log);
354
+ }
355
+
356
+ /**
357
+ * Parse a a single column or index definition.
358
+ *
359
+ * This function can parse many (but not all) types of syntax used to define columns
360
+ * and indexes in a "CREATE TABLE" query.
361
+ *
362
+ * @param string $line
363
+ * @return array
364
+ */
365
+ static function parse_create_definition($line){
366
+ $line = preg_replace('@[,\r\n\s]+$@', '', $line); //Strip the ", " line separator
367
+
368
+ $pieces = preg_split('@\s+|(?=\()@', $line, -1, PREG_SPLIT_NO_EMPTY);
369
+ if ( empty($pieces) ){
370
+ return null;
371
+ }
372
+
373
+ $token = strtolower(array_shift($pieces));
374
+
375
+ $index_modifier = '';
376
+ $index = false;
377
+
378
+ //Determine if this line defines an index
379
+ if ( in_array($token, array('primary', 'unique', 'fulltext')) ){
380
+ $index_modifier = $token;
381
+ $index = true;
382
+ $token = strtolower(array_shift($pieces));
383
+ }
384
+
385
+ if ( in_array($token, array('index', 'key')) ){
386
+ $index = true;
387
+ $token = strtolower(array_shift($pieces));
388
+ }
389
+
390
+ //Determine column/index name
391
+ $name = '';
392
+ if ( $index ){
393
+ //Names are optional for indexes; the INDEX/etc keyword can be immediately
394
+ //followed by a column list (or index_type, but we're ignoring that possibility).
395
+ if ( strpos($token, '(') === false ){
396
+ $name = $token;
397
+ } else {
398
+ if ( $index_modifier == 'primary' ){
399
+ $name = 'primary';
400
+ }
401
+ array_unshift($pieces, $token);
402
+ }
403
+ } else {
404
+ $name = $token;
405
+ }
406
+ $name = strtolower(trim($name, '`'));
407
+
408
+ $definition = compact('name', 'index', 'index_modifier');
409
+
410
+ //Parse the rest of the line
411
+ $remainder = implode(' ', $pieces);
412
+ if ( $index ){
413
+ $definition['columns'] = blcTableDelta::parse_index_column_list($remainder);
414
+
415
+ //If the index doesn't have a name, use the name of the first column
416
+ //(this is what MySQL does, but only when there isn't already an index with that name).
417
+ if ( empty($definition['name']) ){
418
+ $definition['name'] = $definition['columns'][0]['column_name'];
419
+ }
420
+ //Rebuild the index def. in a normalized form
421
+ $definition['index_definition'] = blcTableDelta::generate_index_string($definition);
422
+
423
+ } else {
424
+ $column_def = blcTableDelta::parse_column_definition($remainder);
425
+ $definition = array_merge($definition, $column_def);
426
+ }
427
+
428
+ return $definition;
429
+ }
430
+
431
+ /**
432
+ * Parse the list of columns included in an index.
433
+ *
434
+ * This function returns a list of column descriptors. Each descriptor is
435
+ * an associative array with the keys 'column_name', 'length' and 'order'.
436
+ *
437
+ * @param string $line
438
+ * @return array Array of index columns
439
+ */
440
+ static function parse_index_column_list($line){
441
+ $line = preg_replace('@^\s*\(|\)\s*$@', '', $line); //Strip the braces that surround the column list
442
+ $pieces = preg_split('@\s*,\s*@', $line);
443
+
444
+ $columns = array();
445
+ foreach($pieces as $piece){
446
+ if ( preg_match('@`?(?P<column_name>[^\s`]+)`?(?:\s*\(\s*(?P<length>\d+)\s*\))?(?:\s+(?P<order>ASC|DESC))?@i', $piece, $matches) ){
447
+
448
+ $column = array(
449
+ 'column_name' => strtolower($matches['column_name']),
450
+ 'length' => null,
451
+ 'order' => null //unused; included for completeness
452
+ );
453
+
454
+ if ( isset($matches['length']) && is_numeric($matches['length']) ){
455
+ $column['length'] = intval($matches['length']);
456
+ }
457
+ if ( isset($matches['order']) && !empty($matches['order']) ){
458
+ $column['order'] = strtolower($matches['order']);
459
+ }
460
+
461
+ $columns[] = $column;
462
+ };
463
+ }
464
+
465
+ return $columns;
466
+ }
467
+
468
+ /**
469
+ * Parse column datatype and flags.
470
+ *
471
+ *
472
+ * @param string $line
473
+ * @return array
474
+ */
475
+ static function parse_column_definition($line){
476
+ $line = trim($line);
477
+
478
+ //Extract datatype. This regexp is not entirely reliable - for example, it won't work
479
+ //with enum fields where one of values contains brackets "()".
480
+ $data_type = '';
481
+ $regexp = '
482
+ @
483
+ (?P<type_name>^\w+)
484
+
485
+ # followed by an optional length or a list of enum values
486
+ (?:\s*
487
+ \(
488
+ \s* (?P<length>[^()]+) \s*
489
+ \)
490
+ )?
491
+
492
+ # various type modifiers/keywords
493
+ (?P<keywords>
494
+ (?:\s+
495
+ (?: BINARY | UNSIGNED | ZEROFILL )
496
+ )*
497
+ )?
498
+ @xi';
499
+
500
+ if ( preg_match($regexp, $line, $matches) ){
501
+ $data_type = strtolower($matches['type_name']);
502
+ if ( !empty($matches['length']) ){
503
+ $data_type .= '(' . trim($matches['length']) . ')';
504
+ }
505
+ if ( !empty($matches['keywords']) ){
506
+ $data_type .= preg_replace('@\s+@', ' ', $matches['keywords']); //Collapse spaces
507
+ }
508
+ $line = substr($line, strlen($data_type));
509
+ }
510
+
511
+ //Extract flags
512
+ $null_allowed = !preg_match('@\sNOT\s+NULL\b@i', $line);
513
+ $auto_increment = preg_match('@\sAUTO_INCREMENT\b@i', $line);
514
+
515
+ //Got a default value?
516
+ $default = null;
517
+ if ( preg_match("@\sDEFAULT\s+('[^']*'|\"[^\"]*\"|\d+)@i", $line, $matches) ){
518
+ $default = trim($matches[1], '"\'');
519
+ }
520
+
521
+ //Custom character set and/or collation?
522
+ $charset = $collation = null;
523
+ if ( preg_match('@ (?:\s CHARACTER \s+ SET \s+ (?P<charset>[^\s()]+) )? (?:\s COLLATE \s+ (?P<collation>[^\s()]+) )? @xi', $line, $matches) ){
524
+ if ( isset($matches['charset']) ){
525
+ $charset = $matches['charset'];
526
+ }
527
+ if ( isset($matches['collation']) ){
528
+ $collation = $matches['collation'];
529
+ }
530
+ }
531
+
532
+ //Generate the normalized column definition
533
+ $column_definition = $data_type;
534
+ if ( !empty($charset) ){
535
+ $column_definition .= " CHARACTER SET {$charset}";
536
+ }
537
+ if ( !empty($collation) ){
538
+ $column_definition .= " COLLATE {$collation}";
539
+ }
540
+ if ( !$null_allowed ){
541
+ $column_definition .= " NOT NULL";
542
+ }
543
+ if ( !is_null($default) ){
544
+ $column_definition .= " DEFAULT '{$default}'";
545
+ }
546
+ if ( $auto_increment ){
547
+ $column_definition .= " AUTO_INCREMENT";
548
+ }
549
+
550
+ return compact('data_type', 'null_allowed', 'auto_increment', 'default', 'charset', 'collation', 'column_definition');
551
+ }
552
+
553
+ /**
554
+ * Generate an index's definition string from its parsed representation.
555
+ *
556
+ * @param array $definition The return value of blcTableDelta::parse_create_definition()
557
+ * @return string
558
+ */
559
+ static function generate_index_string($definition){
560
+
561
+ //Rebuild the index def. in a normalized form
562
+ $index_definition = '';
563
+ if ( !empty($definition['index_modifier']) ){
564
+ $index_definition .= strtoupper($definition['index_modifier']) . ' ';
565
+ }
566
+ $index_definition .= 'KEY';
567
+ if ( empty($definition['index_modifier']) || ($definition['index_modifier'] != 'primary') ){
568
+ $index_definition .= ' `' . $definition['name'].'`';
569
+ }
570
+
571
+ $column_strings = array();
572
+ foreach($definition['columns'] as $column){
573
+ $c = '`' . $column['column_name'] . '`';
574
+ if ( $column['length'] ){
575
+ $c .= '('.$column['length'].')';
576
+ }
577
+ $column_strings[] = $c;
578
+ }
579
+
580
+ $index_definition .= ' (' . implode(', ', $column_strings) . ')';
581
+ return $index_definition;
582
+ }
583
+
584
+ }
585
+
includes/admin/links-page-js.php CHANGED
@@ -1,946 +1,946 @@
1
- <script type='text/javascript'>
2
-
3
- function alterLinkCounter(factor, filterId){
4
- var counter;
5
- if (filterId) {
6
- counter = jQuery('.filter-' + filterId + '-link-count');
7
- } else {
8
- counter = jQuery('.current-link-count');
9
- }
10
-
11
- var cnt = parseInt(counter.eq(0).html(), 10);
12
- cnt = cnt + factor;
13
- counter.html(cnt);
14
-
15
- if ( blc_is_broken_filter ){
16
- //Update the broken link count displayed beside the "Broken Links" menu
17
- var menuBubble = jQuery('span.blc-menu-bubble');
18
- if ( menuBubble.length > 0 ){
19
- cnt = parseInt(menuBubble.eq(0).html());
20
- cnt = cnt + factor;
21
- if ( cnt > 0 ){
22
- menuBubble.html(cnt);
23
- } else {
24
- menuBubble.parent().hide();
25
- }
26
- }
27
- }
28
- }
29
-
30
- function replaceLinkId(old_id, new_id){
31
- var master = jQuery('#blc-row-'+old_id);
32
-
33
- master.attr('id', 'blc-row-'+new_id);
34
- master.find('.blc-link-id').html(new_id);
35
- master.find('th.check-column input[type="checkbox"]').val(new_id);
36
-
37
- var details_row = jQuery('#link-details-'+old_id);
38
- details_row.attr('id', 'link-details-'+new_id);
39
- }
40
-
41
- function reloadDetailsRow(link_id){
42
- var details_row = jQuery('#link-details-'+link_id);
43
-
44
- //Load up the new link info (so sue me)
45
- details_row.find('td').html('<center><?php echo esc_js(__('Loading...' , 'broken-link-checker')); ?></center>').load(
46
- "<?php echo admin_url('admin-ajax.php'); ?>",
47
- {
48
- 'action' : 'blc_link_details',
49
- 'link_id' : link_id
50
- }
51
- );
52
- }
53
-
54
- jQuery(function($){
55
-
56
- //The details button - display/hide detailed info about a link
57
- $(".blc-details-button, td.column-link-text, td.column-status, td.column-new-link-text").click(function () {
58
- var master = $(this).parents('.blc-row');
59
- var link_id = master.attr('id').split('-')[2];
60
- $('#link-details-'+link_id).toggle();
61
- return false;
62
- });
63
-
64
- var ajaxInProgressHtml = '<?php echo esc_js(__('Wait...', 'broken-link-checker')); ?>';
65
-
66
- //The "Not broken" button - manually mark the link as valid. The link will be checked again later.
67
- $(".blc-discard-button").click(function () {
68
- var me = $(this);
69
- me.html(ajaxInProgressHtml);
70
-
71
- var master = me.parents('.blc-row');
72
- var link_id = master.attr('id').split('-')[2];
73
-
74
- $.post(
75
- "<?php echo admin_url('admin-ajax.php'); ?>",
76
- {
77
- 'action' : 'blc_discard',
78
- 'link_id' : link_id,
79
- '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_discard')); ?>'
80
- },
81
- function (data, textStatus){
82
- if (data == 'OK'){
83
- var details = $('#link-details-'+link_id);
84
-
85
- //Remove the "Not broken" action
86
- me.parent().remove();
87
-
88
- //Set the displayed link status to OK
89
- var classNames = master.attr('class');
90
- classNames = classNames.replace(/(^|\s)link-status-[^\s]+(\s|$)/, ' ') + ' link-status-ok';
91
- master.attr('class', classNames);
92
-
93
- //Flash the main row green to indicate success, then remove it if the current view
94
- //is supposed to show only broken links or warnings.
95
- var should_hide_link = blc_is_broken_filter || (blc_current_base_filter == 'warnings');
96
-
97
- flashElementGreen(master, function(){
98
- if ( should_hide_link ){
99
- details.remove();
100
- master.remove();
101
- } else {
102
- reloadDetailsRow(link_id);
103
- }
104
- });
105
-
106
- //Update the elements displaying the number of results for the current filter.
107
- if( should_hide_link ){
108
- alterLinkCounter(-1);
109
- }
110
- } else {
111
- me.html('<?php echo esc_js(__('Not broken' , 'broken-link-checker')); ?>');
112
- alert(data);
113
- }
114
- }
115
- );
116
-
117
- return false;
118
- });
119
-
120
- //The "Dismiss" button - hide the link from the "Broken" and "Redirects" filters, but still apply link tweaks and so on.
121
- $(".blc-dismiss-button").click(function () {
122
- var me = $(this);
123
- var oldButtonHtml = me.html();
124
- me.html(ajaxInProgressHtml);
125
-
126
- var master = me.closest('.blc-row');
127
- var link_id = master.attr('id').split('-')[2];
128
- var should_hide_link = $.inArray(blc_current_base_filter, ['broken', 'redirects', 'warnings']) > -1;
129
-
130
- $.post(
131
- "<?php echo admin_url('admin-ajax.php'); ?>",
132
- {
133
- 'action' : 'blc_dismiss',
134
- 'link_id' : link_id,
135
- '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_dismiss')); ?>'
136
- },
137
- function (data, textStatus){
138
- if (data == 'OK'){
139
- var details = $('#link-details-'+link_id);
140
-
141
- //Remove the "Dismiss" action
142
- me.parent().hide();
143
-
144
- //Flash the main row green to indicate success, then remove it if necessary.
145
- flashElementGreen(master, function(){
146
- if ( should_hide_link ){
147
- details.remove();
148
- master.remove();
149
- }
150
- });
151
-
152
- //Update the elements displaying the number of results for the current filter.
153
- if( should_hide_link ){
154
- alterLinkCounter(-1);
155
- alterLinkCounter(1, 'dismissed');
156
- }
157
- } else {
158
- me.html(oldButtonHtml);
159
- alert(data);
160
- }
161
- }
162
- );
163
-
164
- return false;
165
- });
166
-
167
- //The "Undismiss" button.
168
- $(".blc-undismiss-button").click(function () {
169
- var me = $(this);
170
- var oldButtonHtml = me.html();
171
- me.html(ajaxInProgressHtml);
172
-
173
- var master = me.closest('.blc-row');
174
- var link_id = master.attr('id').split('-')[2];
175
- var should_hide_link = (blc_current_base_filter == 'dismissed');
176
-
177
- $.post(
178
- "<?php echo admin_url('admin-ajax.php'); ?>",
179
- {
180
- 'action' : 'blc_undismiss',
181
- 'link_id' : link_id,
182
- '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_undismiss')); ?>'
183
- },
184
- function (data, textStatus){
185
- if (data == 'OK'){
186
- var details = $('#link-details-'+link_id);
187
-
188
- //Remove the action.
189
- me.parent().hide();
190
-
191
- //Flash the main row green to indicate success, then remove it if necessary.
192
- flashElementGreen(master, function(){
193
- if ( should_hide_link ){
194
- details.remove();
195
- master.remove();
196
- }
197
- });
198
-
199
- //Update the elements displaying the number of results for the current filter.
200
- if( should_hide_link ){
201
- alterLinkCounter(-1);
202
- }
203
- } else {
204
- me.html(oldButtonHtml);
205
- alert(data);
206
- }
207
- }
208
- );
209
-
210
- return false;
211
- });
212
-
213
- //The "Recheck" button.
214
- $(".blc-recheck-button").click(function () {
215
- var me = $(this);
216
- var oldButtonHtml = me.html();
217
- me.html(ajaxInProgressHtml);
218
-
219
- var master = me.closest('.blc-row');
220
- var link_id = master.attr('id').split('-')[2];
221
-
222
- $.post(
223
- "<?php echo admin_url('admin-ajax.php'); ?>",
224
- {
225
- 'action' : 'blc_recheck',
226
- 'link_id' : link_id,
227
- '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_recheck')); ?>'
228
- },
229
- function (response){
230
- me.html(oldButtonHtml);
231
-
232
- if (response && (typeof(response['error']) != 'undefined')){
233
- //An internal error occurred before the plugin could check the link (e.g. database error).
234
- alert(response.error);
235
- } else {
236
- //Display the new status in the link row.
237
- displayLinkStatus(master, response);
238
- reloadDetailsRow(link_id);
239
-
240
- //Flash the row green to indicate success
241
- flashElementGreen(master);
242
- }
243
- },
244
- 'json'
245
- );
246
-
247
- return false;
248
- });
249
-
250
- //The "Fix redirect" action.
251
- $('.blc-deredirect-button').click(function() {
252
- //This action can only be used once. If it succeeds, it will no longer be applicable to the current link.
253
- //If it fails, something is broken and trying again probably won't help.
254
- var me = $(this);
255
- me.text(ajaxInProgressHtml);
256
-
257
- var master = me.closest('.blc-row');
258
- var linkId = master.attr('id').split('-')[2];
259
- var shouldHideLink = blc_current_base_filter == 'redirects';
260
- var details = $('#link-details-' + linkId);
261
-
262
- $.post(
263
- "<?php echo admin_url('admin-ajax.php'); ?>",
264
- {
265
- 'action' : 'blc_deredirect',
266
- 'link_id' : linkId,
267
- '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_deredirect')); ?>'
268
- },
269
- function (response){
270
- me.closest('span').hide();
271
-
272
- if (handleEditResponse(response, master, linkId, null)) {
273
- if (shouldHideLink) {
274
- details.remove();
275
- master.remove();
276
- }
277
- }
278
- },
279
- 'json'
280
- );
281
-
282
- return false;
283
- });
284
-
285
- function flashElementGreen(element, callback) {
286
- var oldColor = element.css('background-color');
287
- element.animate({ backgroundColor: "#E0FFB3" }, 200).animate({ backgroundColor: oldColor }, 300, callback);
288
- }
289
-
290
-
291
- /**
292
- * Update status indicators for a link. This includes the contents of the "Status" column, CSS classes and so on.
293
- *
294
- * @param {Object} row Table row as a jQuery object.
295
- * @param {Object} status
296
- */
297
- function displayLinkStatus(row, status) {
298
- //Update the status code and class.
299
- var statusColumn = row.find('td.column-status');
300
- if (status.status_text) {
301
- statusColumn.find('.status-text').text(status.status_text);
302
- }
303
- statusColumn.find('.http-code').text(status.http_code ? status.http_code : '');
304
-
305
- var oldStatusClass = row.attr('class').match(/(?:^|\s)(link-status-[^\s]+)(?:\s|$)/);
306
- oldStatusClass = oldStatusClass ? oldStatusClass[1] : '';
307
- var newStatusClass = 'link-status-' + status.status_code;
308
-
309
- statusColumn.find('.link-status-row').removeClass(oldStatusClass).addClass(newStatusClass);
310
- row.removeClass(oldStatusClass).addClass(newStatusClass);
311
-
312
- //Last check time and failure duration are complicated to update, so we'll just hide them.
313
- //The user can refresh the page to get the new values.
314
- statusColumn.find('.link-last-checked td').html('&nbsp;');
315
- statusColumn.find('.link-broken-for td').html('&nbsp;');
316
-
317
- //The link may or may not be a redirect now.
318
- row.toggleClass('blc-redirect', status.redirect_count > 0);
319
-
320
- if (typeof status['redirect_count'] !== 'undefined') {
321
- var redirectColumn = row.find('td.column-redirect-url').empty();
322
-
323
- if (status.redirect_count > 0 && status.final_url) {
324
- redirectColumn.append(
325
- $(
326
- '<a></a>',
327
- {
328
- href: status.final_url,
329
- text: status.final_url,
330
- title: status.final_url,
331
- 'class': 'blc-redirect-url',
332
- target: '_blank'
333
- }
334
- )
335
- );
336
- }
337
- }
338
- }
339
-
340
-
341
- /**
342
- * Display the inline link editor.
343
- *
344
- * @param {Number} link_id Link ID. The link must be visible in the current view.
345
- */
346
- function showLinkEditor(link_id) {
347
- var master = $('#blc-row-' + link_id),
348
- editorId = 'blc-edit-row-' + link_id,
349
- editRow;
350
-
351
- //Get rid of all existing inline editors.
352
- master.closest('table').find('tr.blc-inline-editor').each(function() {
353
- hideLinkEditor($(this));
354
- });
355
-
356
- //Create an inline editor for this link.
357
- editRow = $('#blc-inline-edit-row').clone(true).attr('id', editorId);
358
- editRow.toggleClass('alternate', master.hasClass('alternate'));
359
- master.after(editRow);
360
-
361
- //Populate editor fields.
362
- var urlElement = master.find('a.blc-link-url');
363
- var linkUrl = urlElement.data('editable-url') || urlElement.attr('href');
364
- var urlInput = editRow.find('.blc-link-url-field').val(linkUrl);
365
-
366
- var titleInput = editRow.find('.blc-link-text-field');
367
- var linkText = master.data('link-text'),
368
- canEditText = master.data('can-edit-text') == 1, //jQuery will convert a '1' to 1 (number) when reading a data attribute.
369
- canEditUrl = master.data('can-edit-url') == 1,
370
- noneText = '<?php echo esc_js(_x('(None)', 'link text', 'broken-link-checker')); ?>',
371
- multipleLinksText = '<?php echo esc_js(_x('(Multiple links)', 'link text', 'broken-link-checker')); ?>';
372
-
373
- titleInput.prop('readonly', !canEditText);
374
- urlInput.prop('readonly', !canEditUrl);
375
-
376
- if ( (typeof linkText !== 'undefined') && (linkText !== null) ) {
377
- if (linkText === '') {
378
- titleInput.val(canEditText ? linkText : noneText);
379
- } else {
380
- titleInput.val(linkText)
381
- }
382
- titleInput.prop('placeholder', noneText);
383
- } else {
384
- if (canEditText) {
385
- titleInput.val('').prop('placeholder', multipleLinksText);
386
- } else {
387
- titleInput.val(multipleLinksText)
388
- }
389
- }
390
-
391
- //Populate the list of URL replacement suggestions.
392
- if (canEditUrl && blc_suggestions_enabled && (master.hasClass('link-status-error') || master.hasClass('link-status-warning'))) {
393
- editRow.find('.blc-url-replacement-suggestions').show();
394
- var suggestionList = editRow.find('.blc-suggestion-list');
395
- findReplacementSuggestions(linkUrl, suggestionList);
396
- }
397
-
398
- editRow.find('.blc-update-link-button').prop('disabled', !(canEditUrl || canEditText));
399
-
400
- //Make the editor span the entire width of the table.
401
- editRow.find('td.blc-colspan-change').attr('colspan', master.closest('table').find('thead th:visible').length);
402
-
403
- master.hide();
404
- editRow.show();
405
- urlInput.focus();
406
- if (canEditUrl) {
407
- urlInput.select();
408
- }
409
- }
410
-
411
- /**
412
- * Hide the inline editor for a particular link.
413
- *
414
- * @param link_id Either a numeric link ID or a jQuery object that represents the editor row.
415
- */
416
- function hideLinkEditor(link_id) {
417
- var editRow = isNaN(link_id) ? link_id : $('#blc-edit-row-' + link_id);
418
- editRow.prev('tr.blc-row').show();
419
- editRow.remove();
420
- }
421
-
422
- /**
423
- * Find possible replacements for a broken link and display them in a list.
424
- *
425
- * @param {String} url The current link URL.
426
- * @param suggestionList jQuery object that represents a list element.
427
- */
428
- function findReplacementSuggestions(url, suggestionList) {
429
- var searchingText = '<?php echo esc_js(_x('Searching...', 'link suggestions', 'broken-link-checker')) ?>';
430
- var noSuggestionsText = '<?php echo esc_js(_x('No suggestions available.', 'link suggestions', 'broken-link-checker')) ?>';
431
- var iaSuggestionName = '<?php echo esc_js(_x('Archived page from %s (via the Wayback Machine)', 'link suggestions', 'broken-link-checker')); ?>';
432
-
433
- suggestionList.empty().append('<li>' + searchingText + '</li>');
434
-
435
- var suggestionTemplate = $('#blc-suggestion-template').find('li').first();
436
-
437
- //Check the Wayback Machine for an archived version of the page.
438
- $.getJSON(
439
- 'https://archive.org/wayback/available?callback=?',
440
- { url: url },
441
-
442
- function(data) {
443
- suggestionList.empty();
444
-
445
- //Check if there are any results.
446
- if (!data || !data.archived_snapshots || !data.archived_snapshots.closest || !data.archived_snapshots.closest.available ) {
447
- suggestionList.append('<li>' + noSuggestionsText + '</li>');
448
- return;
449
- }
450
-
451
- var snapshot = data.archived_snapshots.closest;
452
-
453
- //Convert the timestamp from YYYYMMDDHHMMSS to ISO 8601 date format.
454
- var readableTimestamp = snapshot.timestamp.substr(0, 4) +
455
- '-' + snapshot.timestamp.substr(4, 2) +
456
- '-' + snapshot.timestamp.substr(6, 2);
457
- var name = sprintf(iaSuggestionName, readableTimestamp);
458
-
459
- //Enforce HTTPS by default
460
- snapshot.url = (snapshot.url).replace( new RegExp("^http:", "m"), "https:");
461
-
462
- //Display the suggestion.
463
- var item = suggestionTemplate.clone();
464
- item.find('.blc-suggestion-name a').text(name).attr('href', snapshot.url);
465
- item.find('.blc-suggestion-url').text(snapshot.url);
466
- suggestionList.append(item);
467
- }
468
- );
469
- }
470
-
471
- /**
472
- * Call our PHP backend and tell it to edit all occurrences of particular link.
473
- * Updates UI with the new link info and displays any error messages that might be generated.
474
- *
475
- * @param linkId Either a numeric link ID or a jQuery object representing the link row.
476
- * @param {String} newUrl The new link URL.
477
- * @param {String} newText The new link text. Optional. Set to null to leave it unchanged.
478
- */
479
- function updateLink(linkId, newUrl, newText) {
480
- var master, editRow;
481
- if ( isNaN(linkId) ){
482
- master = linkId;
483
- linkId = master.attr('id').split("-")[2]; //id="blc-row-$linkid"
484
- } else {
485
- master = $('#blc-row-' + linkId);
486
- }
487
- editRow = $('#blc-edit-row-' + linkId);
488
-
489
- var urlElement = master.find('a.blc-link-url');
490
- var progressIndicator = editRow.find('.waiting'),
491
- updateButton = editRow.find('.blc-update-link-button');
492
- progressIndicator.show();
493
- updateButton.prop('disabled', true);
494
-
495
- $.post(
496
- '<?php echo admin_url('admin-ajax.php'); ?>',
497
- {
498
- 'action' : 'blc_edit',
499
- 'link_id' : linkId,
500
- 'new_url' : newUrl,
501
- 'new_text' : newText,
502
- '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_edit')); ?>'
503
- },
504
- function(response) {
505
- progressIndicator.hide();
506
- updateButton.prop('disabled', false);
507
-
508
- handleEditResponse(response, master, linkId, newText);
509
-
510
- hideLinkEditor(editRow);
511
- },
512
- 'json'
513
- );
514
-
515
- }
516
-
517
- function handleEditResponse(response, master, linkId, newText) {
518
- if (response && (typeof(response['error']) != 'undefined')){
519
- //An internal error occurred before the link could be edited.
520
- alert(response.error);
521
- return false;
522
- } else if (response.errors.length > 0) {
523
- //Build and display an error message.
524
- var msg = '';
525
-
526
- if ( response.cnt_okay > 0 ){
527
- var fragment = sprintf(
528
- '<?php echo esc_js(__('%d instances of the link were successfully modified.', 'broken-link-checker')); ?>',
529
- response.cnt_okay
530
- );
531
- msg = msg + fragment + '\n';
532
- if ( response.cnt_error > 0 ){
533
- fragment = sprintf(
534
- '<?php echo esc_js(__("However, %d instances couldn't be edited and still point to the old URL.", 'broken-link-checker')); ?>',
535
- response.cnt_error
536
- );
537
- msg = msg + fragment + "\n";
538
- }
539
- } else {
540
- msg = msg + '<?php echo esc_js(__('The link could not be modified.', 'broken-link-checker')); ?>\n';
541
- }
542
-
543
- msg = msg + '\n<?php echo esc_js(__("The following error(s) occurred :", 'broken-link-checker')); ?>\n* ';
544
- msg = msg + response.errors.join('\n* ');
545
-
546
- alert(msg);
547
- return false;
548
- } else {
549
- //Everything went well. Update the link row with the new values.
550
-
551
- //Replace the displayed link URL with the new one.
552
- var urlElement = master.find('a.blc-link-url');
553
- urlElement
554
- .attr('href', response.url)
555
- .text(response.url)
556
- .data('editable-url', response.url)
557
- .prop('title', response.url);
558
- if ( typeof response['escaped_url'] != 'undefined' ) {
559
- urlElement.attr('href', response.escaped_url)
560
- }
561
-
562
- //Save the new ID
563
- replaceLinkId(linkId, response.new_link_id);
564
- //Load up the new link info
565
- reloadDetailsRow(response.new_link_id);
566
-
567
- //Update the link text if it was edited.
568
- if ((newText !== null) && (response.link_text !== null)) {
569
- master.data('link-text', response.link_text);
570
- if (response.ui_link_text !== null) {
571
- master.find('.column-new-link-text').html(response.ui_link_text);
572
- }
573
- }
574
-
575
- //Update the status code and class.
576
- displayLinkStatus(master, response);
577
-
578
- //Flash the row green to indicate success
579
- flashElementGreen(master);
580
-
581
- return true;
582
- }
583
- }
584
-
585
- //The "Edit URL" button - displays the inline editor
586
- $(".blc-edit-button").click(function () {
587
- var master = $(this).closest('.blc-row');
588
- var link_id = master.attr('id').split('-')[2];
589
- showLinkEditor(link_id);
590
- });
591
-
592
- //Let the user use Enter and Esc as shortcuts for "Update" and "Cancel"
593
- $('.blc-inline-editor input[type="text"]').keypress(function (e) {
594
- var editRow = $(this).closest('.blc-inline-editor');
595
- if (e.which == 13) {
596
- editRow.find('.blc-update-link-button').click();
597
- return false;
598
- } else if (e.which == 27) {
599
- editRow.find('.blc-cancel-button').click();
600
- return false;
601
- }
602
- return true;
603
- });
604
-
605
-
606
- //The "Update" button in the inline editor.
607
- $('.blc-update-link-button').click(function() {
608
- var editRow = $(this).closest('tr'),
609
- master = editRow.prev('.blc-row');
610
-
611
- //Ensure the new URL is not empty.
612
- var urlField = editRow.find('.blc-link-url-field');
613
- var newUrl = urlField.val();
614
- if ($.trim(newUrl) == '') {
615
- alert('<?php echo esc_js(__('Error: Link URL must not be empty.', 'broken-link-checker')); ?>');
616
- urlField.focus();
617
- return;
618
- }
619
-
620
- var newLinkText = null,
621
- linkTextField = editRow.find('.blc-link-text-field'),
622
- oldLinkText = master.data('link-text');
623
- if (!linkTextField.prop('readonly')) {
624
- newLinkText = linkTextField.val();
625
- //Empty or identical to the original = leave the text unchanged.
626
- if ((newLinkText === '') || (newLinkText === oldLinkText)) {
627
- newLinkText = null;
628
- }
629
- }
630
-
631
- updateLink(master, newUrl, newLinkText);
632
- });
633
-
634
- //The "Cancel" in the inline editor.
635
- $(".blc-cancel-button").click(function () {
636
- var editRow = $(this).closest('tr');
637
- hideLinkEditor(editRow);
638
- });
639
-
640
- //The "Use this URL" button in the inline editor replaces the link URL
641
- //with the selected suggestion URL.
642
- $('#blc-links').on('click', '.blc-use-url-button', function() {
643
- var button = $(this);
644
- var suggestionUrl = button.closest('tr').find('.blc-suggestion-name a').attr('href');
645
- button.closest('.blc-inline-editor').find('.blc-link-url-field').val(suggestionUrl);
646
- });
647
-
648
-
649
- //The "Unlink" button - remove the link/image from all posts, custom fields, etc.
650
- $(".blc-unlink-button").click(function () {
651
- var me = this;
652
- var master = $(me).parents('.blc-row');
653
- $(me).html('<?php echo esc_js(__('Wait...' , 'broken-link-checker')); ?>');
654
-
655
- //Find the link ID
656
- var link_id = master.attr('id').split('-')[2];
657
-
658
- $.post(
659
- "<?php echo admin_url('admin-ajax.php'); ?>",
660
- {
661
- 'action' : 'blc_unlink',
662
- 'link_id' : link_id,
663
- '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_unlink')); ?>'
664
- },
665
- function (data, textStatus){
666
- eval('data = ' + data);
667
-
668
- if ( data && (typeof(data['error']) != 'undefined') ){
669
- //An internal error occurred before the link could be edited.
670
- //data.error is an error message.
671
- alert(data.error);
672
- } else {
673
- if ( data.errors.length == 0 ){
674
- //The link was successfully removed. Hide its details.
675
- $('#link-details-'+link_id).hide();
676
- //Flash the main row green to indicate success, then hide it.
677
- var oldColor = master.css('background-color');
678
- master.animate({ backgroundColor: "#E0FFB3" }, 200).animate({ backgroundColor: oldColor }, 300, function(){
679
- master.hide();
680
- });
681
-
682
- alterLinkCounter(-1);
683
-
684
- return;
685
- } else {
686
- //Build and display an error message.
687
- var msg = '';
688
-
689
- if ( data.cnt_okay > 0 ){
690
- msg = msg + sprintf(
691
- '<?php echo esc_js(__("%d instances of the link were successfully unlinked.", 'broken-link-checker')); ?>\n',
692
- data.cnt_okay
693
- );
694
-
695
- if ( data.cnt_error > 0 ){
696
- msg = msg + sprintf(
697
- '<?php echo esc_js(__("However, %d instances couldn't be removed.", 'broken-link-checker')); ?>\n',
698
- data.cnt_error
699
- );
700
- }
701
- } else {
702
- msg = msg + '<?php echo esc_js(__("The plugin failed to remove the link.", 'broken-link-checker')); ?>\n';
703
- }
704
-
705
- msg = msg + '\n<?php echo esc_js(__("The following error(s) occured :", 'broken-link-checker')); ?>\n* ';
706
- msg = msg + data.errors.join('\n* ');
707
-
708
- //Show the error message
709
- alert(msg);
710
- }
711
- }
712
-
713
- $(me).html('<?php echo esc_js(__('Unlink' , 'broken-link-checker')); ?>');
714
- }
715
- );
716
- });
717
-
718
- //--------------------------------------------
719
- //The search box(es)
720
- //--------------------------------------------
721
-
722
- var searchForm = $('#search-links-dialog');
723
-
724
- searchForm.dialog({
725
- autoOpen : false,
726
- dialogClass : 'blc-search-container',
727
- resizable: false
728
- });
729
-
730
- $('#blc-open-search-box').click(function(){
731
- if ( searchForm.dialog('isOpen') ){
732
- searchForm.dialog('close');
733
- } else {
734
- searchForm
735
- .dialog('open')
736
- .dialog('widget')
737
- .position({
738
- my: 'right top',
739
- at: 'right bottom',
740
- of: $('#blc-open-search-box')
741
- });
742
- }
743
- });
744
-
745
- $('#blc-cancel-search').click(function(){
746
- searchForm.dialog('close');
747
- });
748
-
749
- //The "Save This Search Query" button creates a new custom filter based on the current search
750
- $('#blc-create-filter').click(function(){
751
- var filter_name = prompt("<?php echo esc_js(__("Enter a name for the new custom filter", 'broken-link-checker')); ?>", "");
752
- if ( filter_name ){
753
- $('#blc-custom-filter-name').val(filter_name);
754
- $('#custom-filter-form').submit();
755
- }
756
- });
757
-
758
- //Display a confirmation dialog when the user clicks the "Delete This Filter" button
759
- $('#blc-delete-filter').click(function(){
760
- var message = '<?php
761
- echo esc_js(
762
- html_entity_decode(
763
- __("You are about to delete the current filter.\n'Cancel' to stop, 'OK' to delete", 'broken-link-checker'),
764
- ENT_QUOTES,
765
- get_bloginfo('charset')
766
- )
767
- );
768
- ?>';
769
- return confirm(message);
770
- });
771
-
772
- //--------------------------------------------
773
- // Bulk actions
774
- //--------------------------------------------
775
-
776
- $('#blc-bulk-action-form').submit(function(){
777
- var action = $('#blc-bulk-action').val(), message;
778
- if ( action == '-1' ){
779
- action = $('#blc-bulk-action2').val();
780
- }
781
-
782
- if ( action == 'bulk-delete-sources' ){
783
- //Convey the gravitas of deleting link sources.
784
- message = '<?php
785
- echo esc_js(
786
- html_entity_decode(
787
- __("Are you sure you want to delete all posts, bookmarks or other items that contain any of the selected links? This action can't be undone.\n'Cancel' to stop, 'OK' to delete", 'broken-link-checker'),
788
- ENT_QUOTES,
789
- get_bloginfo('charset')
790
- )
791
- );
792
- ?>';
793
- if ( !confirm(message) ){
794
- return false;
795
- }
796
- } else if ( action == 'bulk-unlink' ){
797
- //Likewise for unlinking.
798
- message = '<?php
799
- echo esc_js(
800
- html_entity_decode(
801
- __("Are you sure you want to remove the selected links? This action can't be undone.\n'Cancel' to stop, 'OK' to remove", 'broken-link-checker'),
802
- ENT_QUOTES,
803
- get_bloginfo('charset')
804
- )
805
- );
806
- ?>';
807
- if ( !confirm(message) ){
808
- return false;
809
- }
810
- }
811
- });
812
-
813
- //Automatically disable bulk actions that don't apply to the currently selected links.
814
- $('#blc-bulk-action').focus(function() {
815
- var redirectsSelected = false, brokenLinksSelected = false;
816
- $('tr th.check-column input:checked', '#blc-links').each(function() {
817
- var row = $(this).closest('tr');
818
- if (row.hasClass('blc-redirect')) {
819
- redirectsSelected = true
820
- }
821
- if (row.hasClass('link-status-error') || row.hasClass('link-status-warning')) {
822
- brokenLinksSelected = true;
823
- }
824
- });
825
-
826
- var bulkAction = $(this);
827
- bulkAction.find('option[value="bulk-deredirect"]').prop('disabled', !redirectsSelected);
828
- bulkAction.find('option[value="bulk-not-broken"]').prop('disabled', !brokenLinksSelected);
829
- });
830
-
831
- //------------------------------------------------------------
832
- // Manipulate highlight settings for permanently broken links
833
- //------------------------------------------------------------
834
- var highlight_permanent_failures_checkbox = $('#highlight_permanent_failures');
835
- var failure_duration_threshold_input = $('#failure_duration_threshold');
836
-
837
- //Apply/remove highlights when the checkbox is (un)checked
838
- highlight_permanent_failures_checkbox.change(function(){
839
- //save_highlight_settings();
840
-
841
- if ( this.checked ){
842
- $('#blc-links tr.blc-permanently-broken').addClass('blc-permanently-broken-hl');
843
- } else {
844
- $('#blc-links tr.blc-permanently-broken').removeClass('blc-permanently-broken-hl');
845
- }
846
- });
847
-
848
- //Apply/remove highlights when the duration threshold is changed.
849
- failure_duration_threshold_input.change(function(){
850
- var new_threshold = parseInt($(this).val());
851
- //save_highlight_settings();
852
- if (isNaN(new_threshold) || (new_threshold < 1)) {
853
- return;
854
- }
855
-
856
- highlight_permanent_failures = highlight_permanent_failures_checkbox.is(':checked');
857
-
858
- $('#blc-links tr.blc-row').each(function(index){
859
- var days_broken = $(this).attr('data-days-broken');
860
- if ( days_broken >= new_threshold ){
861
- $(this).addClass('blc-permanently-broken');
862
- if ( highlight_permanent_failures ){
863
- $(this).addClass('blc-permanently-broken-hl');
864
- }
865
- } else {
866
- $(this).removeClass('blc-permanently-broken').removeClass('blc-permanently-broken-hl');
867
- }
868
- });
869
- });
870
-
871
- //Show/hide table columns dynamically
872
- $('#blc-column-selector input[type="checkbox"]').change(function(){
873
- var checkbox = $(this);
874
- var column_id = checkbox.attr('name').split(/\[|\]/)[1];
875
- if (checkbox.is(':checked')){
876
- $('td.column-'+column_id+', th.column-'+column_id, '#blc-links').removeClass('hidden');
877
- } else {
878
- $('td.column-'+column_id+', th.column-'+column_id, '#blc-links').addClass('hidden');
879
- }
880
-
881
- //Recalculate colspan's for detail rows to take into account the changed number of
882
- //visible columns. Otherwise you can get some ugly layout glitches.
883
- $('#blc-links tr.blc-link-details td').attr(
884
- 'colspan',
885
- $('#blc-column-selector input[type="checkbox"]:checked').length+1
886
- );
887
- });
888
-
889
- //Unlike other fields in "Screen Options", the links-per-page setting
890
- //is handled using straight form submission (POST), not AJAX.
891
- $('#blc-per-page-apply-button').click(function(){
892
- $('#adv-settings').submit();
893
- });
894
-
895
- $('#blc_links_per_page').keypress(function(e){
896
- if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
897
- $('#adv-settings').submit();
898
- }
899
- });
900
-
901
- //Toggle status code colors when the corresponding checkbox is toggled
902
- $('#table_color_code_status').click(function(){
903
- if ( $(this).is(':checked') ){
904
- $('#blc-links').addClass('color-code-link-status');
905
- } else {
906
- $('#blc-links').removeClass('color-code-link-status');
907
- }
908
- });
909
-
910
- //Show the bulk edit/find & replace form when the user applies the appropriate bulk action
911
- $('#doaction, #doaction2').click(function(e){
912
- var n = $(this).attr('id').substr(2);
913
- if ( $('select[name="'+n+'"]').val() == 'bulk-edit' ) {
914
- e.preventDefault();
915
- //Any links selected?
916
- if ($('tbody th.check-column input:checked').length > 0){
917
- $('#bulk-edit').show();
918
- }
919
- }
920
- });
921
-
922
- //Hide the bulk edit/find & replace form when "Cancel" is clicked
923
- $('#bulk-edit .cancel').click(function(){
924
- $('#bulk-edit').hide();
925
- return false;
926
- });
927
-
928
- //Minimal input validation for the bulk edit form
929
- $('#bulk-edit input[type="submit"]').click(function(e){
930
- if( $('#bulk-edit input[name="search"]').val() == '' ){
931
- alert('<?php echo esc_js(__('Enter a search string first.', 'broken-link-checker')); ?>');
932
- $('#bulk-edit input[name="search"]').focus();
933
- e.preventDefault();
934
- return;
935
- }
936
-
937
- if ($('tbody th.check-column input:checked').length == 0){
938
- alert('<?php echo esc_js(__('Select one or more links to edit.', 'broken-link-checker')); ?>');
939
- e.preventDefault();
940
- }
941
- });
942
-
943
-
944
- });
945
-
946
  </script>
1
+ <script type='text/javascript'>
2
+
3
+ function alterLinkCounter(factor, filterId){
4
+ var counter;
5
+ if (filterId) {
6
+ counter = jQuery('.filter-' + filterId + '-link-count');
7
+ } else {
8
+ counter = jQuery('.current-link-count');
9
+ }
10
+
11
+ var cnt = parseInt(counter.eq(0).html(), 10);
12
+ cnt = cnt + factor;
13
+ counter.html(cnt);
14
+
15
+ if ( blc_is_broken_filter ){
16
+ //Update the broken link count displayed beside the "Broken Links" menu
17
+ var menuBubble = jQuery('span.blc-menu-bubble');
18
+ if ( menuBubble.length > 0 ){
19
+ cnt = parseInt(menuBubble.eq(0).html());
20
+ cnt = cnt + factor;
21
+ if ( cnt > 0 ){
22
+ menuBubble.html(cnt);
23
+ } else {
24
+ menuBubble.parent().hide();
25
+ }
26
+ }
27
+ }
28
+ }
29
+
30
+ function replaceLinkId(old_id, new_id){
31
+ var master = jQuery('#blc-row-'+old_id);
32
+
33
+ master.attr('id', 'blc-row-'+new_id);
34
+ master.find('.blc-link-id').html(new_id);
35
+ master.find('th.check-column input[type="checkbox"]').val(new_id);
36
+
37
+ var details_row = jQuery('#link-details-'+old_id);
38
+ details_row.attr('id', 'link-details-'+new_id);
39
+ }
40
+
41
+ function reloadDetailsRow(link_id){
42
+ var details_row = jQuery('#link-details-'+link_id);
43
+
44
+ //Load up the new link info (so sue me)
45
+ details_row.find('td').html('<center><?php echo esc_js(__('Loading...' , 'broken-link-checker')); ?></center>').load(
46
+ "<?php echo admin_url('admin-ajax.php'); ?>",
47
+ {
48
+ 'action' : 'blc_link_details',
49
+ 'link_id' : link_id
50
+ }
51
+ );
52
+ }
53
+
54
+ jQuery(function($){
55
+
56
+ //The details button - display/hide detailed info about a link
57
+ $(".blc-details-button, td.column-link-text, td.column-status, td.column-new-link-text").click(function () {
58
+ var master = $(this).parents('.blc-row');
59
+ var link_id = master.attr('id').split('-')[2];
60
+ $('#link-details-'+link_id).toggle();
61
+ return false;
62
+ });
63
+
64
+ var ajaxInProgressHtml = '<?php echo esc_js(__('Wait...', 'broken-link-checker')); ?>';
65
+
66
+ //The "Not broken" button - manually mark the link as valid. The link will be checked again later.
67
+ $(".blc-discard-button").click(function () {
68
+ var me = $(this);
69
+ me.html(ajaxInProgressHtml);
70
+
71
+ var master = me.parents('.blc-row');
72
+ var link_id = master.attr('id').split('-')[2];
73
+
74
+ $.post(
75
+ "<?php echo admin_url('admin-ajax.php'); ?>",
76
+ {
77
+ 'action' : 'blc_discard',
78
+ 'link_id' : link_id,
79
+ '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_discard')); ?>'
80
+ },
81
+ function (data, textStatus){
82
+ if (data == 'OK'){
83
+ var details = $('#link-details-'+link_id);
84
+
85
+ //Remove the "Not broken" action
86
+ me.parent().remove();
87
+
88
+ //Set the displayed link status to OK
89
+ var classNames = master.attr('class');
90
+ classNames = classNames.replace(/(^|\s)link-status-[^\s]+(\s|$)/, ' ') + ' link-status-ok';
91
+ master.attr('class', classNames);
92
+
93
+ //Flash the main row green to indicate success, then remove it if the current view
94
+ //is supposed to show only broken links or warnings.
95
+ var should_hide_link = blc_is_broken_filter || (blc_current_base_filter == 'warnings');
96
+
97
+ flashElementGreen(master, function(){
98
+ if ( should_hide_link ){
99
+ details.remove();
100
+ master.remove();
101
+ } else {
102
+ reloadDetailsRow(link_id);
103
+ }
104
+ });
105
+
106
+ //Update the elements displaying the number of results for the current filter.
107
+ if( should_hide_link ){
108
+ alterLinkCounter(-1);
109
+ }
110
+ } else {
111
+ me.html('<?php echo esc_js(__('Not broken' , 'broken-link-checker')); ?>');
112
+ alert(data);
113
+ }
114
+ }
115
+ );
116
+
117
+ return false;
118
+ });
119
+
120
+ //The "Dismiss" button - hide the link from the "Broken" and "Redirects" filters, but still apply link tweaks and so on.
121
+ $(".blc-dismiss-button").click(function () {
122
+ var me = $(this);
123
+ var oldButtonHtml = me.html();
124
+ me.html(ajaxInProgressHtml);
125
+
126
+ var master = me.closest('.blc-row');
127
+ var link_id = master.attr('id').split('-')[2];
128
+ var should_hide_link = $.inArray(blc_current_base_filter, ['broken', 'redirects', 'warnings']) > -1;
129
+
130
+ $.post(
131
+ "<?php echo admin_url('admin-ajax.php'); ?>",
132
+ {
133
+ 'action' : 'blc_dismiss',
134
+ 'link_id' : link_id,
135
+ '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_dismiss')); ?>'
136
+ },
137
+ function (data, textStatus){
138
+ if (data == 'OK'){
139
+ var details = $('#link-details-'+link_id);
140
+
141
+ //Remove the "Dismiss" action
142
+ me.parent().hide();
143
+
144
+ //Flash the main row green to indicate success, then remove it if necessary.
145
+ flashElementGreen(master, function(){
146
+ if ( should_hide_link ){
147
+ details.remove();
148
+ master.remove();
149
+ }
150
+ });
151
+
152
+ //Update the elements displaying the number of results for the current filter.
153
+ if( should_hide_link ){
154
+ alterLinkCounter(-1);
155
+ alterLinkCounter(1, 'dismissed');
156
+ }
157
+ } else {
158
+ me.html(oldButtonHtml);
159
+ alert(data);
160
+ }
161
+ }
162
+ );
163
+
164
+ return false;
165
+ });
166
+
167
+ //The "Undismiss" button.
168
+ $(".blc-undismiss-button").click(function () {
169
+ var me = $(this);
170
+ var oldButtonHtml = me.html();
171
+ me.html(ajaxInProgressHtml);
172
+
173
+ var master = me.closest('.blc-row');
174
+ var link_id = master.attr('id').split('-')[2];
175
+ var should_hide_link = (blc_current_base_filter == 'dismissed');
176
+
177
+ $.post(
178
+ "<?php echo admin_url('admin-ajax.php'); ?>",
179
+ {
180
+ 'action' : 'blc_undismiss',
181
+ 'link_id' : link_id,
182
+ '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_undismiss')); ?>'
183
+ },
184
+ function (data, textStatus){
185
+ if (data == 'OK'){
186
+ var details = $('#link-details-'+link_id);
187
+
188
+ //Remove the action.
189
+ me.parent().hide();
190
+
191
+ //Flash the main row green to indicate success, then remove it if necessary.
192
+ flashElementGreen(master, function(){
193
+ if ( should_hide_link ){
194
+ details.remove();
195
+ master.remove();
196
+ }
197
+ });
198
+
199
+ //Update the elements displaying the number of results for the current filter.
200
+ if( should_hide_link ){
201
+ alterLinkCounter(-1);
202
+ }
203
+ } else {
204
+ me.html(oldButtonHtml);
205
+ alert(data);
206
+ }
207
+ }
208
+ );
209
+
210
+ return false;
211
+ });
212
+
213
+ //The "Recheck" button.
214
+ $(".blc-recheck-button").click(function () {
215
+ var me = $(this);
216
+ var oldButtonHtml = me.html();
217
+ me.html(ajaxInProgressHtml);
218
+
219
+ var master = me.closest('.blc-row');
220
+ var link_id = master.attr('id').split('-')[2];
221
+
222
+ $.post(
223
+ "<?php echo admin_url('admin-ajax.php'); ?>",
224
+ {
225
+ 'action' : 'blc_recheck',
226
+ 'link_id' : link_id,
227
+ '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_recheck')); ?>'
228
+ },
229
+ function (response){
230
+ me.html(oldButtonHtml);
231
+
232
+ if (response && (typeof(response['error']) != 'undefined')){
233
+ //An internal error occurred before the plugin could check the link (e.g. database error).
234
+ alert(response.error);
235
+ } else {
236
+ //Display the new status in the link row.
237
+ displayLinkStatus(master, response);
238
+ reloadDetailsRow(link_id);
239
+
240
+ //Flash the row green to indicate success
241
+ flashElementGreen(master);
242
+ }
243
+ },
244
+ 'json'
245
+ );
246
+
247
+ return false;
248
+ });
249
+
250
+ //The "Fix redirect" action.
251
+ $('.blc-deredirect-button').click(function() {
252
+ //This action can only be used once. If it succeeds, it will no longer be applicable to the current link.
253
+ //If it fails, something is broken and trying again probably won't help.
254
+ var me = $(this);
255
+ me.text(ajaxInProgressHtml);
256
+
257
+ var master = me.closest('.blc-row');
258
+ var linkId = master.attr('id').split('-')[2];
259
+ var shouldHideLink = blc_current_base_filter == 'redirects';
260
+ var details = $('#link-details-' + linkId);
261
+
262
+ $.post(
263
+ "<?php echo admin_url('admin-ajax.php'); ?>",
264
+ {
265
+ 'action' : 'blc_deredirect',
266
+ 'link_id' : linkId,
267
+ '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_deredirect')); ?>'
268
+ },
269
+ function (response){
270
+ me.closest('span').hide();
271
+
272
+ if (handleEditResponse(response, master, linkId, null)) {
273
+ if (shouldHideLink) {
274
+ details.remove();
275
+ master.remove();
276
+ }
277
+ }
278
+ },
279
+ 'json'
280
+ );
281
+
282
+ return false;
283
+ });
284
+
285
+ function flashElementGreen(element, callback) {
286
+ var oldColor = element.css('background-color');
287
+ element.animate({ backgroundColor: "#E0FFB3" }, 200).animate({ backgroundColor: oldColor }, 300, callback);
288
+ }
289
+
290
+
291
+ /**
292
+ * Update status indicators for a link. This includes the contents of the "Status" column, CSS classes and so on.
293
+ *
294
+ * @param {Object} row Table row as a jQuery object.
295
+ * @param {Object} status
296
+ */
297
+ function displayLinkStatus(row, status) {
298
+ //Update the status code and class.
299
+ var statusColumn = row.find('td.column-status');
300
+ if (status.status_text) {
301
+ statusColumn.find('.status-text').text(status.status_text);
302
+ }
303
+ statusColumn.find('.http-code').text(status.http_code ? status.http_code : '');
304
+
305
+ var oldStatusClass = row.attr('class').match(/(?:^|\s)(link-status-[^\s]+)(?:\s|$)/);
306
+ oldStatusClass = oldStatusClass ? oldStatusClass[1] : '';
307
+ var newStatusClass = 'link-status-' + status.status_code;
308
+
309
+ statusColumn.find('.link-status-row').removeClass(oldStatusClass).addClass(newStatusClass);
310
+ row.removeClass(oldStatusClass).addClass(newStatusClass);
311
+
312
+ //Last check time and failure duration are complicated to update, so we'll just hide them.
313
+ //The user can refresh the page to get the new values.
314
+ statusColumn.find('.link-last-checked td').html('&nbsp;');
315
+ statusColumn.find('.link-broken-for td').html('&nbsp;');
316
+
317
+ //The link may or may not be a redirect now.
318
+ row.toggleClass('blc-redirect', status.redirect_count > 0);
319
+
320
+ if (typeof status['redirect_count'] !== 'undefined') {
321
+ var redirectColumn = row.find('td.column-redirect-url').empty();
322
+
323
+ if (status.redirect_count > 0 && status.final_url) {
324
+ redirectColumn.append(
325
+ $(
326
+ '<a></a>',
327
+ {
328
+ href: status.final_url,
329
+ text: status.final_url,
330
+ title: status.final_url,
331
+ 'class': 'blc-redirect-url',
332
+ target: '_blank'
333
+ }
334
+ )
335
+ );
336
+ }
337
+ }
338
+ }
339
+
340
+
341
+ /**
342
+ * Display the inline link editor.
343
+ *
344
+ * @param {Number} link_id Link ID. The link must be visible in the current view.
345
+ */
346
+ function showLinkEditor(link_id) {
347
+ var master = $('#blc-row-' + link_id),
348
+ editorId = 'blc-edit-row-' + link_id,
349
+ editRow;
350
+
351
+ //Get rid of all existing inline editors.
352
+ master.closest('table').find('tr.blc-inline-editor').each(function() {
353
+ hideLinkEditor($(this));
354
+ });
355
+
356
+ //Create an inline editor for this link.
357
+ editRow = $('#blc-inline-edit-row').clone(true).attr('id', editorId);
358
+ editRow.toggleClass('alternate', master.hasClass('alternate'));
359
+ master.after(editRow);
360
+
361
+ //Populate editor fields.
362
+ var urlElement = master.find('a.blc-link-url');
363
+ var linkUrl = urlElement.data('editable-url') || urlElement.attr('href');
364
+ var urlInput = editRow.find('.blc-link-url-field').val(linkUrl);
365
+
366
+ var titleInput = editRow.find('.blc-link-text-field');
367
+ var linkText = master.data('link-text'),
368
+ canEditText = master.data('can-edit-text') == 1, //jQuery will convert a '1' to 1 (number) when reading a data attribute.
369
+ canEditUrl = master.data('can-edit-url') == 1,
370
+ noneText = '<?php echo esc_js(_x('(None)', 'link text', 'broken-link-checker')); ?>',
371
+ multipleLinksText = '<?php echo esc_js(_x('(Multiple links)', 'link text', 'broken-link-checker')); ?>';
372
+
373
+ titleInput.prop('readonly', !canEditText);
374
+ urlInput.prop('readonly', !canEditUrl);
375
+
376
+ if ( (typeof linkText !== 'undefined') && (linkText !== null) ) {
377
+ if (linkText === '') {
378
+ titleInput.val(canEditText ? linkText : noneText);
379
+ } else {
380
+ titleInput.val(linkText)
381
+ }
382
+ titleInput.prop('placeholder', noneText);
383
+ } else {
384
+ if (canEditText) {
385
+ titleInput.val('').prop('placeholder', multipleLinksText);
386
+ } else {
387
+ titleInput.val(multipleLinksText)
388
+ }
389
+ }
390
+
391
+ //Populate the list of URL replacement suggestions.
392
+ if (canEditUrl && blc_suggestions_enabled && (master.hasClass('link-status-error') || master.hasClass('link-status-warning'))) {
393
+ editRow.find('.blc-url-replacement-suggestions').show();
394
+ var suggestionList = editRow.find('.blc-suggestion-list');
395
+ findReplacementSuggestions(linkUrl, suggestionList);
396
+ }
397
+
398
+ editRow.find('.blc-update-link-button').prop('disabled', !(canEditUrl || canEditText));
399
+
400
+ //Make the editor span the entire width of the table.
401
+ editRow.find('td.blc-colspan-change').attr('colspan', master.closest('table').find('thead th:visible').length);
402
+
403
+ master.hide();
404
+ editRow.show();
405
+ urlInput.focus();
406
+ if (canEditUrl) {
407
+ urlInput.select();
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Hide the inline editor for a particular link.
413
+ *
414
+ * @param link_id Either a numeric link ID or a jQuery object that represents the editor row.
415
+ */
416
+ function hideLinkEditor(link_id) {
417
+ var editRow = isNaN(link_id) ? link_id : $('#blc-edit-row-' + link_id);
418
+ editRow.prev('tr.blc-row').show();
419
+ editRow.remove();
420
+ }
421
+
422
+ /**
423
+ * Find possible replacements for a broken link and display them in a list.
424
+ *
425
+ * @param {String} url The current link URL.
426
+ * @param suggestionList jQuery object that represents a list element.
427
+ */
428
+ function findReplacementSuggestions(url, suggestionList) {
429
+ var searchingText = '<?php echo esc_js(_x('Searching...', 'link suggestions', 'broken-link-checker')) ?>';
430
+ var noSuggestionsText = '<?php echo esc_js(_x('No suggestions available.', 'link suggestions', 'broken-link-checker')) ?>';
431
+ var iaSuggestionName = '<?php echo esc_js(_x('Archived page from %s (via the Wayback Machine)', 'link suggestions', 'broken-link-checker')); ?>';
432
+
433
+ suggestionList.empty().append('<li>' + searchingText + '</li>');
434
+
435
+ var suggestionTemplate = $('#blc-suggestion-template').find('li').first();
436
+
437
+ //Check the Wayback Machine for an archived version of the page.
438
+ $.getJSON(
439
+ 'https://archive.org/wayback/available?callback=?',
440
+ { url: url },
441
+
442
+ function(data) {
443
+ suggestionList.empty();
444
+
445
+ //Check if there are any results.
446
+ if (!data || !data.archived_snapshots || !data.archived_snapshots.closest || !data.archived_snapshots.closest.available ) {
447
+ suggestionList.append('<li>' + noSuggestionsText + '</li>');
448
+ return;
449
+ }
450
+
451
+ var snapshot = data.archived_snapshots.closest;
452
+
453
+ //Convert the timestamp from YYYYMMDDHHMMSS to ISO 8601 date format.
454
+ var readableTimestamp = snapshot.timestamp.substr(0, 4) +
455
+ '-' + snapshot.timestamp.substr(4, 2) +
456
+ '-' + snapshot.timestamp.substr(6, 2);
457
+ var name = sprintf(iaSuggestionName, readableTimestamp);
458
+
459
+ //Enforce HTTPS by default
460
+ snapshot.url = (snapshot.url).replace( new RegExp("^http:", "m"), "https:");
461
+
462
+ //Display the suggestion.
463
+ var item = suggestionTemplate.clone();
464
+ item.find('.blc-suggestion-name a').text(name).attr('href', snapshot.url);
465
+ item.find('.blc-suggestion-url').text(snapshot.url);
466
+ suggestionList.append(item);
467
+ }
468
+ );
469
+ }
470
+
471
+ /**
472
+ * Call our PHP backend and tell it to edit all occurrences of particular link.
473
+ * Updates UI with the new link info and displays any error messages that might be generated.
474
+ *
475
+ * @param linkId Either a numeric link ID or a jQuery object representing the link row.
476
+ * @param {String} newUrl The new link URL.
477
+ * @param {String} newText The new link text. Optional. Set to null to leave it unchanged.
478
+ */
479
+ function updateLink(linkId, newUrl, newText) {
480
+ var master, editRow;
481
+ if ( isNaN(linkId) ){
482
+ master = linkId;
483
+ linkId = master.attr('id').split("-")[2]; //id="blc-row-$linkid"
484
+ } else {
485
+ master = $('#blc-row-' + linkId);
486
+ }
487
+ editRow = $('#blc-edit-row-' + linkId);
488
+
489
+ var urlElement = master.find('a.blc-link-url');
490
+ var progressIndicator = editRow.find('.waiting'),
491
+ updateButton = editRow.find('.blc-update-link-button');
492
+ progressIndicator.show();
493
+ updateButton.prop('disabled', true);
494
+
495
+ $.post(
496
+ '<?php echo admin_url('admin-ajax.php'); ?>',
497
+ {
498
+ 'action' : 'blc_edit',
499
+ 'link_id' : linkId,
500
+ 'new_url' : newUrl,
501
+ 'new_text' : newText,
502
+ '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_edit')); ?>'
503
+ },
504
+ function(response) {
505
+ progressIndicator.hide();
506
+ updateButton.prop('disabled', false);
507
+
508
+ handleEditResponse(response, master, linkId, newText);
509
+
510
+ hideLinkEditor(editRow);
511
+ },
512
+ 'json'
513
+ );
514
+
515
+ }
516
+
517
+ function handleEditResponse(response, master, linkId, newText) {
518
+ if (response && (typeof(response['error']) != 'undefined')){
519
+ //An internal error occurred before the link could be edited.
520
+ alert(response.error);
521
+ return false;
522
+ } else if (response.errors.length > 0) {
523
+ //Build and display an error message.
524
+ var msg = '';
525
+
526
+ if ( response.cnt_okay > 0 ){
527
+ var fragment = sprintf(
528
+ '<?php echo esc_js(__('%d instances of the link were successfully modified.', 'broken-link-checker')); ?>',
529
+ response.cnt_okay
530
+ );
531
+ msg = msg + fragment + '\n';
532
+ if ( response.cnt_error > 0 ){
533
+ fragment = sprintf(
534
+ '<?php echo esc_js(__("However, %d instances couldn't be edited and still point to the old URL.", 'broken-link-checker')); ?>',
535
+ response.cnt_error
536
+ );
537
+ msg = msg + fragment + "\n";
538
+ }
539
+ } else {
540
+ msg = msg + '<?php echo esc_js(__('The link could not be modified.', 'broken-link-checker')); ?>\n';
541
+ }
542
+
543
+ msg = msg + '\n<?php echo esc_js(__("The following error(s) occurred :", 'broken-link-checker')); ?>\n* ';
544
+ msg = msg + response.errors.join('\n* ');
545
+
546
+ alert(msg);
547
+ return false;
548
+ } else {
549
+ //Everything went well. Update the link row with the new values.
550
+
551
+ //Replace the displayed link URL with the new one.
552
+ var urlElement = master.find('a.blc-link-url');
553
+ urlElement
554
+ .attr('href', response.url)
555
+ .text(response.url)
556
+ .data('editable-url', response.url)
557
+ .prop('title', response.url);
558
+ if ( typeof response['escaped_url'] != 'undefined' ) {
559
+ urlElement.attr('href', response.escaped_url)
560
+ }
561
+
562
+ //Save the new ID
563
+ replaceLinkId(linkId, response.new_link_id);
564
+ //Load up the new link info
565
+ reloadDetailsRow(response.new_link_id);
566
+
567
+ //Update the link text if it was edited.
568
+ if ((newText !== null) && (response.link_text !== null)) {
569
+ master.data('link-text', response.link_text);
570
+ if (response.ui_link_text !== null) {
571
+ master.find('.column-new-link-text').html(response.ui_link_text);
572
+ }
573
+ }
574
+
575
+ //Update the status code and class.
576
+ displayLinkStatus(master, response);
577
+
578
+ //Flash the row green to indicate success
579
+ flashElementGreen(master);
580
+
581
+ return true;
582
+ }
583
+ }
584
+
585
+ //The "Edit URL" button - displays the inline editor
586
+ $(".blc-edit-button").click(function () {
587
+ var master = $(this).closest('.blc-row');
588
+ var link_id = master.attr('id').split('-')[2];
589
+ showLinkEditor(link_id);
590
+ });
591
+
592
+ //Let the user use Enter and Esc as shortcuts for "Update" and "Cancel"
593
+ $('.blc-inline-editor input[type="text"]').keypress(function (e) {
594
+ var editRow = $(this).closest('.blc-inline-editor');
595
+ if (e.which == 13) {
596
+ editRow.find('.blc-update-link-button').click();
597
+ return false;
598
+ } else if (e.which == 27) {
599
+ editRow.find('.blc-cancel-button').click();
600
+ return false;
601
+ }
602
+ return true;
603
+ });
604
+
605
+
606
+ //The "Update" button in the inline editor.
607
+ $('.blc-update-link-button').click(function() {
608
+ var editRow = $(this).closest('tr'),
609
+ master = editRow.prev('.blc-row');
610
+
611
+ //Ensure the new URL is not empty.
612
+ var urlField = editRow.find('.blc-link-url-field');
613
+ var newUrl = urlField.val();
614
+ if ($.trim(newUrl) == '') {
615
+ alert('<?php echo esc_js(__('Error: Link URL must not be empty.', 'broken-link-checker')); ?>');
616
+ urlField.focus();
617
+ return;
618
+ }
619
+
620
+ var newLinkText = null,
621
+ linkTextField = editRow.find('.blc-link-text-field'),
622
+ oldLinkText = master.data('link-text');
623
+ if (!linkTextField.prop('readonly')) {
624
+ newLinkText = linkTextField.val();
625
+ //Empty or identical to the original = leave the text unchanged.
626
+ if ((newLinkText === '') || (newLinkText === oldLinkText)) {
627
+ newLinkText = null;
628
+ }
629
+ }
630
+
631
+ updateLink(master, newUrl, newLinkText);
632
+ });
633
+
634
+ //The "Cancel" in the inline editor.
635
+ $(".blc-cancel-button").click(function () {
636
+ var editRow = $(this).closest('tr');
637
+ hideLinkEditor(editRow);
638
+ });
639
+
640
+ //The "Use this URL" button in the inline editor replaces the link URL
641
+ //with the selected suggestion URL.
642
+ $('#blc-links').on('click', '.blc-use-url-button', function() {
643
+ var button = $(this);
644
+ var suggestionUrl = button.closest('tr').find('.blc-suggestion-name a').attr('href');
645
+ button.closest('.blc-inline-editor').find('.blc-link-url-field').val(suggestionUrl);
646
+ });
647
+
648
+
649
+ //The "Unlink" button - remove the link/image from all posts, custom fields, etc.
650
+ $(".blc-unlink-button").click(function () {
651
+ var me = this;
652
+ var master = $(me).parents('.blc-row');
653
+ $(me).html('<?php echo esc_js(__('Wait...' , 'broken-link-checker')); ?>');
654
+
655
+ //Find the link ID
656
+ var link_id = master.attr('id').split('-')[2];
657
+
658
+ $.post(
659
+ "<?php echo admin_url('admin-ajax.php'); ?>",
660
+ {
661
+ 'action' : 'blc_unlink',
662
+ 'link_id' : link_id,
663
+ '_ajax_nonce' : '<?php echo esc_js(wp_create_nonce('blc_unlink')); ?>'
664
+ },
665
+ function (data, textStatus){
666
+ eval('data = ' + data);
667
+
668
+ if ( data && (typeof(data['error']) != 'undefined') ){
669
+ //An internal error occurred before the link could be edited.
670
+ //data.error is an error message.
671
+ alert(data.error);
672
+ } else {
673
+ if ( data.errors.length == 0 ){
674
+ //The link was successfully removed. Hide its details.
675
+ $('#link-details-'+link_id).hide();
676
+ //Flash the main row green to indicate success, then hide it.
677
+ var oldColor = master.css('background-color');
678
+ master.animate({ backgroundColor: "#E0FFB3" }, 200).animate({ backgroundColor: oldColor }, 300, function(){
679
+ master.hide();
680
+ });
681
+
682
+ alterLinkCounter(-1);
683
+
684
+ return;
685
+ } else {
686
+ //Build and display an error message.
687
+ var msg = '';
688
+
689
+ if ( data.cnt_okay > 0 ){
690
+ msg = msg + sprintf(
691
+ '<?php echo esc_js(__("%d instances of the link were successfully unlinked.", 'broken-link-checker')); ?>\n',
692
+ data.cnt_okay
693
+ );
694
+
695
+ if ( data.cnt_error > 0 ){
696
+ msg = msg + sprintf(
697
+ '<?php echo esc_js(__("However, %d instances couldn't be removed.", 'broken-link-checker')); ?>\n',
698
+ data.cnt_error
699
+ );
700
+ }
701
+ } else {
702
+ msg = msg + '<?php echo esc_js(__("The plugin failed to remove the link.", 'broken-link-checker')); ?>\n';
703
+ }
704
+
705
+ msg = msg + '\n<?php echo esc_js(__("The following error(s) occured :", 'broken-link-checker')); ?>\n* ';
706
+ msg = msg + data.errors.join('\n* ');
707
+
708
+ //Show the error message
709
+ alert(msg);
710
+ }
711
+ }
712
+
713
+ $(me).html('<?php echo esc_js(__('Unlink' , 'broken-link-checker')); ?>');
714
+ }
715
+ );
716
+ });
717
+
718
+ //--------------------------------------------
719
+ //The search box(es)
720
+ //--------------------------------------------
721
+
722
+ var searchForm = $('#search-links-dialog');
723
+
724
+ searchForm.dialog({
725
+ autoOpen : false,
726
+ dialogClass : 'blc-search-container',
727
+ resizable: false
728
+ });
729
+
730
+ $('#blc-open-search-box').click(function(){
731
+ if ( searchForm.dialog('isOpen') ){
732
+ searchForm.dialog('close');
733
+ } else {
734
+ searchForm
735
+ .dialog('open')
736
+ .dialog('widget')
737
+ .position({
738
+ my: 'right top',
739
+ at: 'right bottom',
740
+ of: $('#blc-open-search-box')
741
+ });
742
+ }
743
+ });
744
+
745
+ $('#blc-cancel-search').click(function(){
746
+ searchForm.dialog('close');
747
+ });
748
+
749
+ //The "Save This Search Query" button creates a new custom filter based on the current search
750
+ $('#blc-create-filter').click(function(){
751
+ var filter_name = prompt("<?php echo esc_js(__("Enter a name for the new custom filter", 'broken-link-checker')); ?>", "");
752
+ if ( filter_name ){
753
+ $('#blc-custom-filter-name').val(filter_name);
754
+ $('#custom-filter-form').submit();
755
+ }
756
+ });
757
+
758
+ //Display a confirmation dialog when the user clicks the "Delete This Filter" button
759
+ $('#blc-delete-filter').click(function(){
760
+ var message = '<?php
761
+ echo esc_js(
762
+ html_entity_decode(
763
+ __("You are about to delete the current filter.\n'Cancel' to stop, 'OK' to delete", 'broken-link-checker'),
764
+ ENT_QUOTES,
765
+ get_bloginfo('charset')
766
+ )
767
+ );
768
+ ?>';
769
+ return confirm(message);
770
+ });
771
+
772
+ //--------------------------------------------
773
+ // Bulk actions
774
+ //--------------------------------------------
775
+
776
+ $('#blc-bulk-action-form').submit(function(){
777
+ var action = $('#blc-bulk-action').val(), message;
778
+ if ( action == '-1' ){
779
+ action = $('#blc-bulk-action2').val();
780
+ }
781
+
782
+ if ( action == 'bulk-delete-sources' ){
783
+ //Convey the gravitas of deleting link sources.
784
+ message = '<?php
785
+ echo esc_js(
786
+ html_entity_decode(
787
+ __("Are you sure you want to delete all posts, bookmarks or other items that contain any of the selected links? This action can't be undone.\n'Cancel' to stop, 'OK' to delete", 'broken-link-checker'),
788
+ ENT_QUOTES,
789
+ get_bloginfo('charset')
790
+ )
791
+ );
792
+ ?>';
793
+ if ( !confirm(message) ){
794
+ return false;
795
+ }
796
+ } else if ( action == 'bulk-unlink' ){
797
+ //Likewise for unlinking.
798
+ message = '<?php
799
+ echo esc_js(
800
+ html_entity_decode(
801
+ __("Are you sure you want to remove the selected links? This action can't be undone.\n'Cancel' to stop, 'OK' to remove", 'broken-link-checker'),
802
+ ENT_QUOTES,
803
+ get_bloginfo('charset')
804
+ )
805
+ );
806
+ ?>';
807
+ if ( !confirm(message) ){
808
+ return false;
809
+ }
810
+ }
811
+ });
812
+
813
+ //Automatically disable bulk actions that don't apply to the currently selected links.
814
+ $('#blc-bulk-action').focus(function() {
815
+ var redirectsSelected = false, brokenLinksSelected = false;
816
+ $('tr th.check-column input:checked', '#blc-links').each(function() {
817
+ var row = $(this).closest('tr');
818
+ if (row.hasClass('blc-redirect')) {
819
+ redirectsSelected = true
820
+ }
821
+ if (row.hasClass('link-status-error') || row.hasClass('link-status-warning')) {
822
+ brokenLinksSelected = true;
823
+ }
824
+ });
825
+
826
+ var bulkAction = $(this);
827
+ bulkAction.find('option[value="bulk-deredirect"]').prop('disabled', !redirectsSelected);
828
+ bulkAction.find('option[value="bulk-not-broken"]').prop('disabled', !brokenLinksSelected);
829
+ });
830
+
831
+ //------------------------------------------------------------
832
+ // Manipulate highlight settings for permanently broken links
833
+ //------------------------------------------------------------
834
+ var highlight_permanent_failures_checkbox = $('#highlight_permanent_failures');
835
+ var failure_duration_threshold_input = $('#failure_duration_threshold');
836
+
837
+ //Apply/remove highlights when the checkbox is (un)checked
838
+ highlight_permanent_failures_checkbox.change(function(){
839
+ //save_highlight_settings();
840
+
841
+ if ( this.checked ){
842
+ $('#blc-links tr.blc-permanently-broken').addClass('blc-permanently-broken-hl');
843
+ } else {
844
+ $('#blc-links tr.blc-permanently-broken').removeClass('blc-permanently-broken-hl');
845
+ }
846
+ });
847
+
848
+ //Apply/remove highlights when the duration threshold is changed.
849
+ failure_duration_threshold_input.change(function(){
850
+ var new_threshold = parseInt($(this).val());
851
+ //save_highlight_settings();
852
+ if (isNaN(new_threshold) || (new_threshold < 1)) {
853
+ return;
854
+ }
855
+
856
+ highlight_permanent_failures = highlight_permanent_failures_checkbox.is(':checked');
857
+
858
+ $('#blc-links tr.blc-row').each(function(index){
859
+ var days_broken = $(this).attr('data-days-broken');
860
+ if ( days_broken >= new_threshold ){
861
+ $(this).addClass('blc-permanently-broken');
862
+ if ( highlight_permanent_failures ){
863
+ $(this).addClass('blc-permanently-broken-hl');
864
+ }
865
+ } else {
866
+ $(this).removeClass('blc-permanently-broken').removeClass('blc-permanently-broken-hl');
867
+ }
868
+ });
869
+ });
870
+
871
+ //Show/hide table columns dynamically
872
+ $('#blc-column-selector input[type="checkbox"]').change(function(){
873
+ var checkbox = $(this);
874
+ var column_id = checkbox.attr('name').split(/\[|\]/)[1];
875
+ if (checkbox.is(':checked')){
876
+ $('td.column-'+column_id+', th.column-'+column_id, '#blc-links').removeClass('hidden');
877
+ } else {
878
+ $('td.column-'+column_id+', th.column-'+column_id, '#blc-links').addClass('hidden');
879
+ }
880
+
881
+ //Recalculate colspan's for detail rows to take into account the changed number of
882
+ //visible columns. Otherwise you can get some ugly layout glitches.
883
+ $('#blc-links tr.blc-link-details td').attr(
884
+ 'colspan',
885
+ $('#blc-column-selector input[type="checkbox"]:checked').length+1
886
+ );
887
+ });
888
+
889
+ //Unlike other fields in "Screen Options", the links-per-page setting
890
+ //is handled using straight form submission (POST), not AJAX.
891
+ $('#blc-per-page-apply-button').click(function(){
892
+ $('#adv-settings').submit();
893
+ });
894
+
895
+ $('#blc_links_per_page').keypress(function(e){
896
+ if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
897
+ $('#adv-settings').submit();
898
+ }
899
+ });
900
+
901
+ //Toggle status code colors when the corresponding checkbox is toggled
902
+ $('#table_color_code_status').click(function(){
903
+ if ( $(this).is(':checked') ){
904
+ $('#blc-links').addClass('color-code-link-status');
905
+ } else {
906
+ $('#blc-links').removeClass('color-code-link-status');
907
+ }
908
+ });
909
+
910
+ //Show the bulk edit/find & replace form when the user applies the appropriate bulk action
911
+ $('#doaction, #doaction2').click(function(e){
912
+ var n = $(this).attr('id').substr(2);
913
+ if ( $('select[name="'+n+'"]').val() == 'bulk-edit' ) {
914
+ e.preventDefault();
915
+ //Any links selected?
916
+ if ($('tbody th.check-column input:checked').length > 0){
917
+ $('#bulk-edit').show();
918
+ }
919
+ }
920
+ });
921
+
922
+ //Hide the bulk edit/find & replace form when "Cancel" is clicked
923
+ $('#bulk-edit .cancel').click(function(){
924
+ $('#bulk-edit').hide();
925
+ return false;
926
+ });
927
+
928
+ //Minimal input validation for the bulk edit form
929
+ $('#bulk-edit input[type="submit"]').click(function(e){
930
+ if( $('#bulk-edit input[name="search"]').val() == '' ){
931
+ alert('<?php echo esc_js(__('Enter a search string first.', 'broken-link-checker')); ?>');
932
+ $('#bulk-edit input[name="search"]').focus();
933
+ e.preventDefault();
934
+ return;
935
+ }
936
+
937
+ if ($('tbody th.check-column input:checked').length == 0){
938
+ alert('<?php echo esc_js(__('Select one or more links to edit.', 'broken-link-checker')); ?>');
939
+ e.preventDefault();
940
+ }
941
+ });
942
+
943
+
944
+ });
945
+
946
  </script>
includes/admin/options-page-js.php CHANGED
@@ -1,147 +1,147 @@
1
- <script type="text/javascript">
2
-
3
- jQuery(function($){
4
- $('#blc-tabs').tabs();
5
-
6
- //Refresh the "Status" box every 10 seconds
7
- function blcUpdateStatus(){
8
- $.getJSON(
9
- "<?php echo admin_url('admin-ajax.php'); ?>",
10
- {
11
- 'action' : 'blc_full_status',
12
- 'random' : Math.random()
13
- },
14
- function (data, textStatus){
15
- if ( data && ( typeof(data['text']) != 'undefined' ) ){
16
- $('#wsblc_full_status').html(data.text);
17
- } else {
18
- $('#wsblc_full_status').html('<?php _e('[ Network error ]', 'broken-link-checker'); ?>');
19
- }
20
-
21
- setTimeout(blcUpdateStatus, 10000);
22
- }
23
- );
24
- }
25
- blcUpdateStatus();
26
-
27
- //Refresh the avg. load display every 10 seconds
28
- function blcUpdateLoad(){
29
- $.get(
30
- "<?php echo admin_url('admin-ajax.php'); ?>",
31
- {
32
- 'action' : 'blc_current_load'
33
- },
34
- function (data, textStatus){
35
- $('#wsblc_current_load').html(data);
36
-
37
- setTimeout(blcUpdateLoad, 10000); //...update every 10 seconds
38
- }
39
- );
40
- }
41
- //Only do it if load limiting is available on this server, though.
42
- if ( $('#wsblc_current_load').length > 0 ){
43
- blcUpdateLoad();
44
- }
45
-
46
-
47
- var toggleButton = $('#blc-debug-info-toggle');
48
-
49
- toggleButton.click(function(){
50
-
51
- var box = $('#blc-debug-info');
52
- box.toggle();
53
- if( box.is(':visible') ){
54
- toggleButton.text('<?php _e('Hide debug info', 'broken-link-checker'); ?>');
55
- } else {
56
- toggleButton.text('<?php _e('Show debug info', 'broken-link-checker'); ?>');
57
- }
58
-
59
- });
60
-
61
- $('#toggle-broken-link-css-editor').click(function(){
62
- var box = $('#broken-link-css-wrap').toggleClass('hidden');
63
-
64
- $.cookie(
65
- box.attr('id'),
66
- box.hasClass('hidden')?'0':'1',
67
- {
68
- expires : 365
69
- }
70
- );
71
-
72
- return false;
73
- });
74
-
75
- $('#toggle-removed-link-css-editor').click(function(){
76
- var box = $('#removed-link-css-wrap').toggleClass('hidden');
77
-
78
- $.cookie(
79
- box.attr('id'),
80
- box.hasClass('hidden')?'0':'1',
81
- {
82
- expires : 365
83
- }
84
- );
85
-
86
- return false;
87
- });
88
-
89
- //Show/hide per-module settings
90
- $('.toggle-module-settings').click(function(){
91
- var settingsBox = $(this).parent().find('.module-extra-settings');
92
- if ( settingsBox.length > 0 ){
93
- settingsBox.toggleClass('hidden');
94
- $.cookie(
95
- settingsBox.attr('id'),
96
- settingsBox.hasClass('hidden')?'0':'1',
97
- {
98
- expires : 365
99
- }
100
- );
101
- }
102
- return false;
103
- });
104
-
105
- //When the user ticks the "Custom fields" box, display the field list input
106
- //so that they notice that they need to enter the field names.
107
- $('#module-checkbox-custom_field').click(function(){
108
- var box = $(this);
109
- var fieldList = $('#blc_custom_fields');
110
- if ( box.is(':checked') && ( $.trim(fieldList.val()) == '' ) ){
111
- $('#module-extra-settings-custom_field').removeClass('hidden');
112
- }
113
- });
114
-
115
- //When the user ticks the "Custom fields" box, display the field list input
116
- //so that they notice that they need to enter the field names.
117
- $('#module-checkbox-acf_field').click(function(){
118
- var box = $(this);
119
- var fieldList = $('#blc_acf_fields');
120
- if ( box.is(':checked') && ( $.trim(fieldList.val()) == '' ) ){
121
- $('#module-extra-settings-acf_field').removeClass('hidden');
122
- }
123
- });
124
-
125
- //Handle the "Recheck" button
126
- $('#start-recheck').click(function(){
127
- $('#recheck').val('1'); //populate the hidden field
128
- $('#link_checker_options input[name="submit"]').click(); //.submit() didn't work for some reason
129
- });
130
-
131
- //Enable/disable log-related options depending on whether "Enable logging" is on.
132
- function blcToggleLogOptions() {
133
- $('#blc-logging-options')
134
- .find('input')
135
- .prop('disabled', ! $('#logging_enabled').is(':checked'));
136
- }
137
-
138
- blcToggleLogOptions();
139
- $('#logging_enabled').change(blcToggleLogOptions);
140
-
141
- //
142
- $('#target_resource_usage').change(function() {
143
- $('#target_resource_usage_percent').text($(this).val() + '%')
144
- });
145
- });
146
-
147
  </script>
1
+ <script type="text/javascript">
2
+
3
+ jQuery(function($){
4
+ $('#blc-tabs').tabs();
5
+
6
+ //Refresh the "Status" box every 10 seconds
7
+ function blcUpdateStatus(){
8
+ $.getJSON(
9
+ "<?php echo admin_url('admin-ajax.php'); ?>",
10
+ {
11
+ 'action' : 'blc_full_status',
12
+ 'random' : Math.random()
13
+ },
14
+ function (data, textStatus){
15
+ if ( data && ( typeof(data['text']) != 'undefined' ) ){
16
+ $('#wsblc_full_status').html(data.text);
17
+ } else {
18
+ $('#wsblc_full_status').html('<?php _e('[ Network error ]', 'broken-link-checker'); ?>');
19
+ }
20
+
21
+ setTimeout(blcUpdateStatus, 10000);
22
+ }
23
+ );
24
+ }
25
+ blcUpdateStatus();
26
+
27
+ //Refresh the avg. load display every 10 seconds
28
+ function blcUpdateLoad(){
29
+ $.get(
30
+ "<?php echo admin_url('admin-ajax.php'); ?>",
31
+ {
32
+ 'action' : 'blc_current_load'
33
+ },
34
+ function (data, textStatus){
35
+ $('#wsblc_current_load').html(data);
36
+
37
+ setTimeout(blcUpdateLoad, 10000); //...update every 10 seconds
38
+ }
39
+ );
40
+ }
41
+ //Only do it if load limiting is available on this server, though.
42
+ if ( $('#wsblc_current_load').length > 0 ){
43
+ blcUpdateLoad();
44
+ }
45
+
46
+
47
+ var toggleButton = $('#blc-debug-info-toggle');
48
+
49
+ toggleButton.click(function(){
50
+
51
+ var box = $('#blc-debug-info');
52
+ box.toggle();
53
+ if( box.is(':visible') ){
54
+ toggleButton.text('<?php _e('Hide debug info', 'broken-link-checker'); ?>');
55
+ } else {
56
+ toggleButton.text('<?php _e('Show debug info', 'broken-link-checker'); ?>');
57
+ }
58
+
59
+ });
60
+
61
+ $('#toggle-broken-link-css-editor').click(function(){
62
+ var box = $('#broken-link-css-wrap').toggleClass('hidden');
63
+
64
+ $.cookie(
65
+ box.attr('id'),
66
+ box.hasClass('hidden')?'0':'1',
67
+ {
68
+ expires : 365
69
+ }
70
+ );
71
+
72
+ return false;
73
+ });
74
+
75
+ $('#toggle-removed-link-css-editor').click(function(){
76
+ var box = $('#removed-link-css-wrap').toggleClass('hidden');
77
+
78
+ $.cookie(
79
+ box.attr('id'),
80
+ box.hasClass('hidden')?'0':'1',
81
+ {
82
+ expires : 365
83
+ }
84
+ );
85
+
86
+ return false;
87
+ });
88
+
89
+ //Show/hide per-module settings
90
+ $('.toggle-module-settings').click(function(){
91
+ var settingsBox = $(this).parent().find('.module-extra-settings');
92
+ if ( settingsBox.length > 0 ){
93
+ settingsBox.toggleClass('hidden');
94
+ $.cookie(
95
+ settingsBox.attr('id'),
96
+ settingsBox.hasClass('hidden')?'0':'1',
97
+ {
98
+ expires : 365
99
+ }
100
+ );
101
+ }
102
+ return false;
103
+ });
104
+
105
+ //When the user ticks the "Custom fields" box, display the field list input
106
+ //so that they notice that they need to enter the field names.
107
+ $('#module-checkbox-custom_field').click(function(){
108
+ var box = $(this);
109
+ var fieldList = $('#blc_custom_fields');
110
+ if ( box.is(':checked') && ( $.trim(fieldList.val()) == '' ) ){
111
+ $('#module-extra-settings-custom_field').removeClass('hidden');
112
+ }
113
+ });
114
+
115
+ //When the user ticks the "Custom fields" box, display the field list input
116
+ //so that they notice that they need to enter the field names.
117
+ $('#module-checkbox-acf_field').click(function(){
118
+ var box = $(this);
119
+ var fieldList = $('#blc_acf_fields');
120
+ if ( box.is(':checked') && ( $.trim(fieldList.val()) == '' ) ){
121
+ $('#module-extra-settings-acf_field').removeClass('hidden');
122
+ }
123
+ });
124
+
125
+ //Handle the "Recheck" button
126
+ $('#start-recheck').click(function(){
127
+ $('#recheck').val('1'); //populate the hidden field
128
+ $('#link_checker_options input[name="submit"]').click(); //.submit() didn't work for some reason
129
+ });
130
+
131
+ //Enable/disable log-related options depending on whether "Enable logging" is on.
132
+ function blcToggleLogOptions() {
133
+ $('#blc-logging-options')
134
+ .find('input')
135
+ .prop('disabled', ! $('#logging_enabled').is(':checked'));
136
+ }
137
+
138
+ blcToggleLogOptions();
139
+ $('#logging_enabled').change(blcToggleLogOptions);
140
+
141
+ //
142
+ $('#target_resource_usage').change(function() {
143
+ $('#target_resource_usage_percent').text($(this).val() + '%')
144
+ });
145
+ });
146
+
147
  </script>
includes/admin/search-form.php CHANGED
@@ -1,117 +1,117 @@
1
- <?php
2
- $search_params = $current_filter['search_params'];
3
- ?>
4
- <div class="search-box">
5
-
6
- <?php
7
- //If we're currently displaying search results offer the user the option to
8
- //save the search query as a custom filter.
9
- if ( $filter_id == 'search' ){
10
- ?>
11
- <form name="save-search-query" id="custom-filter-form" action="<?php echo admin_url("tools.php?page=view-broken-links"); ?>" method="post" class="blc-inline-form">
12
- <?php wp_nonce_field('create-custom-filter'); ?>
13
- <input type="hidden" name="name" id="blc-custom-filter-name" value="" />
14
- <input type="hidden" name="params" id="blc-custom-filter-params" value="<?php echo http_build_query($search_params, null, '&'); ?>" />
15
- <input type="hidden" name="action" value="create-custom-filter" />
16
- <input type="button" value="<?php esc_attr_e( 'Save This Search As a Filter', 'broken-link-checker' ); ?>" id="blc-create-filter" class="button" />
17
- </form>
18
- <?php
19
- } elseif ( !empty($current_filter['custom']) ){
20
- //If we're displaying a custom filter give an option to delete it.
21
- ?>
22
- <form name="save-search-query" id="custom-filter-form" action="<?php echo admin_url("tools.php?page=view-broken-links"); ?>" method="post" class="blc-inline-form">
23
- <?php wp_nonce_field('delete-custom-filter'); ?>
24
- <input type="hidden" name="filter_id" id="blc-custom-filter-id" value="<?php echo $filter_id; ?>" />
25
- <input type="hidden" name="action" value="delete-custom-filter" />
26
- <input type="submit" value="<?php esc_attr_e( 'Delete This Filter', 'broken-link-checker' ); ?>" id="blc-delete-filter" class="button" />
27
- </form>
28
- <?php
29
- }
30
- ?>
31
-
32
- <input type="button" value="<?php esc_attr_e( 'Search', 'broken-link-checker' ); ?> &raquo;" id="blc-open-search-box" class="button" />
33
- </div>
34
-
35
- <!-- The search dialog -->
36
- <div id='search-links-dialog' title='Search'>
37
- <form class="search-form" action="<?php echo admin_url('tools.php?page=view-broken-links'); ?>" method="get">
38
- <input type="hidden" name="page" value="view-broken-links" />
39
- <input type="hidden" name="filter_id" value="search" />
40
- <fieldset>
41
-
42
- <label for="s_link_text"><?php _e('Link text', 'broken-link-checker'); ?></label>
43
- <input type="text" name="s_link_text" value="<?php if(!empty($search_params['s_link_text'])) echo esc_attr($search_params['s_link_text']); ?>" id="s_link_text" class="text ui-widget-content" />
44
-
45
- <label for="s_link_url"><?php _e('URL', 'broken-link-checker'); ?></label>
46
- <input type="text" name="s_link_url" id="s_link_url" value="<?php if(!empty($search_params['s_link_url'])) echo esc_attr($search_params['s_link_url']); ?>" class="text ui-widget-content" />
47
-
48
- <label for="s_http_code"><?php _e('HTTP code', 'broken-link-checker'); ?></label>
49
- <input type="text" name="s_http_code" id="s_http_code" value="<?php if(!empty($search_params['s_http_code'])) echo esc_attr($search_params['s_http_code']); ?>" class="text ui-widget-content" />
50
-
51
- <label for="s_filter"><?php _e('Link status', 'broken-link-checker'); ?></label>
52
- <select name="s_filter" id="s_filter">
53
- <?php
54
- if ( !empty($search_params['s_filter']) ){
55
- $search_subfilter = $search_params['s_filter'];
56
- } else {
57
- $search_subfilter = 'all';
58
- }
59
-
60
- $linkQuery = blcLinkQuery::getInstance();
61
- foreach ($linkQuery->native_filters as $filter => $data){
62
- $selected = ($search_subfilter == $filter)?' selected="selected"':'';
63
- printf('<option value="%s"%s>%s</option>', $filter, $selected, $data['name']);
64
- }
65
- ?>
66
- </select>
67
-
68
- <label for="s_link_type"><?php _e('Link type', 'broken-link-checker'); ?></label>
69
- <select name="s_link_type" id="s_link_type">
70
- <option value=""><?php _e('Any', 'broken-link-checker'); ?></option>
71
- <?php
72
- $moduleManager = blcModuleManager::getInstance();
73
-
74
- printf('<optgroup label="%s">', esc_attr(__('Links used in', 'broken-link-checker')));
75
- $containers = $moduleManager->get_modules_by_category('container', false, true);
76
- foreach($containers as $container_type => $module_data){
77
- if ( !empty($module_data['ModuleHidden']) || !$moduleManager->is_active($container_type) ){
78
- continue;
79
- }
80
- $selected = ( isset($search_params['s_link_type']) && $search_params['s_link_type'] == $container_type )?' selected="selected"':'';
81
- printf('<option value="%s"%s>%s</option>', $container_type, $selected, $module_data['Name']);
82
- }
83
- echo '</optgroup>';
84
- //TODO: Better group labels
85
- printf('<optgroup label="%s">', esc_attr(__('Link type', 'broken-link-checker')));
86
- $parsers = $moduleManager->get_modules_by_category('parser', false, true);
87
- foreach($parsers as $parser_type => $module_data){
88
- if ( !empty($module_data['ModuleHidden']) || !$moduleManager->is_active($parser_type) ){
89
- continue;
90
- }
91
- $selected = ( isset($search_params['s_link_type']) && $search_params['s_link_type'] == $parser_type )?' selected="selected"':'';
92
- printf('<option value="%s"%s>%s</option>', $parser_type, $selected, $module_data['Name']);
93
- }
94
- echo '</optgroup>';
95
-
96
- /*
97
- $link_types = array(
98
- __('Any', 'broken-link-checker') => '',
99
- __('Normal link', 'broken-link-checker') => 'link',
100
- __('Image', 'broken-link-checker') => 'image',
101
- __('Custom field', 'broken-link-checker') => 'custom_field',
102
- __('Bookmark', 'broken-link-checker') => 'blogroll',
103
- __('Comment', 'broken-link-checker') => 'comment',
104
- );
105
- */
106
- ?>
107
- </select>
108
-
109
- </fieldset>
110
-
111
- <div id="blc-search-button-row">
112
- <input type="submit" value="<?php esc_attr_e( 'Search Links', 'broken-link-checker' ); ?>" id="blc-search-button" name="search_button" class="button-primary" />
113
- <input type="button" value="<?php esc_attr_e( 'Cancel', 'broken-link-checker' ); ?>" id="blc-cancel-search" class="button" />
114
- </div>
115
-
116
- </form>
117
  </div>
1
+ <?php
2
+ $search_params = $current_filter['search_params'];
3
+ ?>
4
+ <div class="search-box">
5
+
6
+ <?php
7
+ //If we're currently displaying search results offer the user the option to
8
+ //save the search query as a custom filter.
9
+ if ( $filter_id == 'search' ){
10
+ ?>
11
+ <form name="save-search-query" id="custom-filter-form" action="<?php echo admin_url("tools.php?page=view-broken-links"); ?>" method="post" class="blc-inline-form">
12
+ <?php wp_nonce_field('create-custom-filter'); ?>
13
+ <input type="hidden" name="name" id="blc-custom-filter-name" value="" />
14
+ <input type="hidden" name="params" id="blc-custom-filter-params" value="<?php echo http_build_query($search_params, null, '&'); ?>" />
15
+ <input type="hidden" name="action" value="create-custom-filter" />
16
+ <input type="button" value="<?php esc_attr_e( 'Save This Search As a Filter', 'broken-link-checker' ); ?>" id="blc-create-filter" class="button" />
17
+ </form>
18
+ <?php
19
+ } elseif ( !empty($current_filter['custom']) ){
20
+ //If we're displaying a custom filter give an option to delete it.
21
+ ?>
22
+ <form name="save-search-query" id="custom-filter-form" action="<?php echo admin_url("tools.php?page=view-broken-links"); ?>" method="post" class="blc-inline-form">
23
+ <?php wp_nonce_field('delete-custom-filter'); ?>
24
+ <input type="hidden" name="filter_id" id="blc-custom-filter-id" value="<?php echo $filter_id; ?>" />
25
+ <input type="hidden" name="action" value="delete-custom-filter" />
26
+ <input type="submit" value="<?php esc_attr_e( 'Delete This Filter', 'broken-link-checker' ); ?>" id="blc-delete-filter" class="button" />
27
+ </form>
28
+ <?php
29
+ }
30
+ ?>
31
+
32
+ <input type="button" value="<?php esc_attr_e( 'Search', 'broken-link-checker' ); ?> &raquo;" id="blc-open-search-box" class="button" />
33
+ </div>
34
+
35
+ <!-- The search dialog -->
36
+ <div id='search-links-dialog' title='Search'>
37
+ <form class="search-form" action="<?php echo admin_url('tools.php?page=view-broken-links'); ?>" method="get">
38
+ <input type="hidden" name="page" value="view-broken-links" />
39
+ <input type="hidden" name="filter_id" value="search" />
40
+ <fieldset>
41
+
42
+ <label for="s_link_text"><?php _e('Link text', 'broken-link-checker'); ?></label>
43
+ <input type="text" name="s_link_text" value="<?php if(!empty($search_params['s_link_text'])) echo esc_attr($search_params['s_link_text']); ?>" id="s_link_text" class="text ui-widget-content" />
44
+
45
+ <label for="s_link_url"><?php _e('URL', 'broken-link-checker'); ?></label>
46
+ <input type="text" name="s_link_url" id="s_link_url" value="<?php if(!empty($search_params['s_link_url'])) echo esc_attr($search_params['s_link_url']); ?>" class="text ui-widget-content" />
47
+
48
+ <label for="s_http_code"><?php _e('HTTP code', 'broken-link-checker'); ?></label>
49
+ <input type="text" name="s_http_code" id="s_http_code" value="<?php if(!empty($search_params['s_http_code'])) echo esc_attr($search_params['s_http_code']); ?>" class="text ui-widget-content" />
50
+
51
+ <label for="s_filter"><?php _e('Link status', 'broken-link-checker'); ?></label>
52
+ <select name="s_filter" id="s_filter">
53
+ <?php
54
+ if ( !empty($search_params['s_filter']) ){
55
+ $search_subfilter = $search_params['s_filter'];
56
+ } else {
57
+ $search_subfilter = 'all';
58
+ }
59
+
60
+ $linkQuery = blcLinkQuery::getInstance();
61
+ foreach ($linkQuery->native_filters as $filter => $data){
62
+ $selected = ($search_subfilter == $filter)?' selected="selected"':'';
63
+ printf('<option value="%s"%s>%s</option>', $filter, $selected, $data['name']);
64
+ }
65
+ ?>
66
+ </select>
67
+
68
+ <label for="s_link_type"><?php _e('Link type', 'broken-link-checker'); ?></label>
69
+ <select name="s_link_type" id="s_link_type">
70
+ <option value=""><?php _e('Any', 'broken-link-checker'); ?></option>
71
+ <?php
72
+ $moduleManager = blcModuleManager::getInstance();
73
+
74
+ printf('<optgroup label="%s">', esc_attr(__('Links used in', 'broken-link-checker')));
75
+ $containers = $moduleManager->get_modules_by_category('container', false, true);
76
+ foreach($containers as $container_type => $module_data){
77
+ if ( !empty($module_data['ModuleHidden']) || !$moduleManager->is_active($container_type) ){
78
+ continue;
79
+ }
80
+ $selected = ( isset($search_params['s_link_type']) && $search_params['s_link_type'] == $container_type )?' selected="selected"':'';
81
+ printf('<option value="%s"%s>%s</option>', $container_type, $selected, $module_data['Name']);
82
+ }
83
+ echo '</optgroup>';
84
+ //TODO: Better group labels
85
+ printf('<optgroup label="%s">', esc_attr(__('Link type', 'broken-link-checker')));
86
+ $parsers = $moduleManager->get_modules_by_category('parser', false, true);
87
+ foreach($parsers as $parser_type => $module_data){
88
+ if ( !empty($module_data['ModuleHidden']) || !$moduleManager->is_active($parser_type) ){
89
+ continue;
90
+ }
91
+ $selected = ( isset($search_params['s_link_type']) && $search_params['s_link_type'] == $parser_type )?' selected="selected"':'';
92
+ printf('<option value="%s"%s>%s</option>', $parser_type, $selected, $module_data['Name']);
93
+ }
94
+ echo '</optgroup>';
95
+
96
+ /*
97
+ $link_types = array(
98
+ __('Any', 'broken-link-checker') => '',
99
+ __('Normal link', 'broken-link-checker') => 'link',
100
+ __('Image', 'broken-link-checker') => 'image',
101
+ __('Custom field', 'broken-link-checker') => 'custom_field',
102
+ __('Bookmark', 'broken-link-checker') => 'blogroll',
103
+ __('Comment', 'broken-link-checker') => 'comment',
104
+ );
105
+ */
106
+ ?>
107
+ </select>
108
+
109
+ </fieldset>
110
+
111
+ <div id="blc-search-button-row">
112
+ <input type="submit" value="<?php esc_attr_e( 'Search Links', 'broken-link-checker' ); ?>" id="blc-search-button" name="search_button" class="button-primary" />
113
+ <input type="button" value="<?php esc_attr_e( 'Cancel', 'broken-link-checker' ); ?>" id="blc-cancel-search" class="button" />
114
+ </div>
115
+
116
+ </form>
117
  </div>
includes/admin/sidebar.php CHANGED
@@ -1,14 +1,14 @@
1
- <!-- Advertising -->
2
- <?php
3
- $configuration = blc_get_configuration();
4
- if ( !$configuration->get('user_has_donated') ):
5
- ?>
6
- <div id="managewp-ad" class="postbox">
7
- <div class="inside">
8
- <a href="http://managewp.com/?utm_source=broken_link_checker&utm_medium=Banner&utm_content=mwp250_2&utm_campaign=Plugins" title="ManageWP">
9
- <img src="<?php echo plugins_url('images/mwp250_2.png', BLC_PLUGIN_FILE) ?>" width="250" height="250" alt="ManageWP">
10
- </a>
11
- </div>
12
- </div>
13
- <?php
14
  endif; ?>
1
+ <!-- Advertising -->
2
+ <?php
3
+ $configuration = blc_get_configuration();
4
+ if ( !$configuration->get('user_has_donated') ):
5
+ ?>
6
+ <div id="managewp-ad" class="postbox">
7
+ <div class="inside">
8
+ <a href="http://managewp.com/?utm_source=broken_link_checker&utm_medium=Banner&utm_content=mwp250_2&utm_campaign=Plugins" title="ManageWP">
9
+ <img src="<?php echo plugins_url('images/mwp250_2.png', BLC_PLUGIN_FILE) ?>" width="250" height="250" alt="ManageWP">
10
+ </a>
11
+ </div>
12
+ </div>
13
+ <?php
14
  endif; ?>
includes/admin/table-printer.php CHANGED
@@ -75,7 +75,7 @@ if ( ! class_exists( 'blcTablePrinter' ) ) {
75
  if ( $this->core->conf->options['table_color_code_status'] ) {
76
  $table_classes[] = 'color-code-link-status';
77
  };
78
- $table_classes[] = 'base-filter-' . $current_filter['base_filter'];
79
  printf(
80
  '<table class="%s" id="blc-links"><thead><tr>',
81
  implode( ' ', $table_classes )
75
  if ( $this->core->conf->options['table_color_code_status'] ) {
76
  $table_classes[] = 'color-code-link-status';
77
  };
78
+ $table_classes[] = 'base-filter-' . esc_html( $current_filter['base_filter'] );
79
  printf(
80
  '<table class="%s" id="blc-links"><thead><tr>',
81
  implode( ' ', $table_classes )
includes/any-post.php CHANGED
@@ -1,804 +1,804 @@
1
- <?php
2
-
3
- /**
4
- * The manager to rule all (post) managers.
5
- *
6
- * This class dynamically registers container modules for the available post types
7
- * (including custom post types) and does stuff that pertain to all of them, such
8
- * as handling save/delete hooks and (re)creating synch records.
9
- *
10
- * @package Broken Link Checker
11
- * @author Janis Elsts
12
- * @access private
13
- */
14
- class blcPostTypeOverlord {
15
- public $enabled_post_types = array(); //Post types currently selected for link checking
16
- public $enabled_post_statuses = array('publish'); //Only posts that have one of these statuses shall be checked
17
-
18
- var $plugin_conf;
19
- var $resynch_already_done = false;
20
-
21
- /**
22
- * Class "constructor". Can't use an actual constructor due to how PHP4 handles object references.
23
- *
24
- * Specifically, this class is a singleton. The function needs to pass $this to several other
25
- * functions (to set up hooks), which will store the reference for later use. However, it appears
26
- * that in PHP4 the actual value of $this is thrown away right after the constructor finishes, and
27
- * `new` returns a *copy* of $this. The result is that getInstance() won't be returning a ref.
28
- * to the same object as is used for hook callbacks. And that's horrible.
29
- *
30
- * Sets up hooks that monitor added/modified/deleted posts and registers
31
- * virtual modules for all post types.
32
- *
33
- * @return void
34
- */
35
- function init(){
36
- $this->plugin_conf = blc_get_configuration();
37
-
38
- if ( isset($this->plugin_conf->options['enabled_post_statuses']) ){
39
- $this->enabled_post_statuses = $this->plugin_conf->options['enabled_post_statuses'];
40
- }
41
-
42
- //Register a virtual container module for each enabled post type
43
- $module_manager = blcModuleManager::getInstance();
44
-
45
- $post_types = get_post_types(array(), 'objects');
46
- $exceptions = array('revision', 'nav_menu_item', 'attachment');
47
-
48
- foreach($post_types as $data){
49
- $post_type = $data->name;
50
-
51
- if ( in_array($post_type, $exceptions) ){
52
- continue;
53
- }
54
-
55
- $module_manager->register_virtual_module(
56
- $post_type,
57
- array(
58
- 'Name' => $data->labels->name,
59
- 'ModuleCategory' => 'container',
60
- 'ModuleContext' => 'all',
61
- 'ModuleClassName' => 'blcAnyPostContainerManager',
62
- )
63
- );
64
- }
65
-
66
- //These hooks update the synch & instance records when posts are added, deleted or modified.
67
- add_action('delete_post', array(&$this,'post_deleted'));
68
- add_action('save_post', array(&$this,'post_saved'));
69
- //We also treat post trashing/untrashing as delete/save.
70
- add_action('trash_post', array(&$this,'post_deleted'));
71
- add_action('untrash_post', array(&$this,'post_saved'));
72
-
73
- //Highlight and nofollow broken links in posts & pages
74
- if ( $this->plugin_conf->options['mark_broken_links'] || $this->plugin_conf->options['nofollow_broken_links'] ){
75
- add_filter( 'the_content', array(&$this, 'hook_the_content') );
76
- if ( $this->plugin_conf->options['mark_broken_links'] && !empty( $this->plugin_conf->options['broken_link_css'] ) ){
77
- add_action( 'wp_head', array(&$this,'hook_wp_head') );
78
- }
79
- }
80
- }
81
-
82
- /**
83
- * Retrieve an instance of the overlord class.
84
- *
85
- * @return blcPostTypeOverlord
86
- */
87
- static function getInstance(){
88
- static $instance = null;
89
- if ( is_null($instance) ){
90
- $instance = new blcPostTypeOverlord;
91
- $instance->init();
92
- }
93
- return $instance;
94
- }
95
-
96
- /**
97
- * Notify the overlord that a post type is active.
98
- *
99
- * Called by individual instances of blcAnyPostContainerManager to let
100
- * the overlord know that they've been created. Since a module instance
101
- * is only created if the module is active, this event indicates that
102
- * the user has enabled the corresponding post type for link checking.
103
- *
104
- * @param string $post_type
105
- * @return void
106
- */
107
- function post_type_enabled($post_type){
108
- if ( !in_array($post_type, $this->enabled_post_types) ){
109
- $this->enabled_post_types[] = $post_type;
110
- }
111
- }
112
-
113
- /**
114
- * Remove the synch. record and link instances associated with a post when it's deleted
115
- *
116
- * @param int $post_id
117
- * @return void
118
- */
119
- function post_deleted($post_id){
120
- global $wpdb;
121
-
122
- $post_id = intval( $post_id );
123
- //Get the container type matching the type of the deleted post
124
- $post = get_post( $post_id );
125
- if ( !$post ){
126
- return;
127
- }
128
- //Get the associated container object
129
- $post_type = get_post_type( $post );
130
- $post_container = blcContainerHelper::get_container( array( $post_type, $post_id ) );
131
-
132
- if ( $post_container ){
133
- //Delete the container
134
- $post_container->delete();
135
-
136
- // Firstly: See if we have any current instances
137
- $q_current_instance_ids = $wpdb->prepare(
138
- 'SELECT instance_id FROM `'.$wpdb->prefix.'_blc_instances` WHERE container_id = %d AND container_type = %s',
139
- $post_id,
140
- $post_type );
141
-
142
- $current_instance_ids_results = $wpdb->get_results( $q_current_instance_ids, ARRAY_A );
143
-
144
- if( $wpdb->num_rows == 0 ) {
145
- // No current instances present, skip cleanup at once
146
- return;
147
- }
148
-
149
- $current_instance_ids = wp_list_pluck( $current_instance_ids_results, 'instance_id' );
150
-
151
- // Secondly: Get all link_ids used in our current instances
152
- $q_current_link_ids = 'SELECT DISTINCT link_id FROM `'.$wpdb->prefix.'_blc_instances` WHERE instance_id IN (\''.implode("', '", $current_instance_ids).'\')';
153
-
154
- $q_current_link_ids_results = $wpdb->get_results( $q_current_link_ids, ARRAY_A );
155
-
156
- $current_link_ids = wp_list_pluck( $q_current_link_ids_results, 'link_id' );
157
-
158
- // Go ahead and remove blc_instances for this container, blc_cleanup_links( $current_link_ids ) will find and remove any dangling links in the blc_links table
159
- $wpdb->query( 'DELETE FROM `'.$wpdb->prefix.'_blc_instances` WHERE instance_id IN (\''.implode("', '", $current_instance_ids).'\')' );
160
-
161
- //Clean up any dangling links
162
- blc_cleanup_links( $current_link_ids );
163
- }
164
- }
165
-
166
- /**
167
- * When a post is saved or modified, mark it as unparsed.
168
- *
169
- * @param int $post_id
170
- * @return void
171
- */
172
- function post_saved($post_id){
173
- //Get the container type matching the type of the deleted post
174
- $post = get_post($post_id);
175
- if ( !$post ){
176
- return;
177
- }
178
-
179
- //Only check links in currently enabled post types
180
- if ( !in_array($post->post_type, $this->enabled_post_types) ) return;
181
-
182
- //Only check posts that have one of the allowed statuses
183
- if ( !in_array($post->post_status, $this->enabled_post_statuses) ) return;
184
-
185
- //Get the container & mark it as unparsed
186
- $args = array($post->post_type, intval($post_id));
187
- $post_container = blcContainerHelper::get_container( $args );
188
-
189
- $post_container->mark_as_unsynched();
190
- }
191
-
192
-
193
- /**
194
- * Create or update synchronization records for all posts.
195
- *
196
- * @param string $container_type
197
- * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
198
- * @return void
199
- */
200
- function resynch($container_type = '', $forced = false){
201
- global $wpdb; /** @var wpdb $wpdb */
202
- global $blclog;
203
-
204
- //Resynch is expensive in terms of DB performance. Thus we only do it once, processing
205
- //all post types in one go and ignoring any further resynch requests during this pageload.
206
- //BUG: This might be a problem if there ever is an actual need to run resynch twice or
207
- //more per pageload.
208
- if ( $this->resynch_already_done ){
209
- $blclog->log(sprintf('...... Skipping "%s" resyncyh since all post types were already synched.', $container_type));
210
- return;
211
- }
212
-
213
- if ( empty($this->enabled_post_types) ){
214
- $blclog->warn(sprintf('...... Skipping "%s" resyncyh since no post types are enabled.', $container_type));
215
- return;
216
- }
217
-
218
- $escaped_post_types = array_map('esc_sql', $this->enabled_post_types);
219
- $escaped_post_statuses = array_map('esc_sql', $this->enabled_post_statuses);
220
-
221
- if ( $forced ){
222
- //Create new synchronization records for all posts.
223
- $blclog->log('...... Creating synch records for these post types: '.implode(', ', $escaped_post_types) . ' that have one of these statuses: ' . implode(', ', $escaped_post_statuses));
224
- $start = microtime(true);
225
- $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
226
- SELECT posts.id, posts.post_type, 0
227
- FROM {$wpdb->posts} AS posts
228
- WHERE
229
- posts.post_status IN (%s)
230
- AND posts.post_type IN (%s)";
231
- $q = sprintf(
232
- $q,
233
- "'" . implode("', '", $escaped_post_statuses) . "'",
234
- "'" . implode("', '", $escaped_post_types) . "'"
235
- );
236
- $wpdb->query( $q );
237
- $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
238
- } else {
239
- //Delete synch records corresponding to posts that no longer exist.
240
- $blclog->log('...... Deleting synch records for removed posts');
241
- $start = microtime(true);
242
- $q = "DELETE synch.*
243
- FROM
244
- {$wpdb->prefix}blc_synch AS synch LEFT JOIN {$wpdb->posts} AS posts
245
- ON posts.ID = synch.container_id
246
- WHERE
247
- synch.container_type IN (%s) AND posts.ID IS NULL";
248
- $q = sprintf(
249
- $q,
250
- "'" . implode("', '", $escaped_post_types) . "'"
251
- );
252
- $wpdb->query( $q );
253
- $elapsed = microtime(true) - $start;
254
- $blclog->debug($q);
255
- $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
256
-
257
- //Delete records where the post status is not one of the enabled statuses.
258
- $blclog->log('...... Deleting synch records for posts that have a disallowed status');
259
- $start = microtime(true);
260
- $q = "DELETE synch.*
261
- FROM
262
- {$wpdb->prefix}blc_synch AS synch
263
- LEFT JOIN {$wpdb->posts} AS posts
264
- ON (synch.container_id = posts.ID and synch.container_type = posts.post_type)
265
- WHERE
266
- posts.post_status NOT IN (%s)";
267
- $q = sprintf(
268
- $q,
269
- "'" . implode("', '", $escaped_post_statuses) . "'"
270
- );
271
- $wpdb->query( $q );
272
- $elapsed = microtime(true) - $start;
273
- $blclog->debug($q);
274
- $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
275
-
276
- //Remove the 'synched' flag from all posts that have been updated
277
- //since the last time they were parsed/synchronized.
278
- $blclog->log('...... Marking changed posts as unsynched');
279
- $start = microtime(true);
280
- $q = "UPDATE
281
- {$wpdb->prefix}blc_synch AS synch
282
- JOIN {$wpdb->posts} AS posts ON (synch.container_id = posts.ID and synch.container_type=posts.post_type)
283
- SET
284
- synched = 0
285
- WHERE
286
- synch.last_synch < posts.post_modified";
287
- $wpdb->query( $q );
288
- $elapsed = microtime(true) - $start;
289
- $blclog->debug($q);
290
- $blclog->log(sprintf('...... %d rows updated in %.3f seconds', $wpdb->rows_affected, $elapsed));
291
-
292
- //Create synch. records for posts that don't have them.
293
- $blclog->log('...... Creating synch records for new posts');
294
- $start = microtime(true);
295
- $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
296
- SELECT posts.id, posts.post_type, 0
297
- FROM
298
- {$wpdb->posts} AS posts LEFT JOIN {$wpdb->prefix}blc_synch AS synch
299
- ON (synch.container_id = posts.ID and synch.container_type=posts.post_type)
300
- WHERE
301
- posts.post_status IN (%s)
302
- AND posts.post_type IN (%s)
303
- AND synch.container_id IS NULL";
304
- $q = sprintf(
305
- $q,
306
- "'" . implode("', '", $escaped_post_statuses) . "'",
307
- "'" . implode("', '", $escaped_post_types) . "'"
308
- );
309
- $wpdb->query($q);
310
- $elapsed = microtime(true) - $start;
311
- $blclog->debug($q);
312
- $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, $elapsed));
313
- }
314
-
315
- $this->resynch_already_done = true;
316
- }
317
-
318
- /**
319
- * Hook for the 'the_content' filter. Scans the current post and adds the 'broken_link'
320
- * CSS class to all links that are known to be broken. Currently works only on standard
321
- * HTML links (i.e. the '<a href=...' kind).
322
- *
323
- * @param string $content Post content
324
- * @return string Modified post content.
325
- */
326
- function hook_the_content($content){
327
- global $post, $wpdb; /** @var wpdb $wpdb */
328
- if ( empty($post) || !in_array($post->post_type, $this->enabled_post_types)) {
329
- return $content;
330
- }
331
-
332
- //Retrieve info about all occurrences of broken links in the current post
333
- $q = "
334
- SELECT instances.raw_url
335
- FROM {$wpdb->prefix}blc_instances AS instances JOIN {$wpdb->prefix}blc_links AS links
336
- ON instances.link_id = links.link_id
337
- WHERE
338
- instances.container_type = %s
339
- AND instances.container_id = %d
340
- AND links.broken = 1
341
- AND parser_type = 'link'
342
- ";
343
- $q = $wpdb->prepare($q, $post->post_type, $post->ID);
344
- $links = $wpdb->get_results($q, ARRAY_A);
345
-
346
- //Return the content unmodified if there are no broken links in this post.
347
- if ( empty($links) || !is_array($links) ){
348
- return $content;
349
- }
350
-
351
- //Put the broken link URLs in an array
352
- $broken_link_urls = array();
353
- foreach($links as $link){
354
- $broken_link_urls[] = $link['raw_url'];
355
- }
356
-
357
- //Iterate over all HTML links and modify the broken ones
358
- if ( $parser = blcParserHelper::get_parser('link') ){
359
- $content = $parser->multi_edit($content, array(&$this, 'highlight_broken_link'), $broken_link_urls);
360
- }
361
-
362
- return $content;
363
- }
364
-
365
- /**
366
- * Analyse a link and add 'broken_link' CSS class if the link is broken.
367
- *
368
- * @see blcHtmlLink::multi_edit()
369
- *
370
- * @param array $link Associative array of link data.
371
- * @param array $broken_link_urls List of broken link URLs present in the current post.
372
- * @return array|string The modified link
373
- */
374
- function highlight_broken_link($link, $broken_link_urls){
375
- if ( !in_array($link['href'], $broken_link_urls) ){
376
- //Link not broken = return the original link tag
377
- return $link['#raw'];
378
- }
379
-
380
- //Add 'broken_link' to the 'class' attribute (unless already present).
381
- if ( $this->plugin_conf->options['mark_broken_links'] ){
382
- if ( isset($link['class']) ){
383
- $classes = explode(' ', $link['class']);
384
- if ( !in_array('broken_link', $classes) ){
385
- $classes[] = 'broken_link';
386
- $link['class'] = implode(' ', $classes);
387
- }
388
- } else {
389
- $link['class'] = 'broken_link';
390
- }
391
- }
392
-
393
- //Nofollow the link (unless it's already nofollow'ed)
394
- if ( $this->plugin_conf->options['nofollow_broken_links'] ){
395
- if ( isset($link['rel']) ){
396
- $relations = explode(' ', $link['rel']);
397
- if ( !in_array('nofollow', $relations) ){
398
- $relations[] = 'nofollow';
399
- $link['rel'] = implode(' ', $relations);
400
- }
401
- } else {
402
- $link['rel'] = 'nofollow';
403
- }
404
- }
405
-
406
- return $link;
407
- }
408
-
409
- /**
410
- * A hook for the 'wp_head' action. Outputs the user-defined broken link CSS.
411
- *
412
- * @return void
413
- */
414
- function hook_wp_head(){
415
- echo '<style type="text/css">',$this->plugin_conf->options['broken_link_css'],'</style>';
416
- }
417
- }
418
-
419
- //Start up the post overlord
420
- blcPostTypeOverlord::getInstance();
421
-
422
-
423
- /**
424
- * Universal container item class used for all post types.
425
- *
426
- * @package Broken Link Checker
427
- * @author Janis Elsts
428
- * @access public
429
- */
430
- class blcAnyPostContainer extends blcContainer {
431
- var $default_field = 'post_content';
432
-
433
- /**
434
- * Get action links for this post.
435
- *
436
- * @param string $container_field Ignored.
437
- * @return array of action link HTML.
438
- */
439
- function ui_get_action_links($container_field = ''){
440
- $actions = array();
441
-
442
- //Fetch the post (it should be cached already)
443
- $post = $this->get_wrapped_object();
444
- if ( !$post ){
445
- return $actions;
446
- }
447
-
448
- $post_type_object = get_post_type_object($post->post_type);
449
-
450
- //Each post type can have its own cap requirements
451
- if ( current_user_can( $post_type_object->cap->edit_post, $this->container_id ) ){
452
- $actions['edit'] = sprintf(
453
- '<span class="edit"><a href="%s" title="%s">%s</a>',
454
- $this->get_edit_url(),
455
- $post_type_object->labels->edit_item,
456
- __('Edit')
457
- );
458
-
459
- //Trash/Delete link
460
- if ( current_user_can( $post_type_object->cap->delete_post, $this->container_id ) ){
461
- if ( $this->can_be_trashed() ) {
462
- $actions['trash'] = sprintf(
463
- "<span class='trash'><a class='submitdelete' title='%s' href='%s'>%s</a>",
464
- esc_attr(__('Move this item to the Trash')),
465
- esc_attr(get_delete_post_link($this->container_id, '', false)),
466
- __('Trash')
467
- );
468
- } else {
469
- $actions['delete'] = sprintf(
470
- "<span><a class='submitdelete' title='%s' href='%s'>%s</a>",
471
- esc_attr(__('Delete this item permanently')),
472
- esc_attr(get_delete_post_link($this->container_id, '', true)),
473
- __('Delete')
474
- );
475
- }
476
- }
477
- }
478
-
479
- //View/Preview link
480
- $title = get_the_title($this->container_id);
481
- if ( in_array($post->post_status, array('pending', 'draft')) ) {
482
- if ( current_user_can($post_type_object->cap->edit_post, $this->container_id) ){
483
- $actions['view'] = sprintf(
484
- '<span class="view"><a href="%s" title="%s" rel="permalink">%s</a>',
485
- esc_url( add_query_arg( 'preview', 'true', get_permalink($this->container_id) ) ),
486
- esc_attr(sprintf(__('Preview &#8220;%s&#8221;'), $title)),
487
- __('Preview')
488
- );
489
- }
490
- } elseif ( 'trash' != $post->post_status ) {
491
- $actions['view'] = sprintf(
492
- '<span class="view"><a href="%s" title="%s" rel="permalink">%s</a>',
493
- esc_url( get_permalink($this->container_id) ),
494
- esc_attr(sprintf(__('View &#8220;%s&#8221;'), $title)),
495
- __('View')
496
- );
497
- }
498
-
499
- return $actions;
500
- }
501
-
502
- /**
503
- * Get the HTML for displaying the post title in the "Source" column.
504
- *
505
- * @param string $container_field Ignored.
506
- * @param string $context How to filter the output. Optional, defaults to 'display'.
507
- * @return string HTML
508
- */
509
- function ui_get_source($container_field = '', $context = 'display'){
510
- $source = '<a class="row-title" href="%s" title="%s">%s</a>';
511
- $source = sprintf(
512
- $source,
513
- $this->get_edit_url(),
514
- esc_attr(__('Edit this item')),
515
- get_the_title($this->container_id)
516
- );
517
-
518
- return $source;
519
- }
520
-
521
- /**
522
- * Get edit URL for this container. Returns the URL of the Dashboard page where the item
523
- * associated with this container can be edited.
524
- *
525
- * @access protected
526
- *
527
- * @return string
528
- */
529
- function get_edit_url(){
530
- /*
531
- The below is a near-exact copy of the get_post_edit_link() function.
532
- Unfortunately we can't just call that function because it has a hardcoded
533
- caps-check which fails when called from the email notification script
534
- executed by Cron.
535
- */
536
-
537
- if ( !$post = $this->get_wrapped_object() ){
538
- return '';
539
- }
540
-
541
- $context = 'display';
542
- $action = '&amp;action=edit';
543
-
544
- $post_type_object = get_post_type_object( $post->post_type );
545
- if ( !$post_type_object ){
546
- return '';
547
- }
548
-
549
- return apply_filters( 'get_edit_post_link', admin_url( sprintf($post_type_object->_edit_link . $action, $post->ID) ), $post->ID, $context );
550
- }
551
-
552
- /**
553
- * Retrieve the post associated with this container.
554
- *
555
- * @access protected
556
- *
557
- * @param bool $ensure_consistency Set this to true to ignore the cached $wrapped_object value and retrieve an up-to-date copy of the wrapped object from the DB (or WP's internal cache).
558
- * @return object Post data.
559
- */
560
- function get_wrapped_object($ensure_consistency = false){
561
- if( $ensure_consistency || is_null($this->wrapped_object) ){
562
- $this->wrapped_object = get_post($this->container_id);
563
- }
564
- return $this->wrapped_object;
565
- }
566
-
567
- /**
568
- * Update the post associated with this container.
569
- *
570
- * @access protected
571
- *
572
- * @return bool|WP_Error True on success, an error if something went wrong.
573
- */
574
- function update_wrapped_object(){
575
- if ( is_null($this->wrapped_object) ){
576
- return new WP_Error(
577
- 'no_wrapped_object',
578
- __('Nothing to update', 'broken-link-checker')
579
- );
580
- }
581
-
582
- $post_id = wp_update_post($this->wrapped_object, true);
583
- if ( is_wp_error($post_id) ) {
584
- return $post_id;
585
- } else if ( $post_id == 0 ){
586
- return new WP_Error(
587
- 'update_failed',
588
- sprintf(__('Updating post %d failed', 'broken-link-checker'), $this->container_id)
589
- );
590
- } else {
591
- return true;
592
- }
593
- }
594
-
595
- /**
596
- * Get the base URL of the container. For posts, the post permalink is used
597
- * as the base URL when normalizing relative links.
598
- *
599
- * @return string
600
- */
601
- function base_url(){
602
- return get_permalink($this->container_id);
603
- }
604
-
605
- /**
606
- * Delete or trash the post corresponding to this container.
607
- * Will always move to trash instead of deleting if trash is enabled.
608
- *
609
- * @return bool|WP_error
610
- */
611
- function delete_wrapped_object(){
612
- //Note that we don't need to delete the synch record and instances here -
613
- //wp_delete_post()/wp_trash_post() will run the post_delete/trash hook,
614
- //which will be caught by blcPostContainerManager, which will in turn
615
- //delete anything that needs to be deleted.
616
- if ( EMPTY_TRASH_DAYS ){
617
- return $this->trash_wrapped_object();
618
- } else {
619
- if ( wp_delete_post($this->container_id, true) ){
620
- return true;
621
- } else {
622
- return new WP_Error(
623
- 'delete_failed',
624
- sprintf(
625
- __('Failed to delete post "%s" (%d)', 'broken-link-checker'),
626
- get_the_title($this->container_id),
627
- $this->container_id
628
- )
629
- );
630
- }
631
- }
632
- }
633
-
634
- /**
635
- * Move the post corresponding to this container to the Trash.
636
- *
637
- * @return bool|WP_Error
638
- */
639
- function trash_wrapped_object(){
640
- if ( !EMPTY_TRASH_DAYS ){
641
- return new WP_Error(
642
- 'trash_disabled',
643
- sprintf(
644
- __('Can\'t move post "%s" (%d) to the trash because the trash feature is disabled', 'broken-link-checker'),
645
- get_the_title($this->container_id),
646
- $this->container_id
647
- )
648
- );
649
- }
650
-
651
- $post = get_post($this->container_id);
652
- if ( $post->post_status == 'trash' ){
653
- //Prevent conflicts between post and custom field containers trying to trash the same post.
654
- //BUG: Post and custom field containers shouldn't wrap the same object
655
- return true;
656
- }
657
-
658
- if ( wp_trash_post($this->container_id) ){
659
- return true;
660
- } else {
661
- return new WP_Error(
662
- 'trash_failed',
663
- sprintf(
664
- __('Failed to move post "%s" (%d) to the trash', 'broken-link-checker'),
665
- get_the_title($this->container_id),
666
- $this->container_id
667
- )
668
- );
669
- }
670
- }
671
-
672
- /**
673
- * Check if the current user can delete/trash this post.
674
- *
675
- * @return bool
676
- */
677
- function current_user_can_delete(){
678
- $post = $this->get_wrapped_object();
679
- $post_type_object = get_post_type_object($post->post_type);
680
- return current_user_can( $post_type_object->cap->delete_post, $this->container_id );
681
- }
682
-
683
- function can_be_trashed(){
684
- return defined('EMPTY_TRASH_DAYS') && EMPTY_TRASH_DAYS;
685
- }
686
- }
687
-
688
-
689
-
690
- /**
691
- * Universal manager usable for most post types.
692
- *
693
- * @package Broken Link Checker
694
- * @access public
695
- */
696
- class blcAnyPostContainerManager extends blcContainerManager {
697
- var $container_class_name = 'blcAnyPostContainer';
698
- var $fields = array('post_content' => 'html');
699
-
700
- function init(){
701
- parent::init();
702
-
703
- //Notify the overlord that the post/container type that this instance is
704
- //responsible for is enabled.
705
- $overlord = blcPostTypeOverlord::getInstance();
706
- $overlord->post_type_enabled($this->container_type);
707
- }
708
-
709
- /**
710
- * Instantiate multiple containers of the container type managed by this class.
711
- *
712
- * @param array $containers Array of assoc. arrays containing container data.
713
- * @param string $purpose An optional code indicating how the retrieved containers will be used.
714
- * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
715
- *
716
- * @return array of blcPostContainer indexed by "container_type|container_id"
717
- */
718
- function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
719
- $containers = $this->make_containers($containers);
720
-
721
- //Preload post data if it is likely to be useful later
722
- $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_PARSING));
723
- if ( $preload ){
724
- $post_ids = array();
725
- foreach($containers as $container){
726
- $post_ids[] = $container->container_id;
727
- }
728
-
729
- $args = array('include' => implode(',', $post_ids));
730
- $posts = get_posts($args);
731
-
732
- foreach($posts as $post){
733
- $key = $this->container_type . '|' . $post->ID;
734
- if ( isset($containers[$key]) ){
735
- $containers[$key]->wrapped_object = $post;
736
- }
737
- }
738
- }
739
-
740
- return $containers;
741
- }
742
-
743
- /**
744
- * Create or update synchronization records for all posts.
745
- *
746
- * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
747
- * @return void
748
- */
749
- function resynch($forced = false){
750
- $overlord = blcPostTypeOverlord::getInstance();
751
- $overlord->resynch($this->container_type, $forced);
752
- }
753
-
754
- /**
755
- * Get the message to display after $n posts have been deleted.
756
- *
757
- * @param int $n Number of deleted posts.
758
- * @return string A delete confirmation message, e.g. "5 posts were moved deleted"
759
- */
760
- function ui_bulk_delete_message($n){
761
- //Since the "Trash" feature has been introduced, calling wp_delete_post
762
- //doesn't actually delete the post (unless you set force_delete to True),
763
- //just moves it to the trash. So we pick the message accordingly.
764
- //(If possible, BLC *always* moves to trash instead of deleting permanently.)
765
- if ( function_exists('wp_trash_post') && EMPTY_TRASH_DAYS ){
766
- return blcAnyPostContainerManager::ui_bulk_trash_message($n);
767
- } else {
768
- $post_type_object = get_post_type_object($this->container_type);
769
- $type_name = '';
770
-
771
- if ( $this->container_type == 'post' || is_null($post_type_object) ){
772
- $delete_msg = _n("%d post deleted.", "%d posts deleted.", $n, 'broken-link-checker');
773
- } elseif ( $this->container_type == 'page' ){
774
- $delete_msg = _n("%d page deleted.", "%d pages deleted.", $n, 'broken-link-checker');
775
- } else {
776
- $delete_msg = _n('%d "%s" deleted.', '%d "%s" deleted.', $n, 'broken-link-checker');
777
- $type_name = ($n == 1 ? $post_type_object->labels->singular_name : $post_type_object->labels->name);
778
- }
779
- return sprintf($delete_msg, $n, $type_name);
780
- }
781
- }
782
-
783
-
784
- /**
785
- * Get the message to display after $n posts have been trashed.
786
- *
787
- * @param int $n Number of deleted posts.
788
- * @return string A confirmation message, e.g. "5 posts were moved to trash"
789
- */
790
- function ui_bulk_trash_message($n){
791
- $post_type_object = get_post_type_object($this->container_type);
792
- $type_name = '';
793
-
794
- if ( $this->container_type == 'post' || is_null($post_type_object) ){
795
- $delete_msg = _n("%d post moved to the Trash.", "%d posts moved to the Trash.", $n, 'broken-link-checker');
796
- } elseif ( $this->container_type == 'page' ){
797
- $delete_msg = _n("%d page moved to the Trash.", "%d pages moved to the Trash.", $n, 'broken-link-checker');
798
- } else {
799
- $delete_msg = _n('%d "%s" moved to the Trash.', '%d "%s" moved to the Trash.', $n, 'broken-link-checker');
800
- $type_name = ($n == 1 ? $post_type_object->labels->singular_name : $post_type_object->labels->name);
801
- }
802
- return sprintf($delete_msg, $n, $type_name);
803
- }
804
- }
1
+ <?php
2
+
3
+ /**
4
+ * The manager to rule all (post) managers.
5
+ *
6
+ * This class dynamically registers container modules for the available post types
7
+ * (including custom post types) and does stuff that pertain to all of them, such
8
+ * as handling save/delete hooks and (re)creating synch records.
9
+ *
10
+ * @package Broken Link Checker
11
+ * @author Janis Elsts
12
+ * @access private
13
+ */
14
+ class blcPostTypeOverlord {
15
+ public $enabled_post_types = array(); //Post types currently selected for link checking
16
+ public $enabled_post_statuses = array('publish'); //Only posts that have one of these statuses shall be checked
17
+
18
+ var $plugin_conf;
19
+ var $resynch_already_done = false;
20
+
21
+ /**
22
+ * Class "constructor". Can't use an actual constructor due to how PHP4 handles object references.
23
+ *
24
+ * Specifically, this class is a singleton. The function needs to pass $this to several other
25
+ * functions (to set up hooks), which will store the reference for later use. However, it appears
26
+ * that in PHP4 the actual value of $this is thrown away right after the constructor finishes, and
27
+ * `new` returns a *copy* of $this. The result is that getInstance() won't be returning a ref.
28
+ * to the same object as is used for hook callbacks. And that's horrible.
29
+ *
30
+ * Sets up hooks that monitor added/modified/deleted posts and registers
31
+ * virtual modules for all post types.
32
+ *
33
+ * @return void
34
+ */
35
+ function init(){
36
+ $this->plugin_conf = blc_get_configuration();
37
+
38
+ if ( isset($this->plugin_conf->options['enabled_post_statuses']) ){
39
+ $this->enabled_post_statuses = $this->plugin_conf->options['enabled_post_statuses'];
40
+ }
41
+
42
+ //Register a virtual container module for each enabled post type
43
+ $module_manager = blcModuleManager::getInstance();
44
+
45
+ $post_types = get_post_types(array(), 'objects');
46
+ $exceptions = array('revision', 'nav_menu_item', 'attachment');
47
+
48
+ foreach($post_types as $data){
49
+ $post_type = $data->name;
50
+
51
+ if ( in_array($post_type, $exceptions) ){
52
+ continue;
53
+ }
54
+
55
+ $module_manager->register_virtual_module(
56
+ $post_type,
57
+ array(
58
+ 'Name' => $data->labels->name,
59
+ 'ModuleCategory' => 'container',
60
+ 'ModuleContext' => 'all',
61
+ 'ModuleClassName' => 'blcAnyPostContainerManager',
62
+ )
63
+ );
64
+ }
65
+
66
+ //These hooks update the synch & instance records when posts are added, deleted or modified.
67
+ add_action('delete_post', array(&$this,'post_deleted'));
68
+ add_action('save_post', array(&$this,'post_saved'));
69
+ //We also treat post trashing/untrashing as delete/save.
70
+ add_action('trash_post', array(&$this,'post_deleted'));
71
+ add_action('untrash_post', array(&$this,'post_saved'));
72
+
73
+ //Highlight and nofollow broken links in posts & pages
74
+ if ( $this->plugin_conf->options['mark_broken_links'] || $this->plugin_conf->options['nofollow_broken_links'] ){
75
+ add_filter( 'the_content', array(&$this, 'hook_the_content') );
76
+ if ( $this->plugin_conf->options['mark_broken_links'] && !empty( $this->plugin_conf->options['broken_link_css'] ) ){
77
+ add_action( 'wp_head', array(&$this,'hook_wp_head') );
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Retrieve an instance of the overlord class.
84
+ *
85
+ * @return blcPostTypeOverlord
86
+ */
87
+ static function getInstance(){
88
+ static $instance = null;
89
+ if ( is_null($instance) ){
90
+ $instance = new blcPostTypeOverlord;
91
+ $instance->init();
92
+ }
93
+ return $instance;
94
+ }
95
+
96
+ /**
97
+ * Notify the overlord that a post type is active.
98
+ *
99
+ * Called by individual instances of blcAnyPostContainerManager to let
100
+ * the overlord know that they've been created. Since a module instance
101
+ * is only created if the module is active, this event indicates that
102
+ * the user has enabled the corresponding post type for link checking.
103
+ *
104
+ * @param string $post_type
105
+ * @return void
106
+ */
107
+ function post_type_enabled($post_type){
108
+ if ( !in_array($post_type, $this->enabled_post_types) ){
109
+ $this->enabled_post_types[] = $post_type;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Remove the synch. record and link instances associated with a post when it's deleted
115
+ *
116
+ * @param int $post_id
117
+ * @return void
118
+ */
119
+ function post_deleted($post_id){
120
+ global $wpdb;
121
+
122
+ $post_id = intval( $post_id );
123
+ //Get the container type matching the type of the deleted post
124
+ $post = get_post( $post_id );
125
+ if ( !$post ){
126
+ return;
127
+ }
128
+ //Get the associated container object
129
+ $post_type = get_post_type( $post );
130
+ $post_container = blcContainerHelper::get_container( array( $post_type, $post_id ) );
131
+
132
+ if ( $post_container ){
133
+ //Delete the container
134
+ $post_container->delete();
135
+
136
+ // Firstly: See if we have any current instances
137
+ $q_current_instance_ids = $wpdb->prepare(
138
+ 'SELECT instance_id FROM `'.$wpdb->prefix.'_blc_instances` WHERE container_id = %d AND container_type = %s',
139
+ $post_id,
140
+ $post_type );
141
+
142
+ $current_instance_ids_results = $wpdb->get_results( $q_current_instance_ids, ARRAY_A );
143
+
144
+ if( $wpdb->num_rows == 0 ) {
145
+ // No current instances present, skip cleanup at once
146
+ return;
147
+ }
148
+
149
+ $current_instance_ids = wp_list_pluck( $current_instance_ids_results, 'instance_id' );
150
+
151
+ // Secondly: Get all link_ids used in our current instances
152
+ $q_current_link_ids = 'SELECT DISTINCT link_id FROM `'.$wpdb->prefix.'_blc_instances` WHERE instance_id IN (\''.implode("', '", $current_instance_ids).'\')';
153
+
154
+ $q_current_link_ids_results = $wpdb->get_results( $q_current_link_ids, ARRAY_A );
155
+
156
+ $current_link_ids = wp_list_pluck( $q_current_link_ids_results, 'link_id' );
157
+
158
+ // Go ahead and remove blc_instances for this container, blc_cleanup_links( $current_link_ids ) will find and remove any dangling links in the blc_links table
159
+ $wpdb->query( 'DELETE FROM `'.$wpdb->prefix.'_blc_instances` WHERE instance_id IN (\''.implode("', '", $current_instance_ids).'\')' );
160
+
161
+ //Clean up any dangling links
162
+ blc_cleanup_links( $current_link_ids );
163
+ }
164
+ }
165
+
166
+ /**
167
+ * When a post is saved or modified, mark it as unparsed.
168
+ *
169
+ * @param int $post_id
170
+ * @return void
171
+ */
172
+ function post_saved($post_id){
173
+ //Get the container type matching the type of the deleted post
174
+ $post = get_post($post_id);
175
+ if ( !$post ){
176
+ return;
177
+ }
178
+
179
+ //Only check links in currently enabled post types
180
+ if ( !in_array($post->post_type, $this->enabled_post_types) ) return;
181
+
182
+ //Only check posts that have one of the allowed statuses
183
+ if ( !in_array($post->post_status, $this->enabled_post_statuses) ) return;
184
+
185
+ //Get the container & mark it as unparsed
186
+ $args = array($post->post_type, intval($post_id));
187
+ $post_container = blcContainerHelper::get_container( $args );
188
+
189
+ $post_container->mark_as_unsynched();
190
+ }
191
+
192
+
193
+ /**
194
+ * Create or update synchronization records for all posts.
195
+ *
196
+ * @param string $container_type
197
+ * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
198
+ * @return void
199
+ */
200
+ function resynch($container_type = '', $forced = false){
201
+ global $wpdb; /** @var wpdb $wpdb */
202
+ global $blclog;
203
+
204
+ //Resynch is expensive in terms of DB performance. Thus we only do it once, processing
205
+ //all post types in one go and ignoring any further resynch requests during this pageload.
206
+ //BUG: This might be a problem if there ever is an actual need to run resynch twice or
207
+ //more per pageload.
208
+ if ( $this->resynch_already_done ){
209
+ $blclog->log(sprintf('...... Skipping "%s" resyncyh since all post types were already synched.', $container_type));
210
+ return;
211
+ }
212
+
213
+ if ( empty($this->enabled_post_types) ){
214
+ $blclog->warn(sprintf('...... Skipping "%s" resyncyh since no post types are enabled.', $container_type));
215
+ return;
216
+ }
217
+
218
+ $escaped_post_types = array_map('esc_sql', $this->enabled_post_types);
219
+ $escaped_post_statuses = array_map('esc_sql', $this->enabled_post_statuses);
220
+
221
+ if ( $forced ){
222
+ //Create new synchronization records for all posts.
223
+ $blclog->log('...... Creating synch records for these post types: '.implode(', ', $escaped_post_types) . ' that have one of these statuses: ' . implode(', ', $escaped_post_statuses));
224
+ $start = microtime(true);
225
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
226
+ SELECT posts.id, posts.post_type, 0
227
+ FROM {$wpdb->posts} AS posts
228
+ WHERE
229
+ posts.post_status IN (%s)
230
+ AND posts.post_type IN (%s)";
231
+ $q = sprintf(
232
+ $q,
233
+ "'" . implode("', '", $escaped_post_statuses) . "'",
234
+ "'" . implode("', '", $escaped_post_types) . "'"
235
+ );
236
+ $wpdb->query( $q );
237
+ $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
238
+ } else {
239
+ //Delete synch records corresponding to posts that no longer exist.
240
+ $blclog->log('...... Deleting synch records for removed posts');
241
+ $start = microtime(true);
242
+ $q = "DELETE synch.*
243
+ FROM
244
+ {$wpdb->prefix}blc_synch AS synch LEFT JOIN {$wpdb->posts} AS posts
245
+ ON posts.ID = synch.container_id
246
+ WHERE
247
+ synch.container_type IN (%s) AND posts.ID IS NULL";
248
+ $q = sprintf(
249
+ $q,
250
+ "'" . implode("', '", $escaped_post_types) . "'"
251
+ );
252
+ $wpdb->query( $q );
253
+ $elapsed = microtime(true) - $start;
254
+ $blclog->debug($q);
255
+ $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
256
+
257
+ //Delete records where the post status is not one of the enabled statuses.
258
+ $blclog->log('...... Deleting synch records for posts that have a disallowed status');
259
+ $start = microtime(true);
260
+ $q = "DELETE synch.*
261
+ FROM
262
+ {$wpdb->prefix}blc_synch AS synch
263
+ LEFT JOIN {$wpdb->posts} AS posts
264
+ ON (synch.container_id = posts.ID and synch.container_type = posts.post_type)
265
+ WHERE
266
+ posts.post_status NOT IN (%s)";
267
+ $q = sprintf(
268
+ $q,
269
+ "'" . implode("', '", $escaped_post_statuses) . "'"
270
+ );
271
+ $wpdb->query( $q );
272
+ $elapsed = microtime(true) - $start;
273
+ $blclog->debug($q);
274
+ $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
275
+
276
+ //Remove the 'synched' flag from all posts that have been updated
277
+ //since the last time they were parsed/synchronized.
278
+ $blclog->log('...... Marking changed posts as unsynched');
279
+ $start = microtime(true);
280
+ $q = "UPDATE
281
+ {$wpdb->prefix}blc_synch AS synch
282
+ JOIN {$wpdb->posts} AS posts ON (synch.container_id = posts.ID and synch.container_type=posts.post_type)
283
+ SET
284
+ synched = 0
285
+ WHERE
286
+ synch.last_synch < posts.post_modified";
287
+ $wpdb->query( $q );
288
+ $elapsed = microtime(true) - $start;
289
+ $blclog->debug($q);
290
+ $blclog->log(sprintf('...... %d rows updated in %.3f seconds', $wpdb->rows_affected, $elapsed));
291
+
292
+ //Create synch. records for posts that don't have them.
293
+ $blclog->log('...... Creating synch records for new posts');
294
+ $start = microtime(true);
295
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
296
+ SELECT posts.id, posts.post_type, 0
297
+ FROM
298
+ {$wpdb->posts} AS posts LEFT JOIN {$wpdb->prefix}blc_synch AS synch
299
+ ON (synch.container_id = posts.ID and synch.container_type=posts.post_type)
300
+ WHERE
301
+ posts.post_status IN (%s)
302
+ AND posts.post_type IN (%s)
303
+ AND synch.container_id IS NULL";
304
+ $q = sprintf(
305
+ $q,
306
+ "'" . implode("', '", $escaped_post_statuses) . "'",
307
+ "'" . implode("', '", $escaped_post_types) . "'"
308
+ );
309
+ $wpdb->query($q);
310
+ $elapsed = microtime(true) - $start;
311
+ $blclog->debug($q);
312
+ $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, $elapsed));
313
+ }
314
+
315
+ $this->resynch_already_done = true;
316
+ }
317
+
318
+ /**
319
+ * Hook for the 'the_content' filter. Scans the current post and adds the 'broken_link'
320
+ * CSS class to all links that are known to be broken. Currently works only on standard
321
+ * HTML links (i.e. the '<a href=...' kind).
322
+ *
323
+ * @param string $content Post content
324
+ * @return string Modified post content.
325
+ */
326
+ function hook_the_content($content){
327
+ global $post, $wpdb; /** @var wpdb $wpdb */
328
+ if ( empty($post) || !in_array($post->post_type, $this->enabled_post_types)) {
329
+ return $content;
330
+ }
331
+
332
+ //Retrieve info about all occurrences of broken links in the current post
333
+ $q = "
334
+ SELECT instances.raw_url
335
+ FROM {$wpdb->prefix}blc_instances AS instances JOIN {$wpdb->prefix}blc_links AS links
336
+ ON instances.link_id = links.link_id
337
+ WHERE
338
+ instances.container_type = %s
339
+ AND instances.container_id = %d
340
+ AND links.broken = 1
341
+ AND parser_type = 'link'
342
+ ";
343
+ $q = $wpdb->prepare($q, $post->post_type, $post->ID);
344
+ $links = $wpdb->get_results($q, ARRAY_A);
345
+
346
+ //Return the content unmodified if there are no broken links in this post.
347
+ if ( empty($links) || !is_array($links) ){
348
+ return $content;
349
+ }
350
+
351
+ //Put the broken link URLs in an array
352
+ $broken_link_urls = array();
353
+ foreach($links as $link){
354
+ $broken_link_urls[] = $link['raw_url'];
355
+ }
356
+
357
+ //Iterate over all HTML links and modify the broken ones
358
+ if ( $parser = blcParserHelper::get_parser('link') ){
359
+ $content = $parser->multi_edit($content, array(&$this, 'highlight_broken_link'), $broken_link_urls);
360
+ }
361
+
362
+ return $content;
363
+ }
364
+
365
+ /**
366
+ * Analyse a link and add 'broken_link' CSS class if the link is broken.
367
+ *
368
+ * @see blcHtmlLink::multi_edit()
369
+ *
370
+ * @param array $link Associative array of link data.
371
+ * @param array $broken_link_urls List of broken link URLs present in the current post.
372
+ * @return array|string The modified link
373
+ */
374
+ function highlight_broken_link($link, $broken_link_urls){
375
+ if ( !in_array($link['href'], $broken_link_urls) ){
376
+ //Link not broken = return the original link tag
377
+ return $link['#raw'];
378
+ }
379
+
380
+ //Add 'broken_link' to the 'class' attribute (unless already present).
381
+ if ( $this->plugin_conf->options['mark_broken_links'] ){
382
+ if ( isset($link['class']) ){
383
+ $classes = explode(' ', $link['class']);
384
+ if ( !in_array('broken_link', $classes) ){
385
+ $classes[] = 'broken_link';
386
+ $link['class'] = implode(' ', $classes);
387
+ }
388
+ } else {
389
+ $link['class'] = 'broken_link';
390
+ }
391
+ }
392
+
393
+ //Nofollow the link (unless it's already nofollow'ed)
394
+ if ( $this->plugin_conf->options['nofollow_broken_links'] ){
395
+ if ( isset($link['rel']) ){
396
+ $relations = explode(' ', $link['rel']);
397
+ if ( !in_array('nofollow', $relations) ){
398
+ $relations[] = 'nofollow';
399
+ $link['rel'] = implode(' ', $relations);
400
+ }
401
+ } else {
402
+ $link['rel'] = 'nofollow';
403
+ }
404
+ }
405
+
406
+ return $link;
407
+ }
408
+
409
+ /**
410
+ * A hook for the 'wp_head' action. Outputs the user-defined broken link CSS.
411
+ *
412
+ * @return void
413
+ */
414
+ function hook_wp_head(){
415
+ echo '<style type="text/css">',$this->plugin_conf->options['broken_link_css'],'</style>';
416
+ }
417
+ }
418
+
419
+ //Start up the post overlord
420
+ blcPostTypeOverlord::getInstance();
421
+
422
+
423
+ /**
424
+ * Universal container item class used for all post types.
425
+ *
426
+ * @package Broken Link Checker
427
+ * @author Janis Elsts
428
+ * @access public
429
+ */
430
+ class blcAnyPostContainer extends blcContainer {
431
+ var $default_field = 'post_content';
432
+
433
+ /**
434
+ * Get action links for this post.
435
+ *
436
+ * @param string $container_field Ignored.
437
+ * @return array of action link HTML.
438
+ */
439
+ function ui_get_action_links($container_field = ''){
440
+ $actions = array();
441
+
442
+ //Fetch the post (it should be cached already)
443
+ $post = $this->get_wrapped_object();
444
+ if ( !$post ){
445
+ return $actions;
446
+ }
447
+
448
+ $post_type_object = get_post_type_object($post->post_type);
449
+
450
+ //Each post type can have its own cap requirements
451
+ if ( current_user_can( $post_type_object->cap->edit_post, $this->container_id ) ){
452
+ $actions['edit'] = sprintf(
453
+ '<span class="edit"><a href="%s" title="%s">%s</a>',
454
+ $this->get_edit_url(),
455
+ $post_type_object->labels->edit_item,
456
+ __('Edit')
457
+ );
458
+
459
+ //Trash/Delete link
460
+ if ( current_user_can( $post_type_object->cap->delete_post, $this->container_id ) ){
461
+ if ( $this->can_be_trashed() ) {
462
+ $actions['trash'] = sprintf(
463
+ "<span class='trash'><a class='submitdelete' title='%s' href='%s'>%s</a>",
464
+ esc_attr(__('Move this item to the Trash')),
465
+ esc_attr(get_delete_post_link($this->container_id, '', false)),
466
+ __('Trash')
467
+ );
468
+ } else {
469
+ $actions['delete'] = sprintf(
470
+ "<span><a class='submitdelete' title='%s' href='%s'>%s</a>",
471
+ esc_attr(__('Delete this item permanently')),
472
+ esc_attr(get_delete_post_link($this->container_id, '', true)),
473
+ __('Delete')
474
+ );
475
+ }
476
+ }
477
+ }
478
+
479
+ //View/Preview link
480
+ $title = get_the_title($this->container_id);
481
+ if ( in_array($post->post_status, array('pending', 'draft')) ) {
482
+ if ( current_user_can($post_type_object->cap->edit_post, $this->container_id) ){
483
+ $actions['view'] = sprintf(
484
+ '<span class="view"><a href="%s" title="%s" rel="permalink">%s</a>',
485
+ esc_url( add_query_arg( 'preview', 'true', get_permalink($this->container_id) ) ),
486
+ esc_attr(sprintf(__('Preview &#8220;%s&#8221;'), $title)),
487
+ __('Preview')
488
+ );
489
+ }
490
+ } elseif ( 'trash' != $post->post_status ) {
491
+ $actions['view'] = sprintf(
492
+ '<span class="view"><a href="%s" title="%s" rel="permalink">%s</a>',
493
+ esc_url( get_permalink($this->container_id) ),
494
+ esc_attr(sprintf(__('View &#8220;%s&#8221;'), $title)),
495
+ __('View')
496
+ );
497
+ }
498
+
499
+ return $actions;
500
+ }
501
+
502
+ /**
503
+ * Get the HTML for displaying the post title in the "Source" column.
504
+ *
505
+ * @param string $container_field Ignored.
506
+ * @param string $context How to filter the output. Optional, defaults to 'display'.
507
+ * @return string HTML
508
+ */
509
+ function ui_get_source($container_field = '', $context = 'display'){
510
+ $source = '<a class="row-title" href="%s" title="%s">%s</a>';
511
+ $source = sprintf(
512
+ $source,
513
+ $this->get_edit_url(),
514
+ esc_attr(__('Edit this item')),
515
+ get_the_title($this->container_id)
516
+ );
517
+
518
+ return $source;
519
+ }
520
+
521
+ /**
522
+ * Get edit URL for this container. Returns the URL of the Dashboard page where the item
523
+ * associated with this container can be edited.
524
+ *
525
+ * @access protected
526
+ *
527
+ * @return string
528
+ */
529
+ function get_edit_url(){
530
+ /*
531
+ The below is a near-exact copy of the get_post_edit_link() function.
532
+ Unfortunately we can't just call that function because it has a hardcoded
533
+ caps-check which fails when called from the email notification script
534
+ executed by Cron.
535
+ */
536
+
537
+ if ( !$post = $this->get_wrapped_object() ){
538
+ return '';
539
+ }
540
+
541
+ $context = 'display';
542
+ $action = '&amp;action=edit';
543
+
544
+ $post_type_object = get_post_type_object( $post->post_type );
545
+ if ( !$post_type_object ){
546
+ return '';
547
+ }
548
+
549
+ return apply_filters( 'get_edit_post_link', admin_url( sprintf($post_type_object->_edit_link . $action, $post->ID) ), $post->ID, $context );
550
+ }
551
+
552
+ /**
553
+ * Retrieve the post associated with this container.
554
+ *
555
+ * @access protected
556
+ *
557
+ * @param bool $ensure_consistency Set this to true to ignore the cached $wrapped_object value and retrieve an up-to-date copy of the wrapped object from the DB (or WP's internal cache).
558
+ * @return object Post data.
559
+ */
560
+ function get_wrapped_object($ensure_consistency = false){
561
+ if( $ensure_consistency || is_null($this->wrapped_object) ){
562
+ $this->wrapped_object = get_post($this->container_id);
563
+ }
564
+ return $this->wrapped_object;
565
+ }
566
+
567
+ /**
568
+ * Update the post associated with this container.
569
+ *
570
+ * @access protected
571
+ *
572
+ * @return bool|WP_Error True on success, an error if something went wrong.
573
+ */
574
+ function update_wrapped_object(){
575
+ if ( is_null($this->wrapped_object) ){
576
+ return new WP_Error(
577
+ 'no_wrapped_object',
578
+ __('Nothing to update', 'broken-link-checker')
579
+ );
580
+ }
581
+
582
+ $post_id = wp_update_post($this->wrapped_object, true);
583
+ if ( is_wp_error($post_id) ) {
584
+ return $post_id;
585
+ } else if ( $post_id == 0 ){
586
+ return new WP_Error(
587
+ 'update_failed',
588
+ sprintf(__('Updating post %d failed', 'broken-link-checker'), $this->container_id)
589
+ );
590
+ } else {
591
+ return true;
592
+ }
593
+ }
594
+
595
+ /**
596
+ * Get the base URL of the container. For posts, the post permalink is used
597
+ * as the base URL when normalizing relative links.
598
+ *
599
+ * @return string
600
+ */
601
+ function base_url(){
602
+ return get_permalink($this->container_id);
603
+ }
604
+
605
+ /**
606
+ * Delete or trash the post corresponding to this container.
607
+ * Will always move to trash instead of deleting if trash is enabled.
608
+ *
609
+ * @return bool|WP_error
610
+ */
611
+ function delete_wrapped_object(){
612
+ //Note that we don't need to delete the synch record and instances here -
613
+ //wp_delete_post()/wp_trash_post() will run the post_delete/trash hook,
614
+ //which will be caught by blcPostContainerManager, which will in turn
615
+ //delete anything that needs to be deleted.
616
+ if ( EMPTY_TRASH_DAYS ){
617
+ return $this->trash_wrapped_object();
618
+ } else {
619
+ if ( wp_delete_post($this->container_id, true) ){
620
+ return true;
621
+ } else {
622
+ return new WP_Error(
623
+ 'delete_failed',
624
+ sprintf(
625
+ __('Failed to delete post "%s" (%d)', 'broken-link-checker'),
626
+ get_the_title($this->container_id),
627
+ $this->container_id
628
+ )
629
+ );
630
+ }
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Move the post corresponding to this container to the Trash.
636
+ *
637
+ * @return bool|WP_Error
638
+ */
639
+ function trash_wrapped_object(){
640
+ if ( !EMPTY_TRASH_DAYS ){
641
+ return new WP_Error(
642
+ 'trash_disabled',
643
+ sprintf(
644
+ __('Can\'t move post "%s" (%d) to the trash because the trash feature is disabled', 'broken-link-checker'),
645
+ get_the_title($this->container_id),
646
+ $this->container_id
647
+ )
648
+ );
649
+ }
650
+
651
+ $post = get_post($this->container_id);
652
+ if ( $post->post_status == 'trash' ){
653
+ //Prevent conflicts between post and custom field containers trying to trash the same post.
654
+ //BUG: Post and custom field containers shouldn't wrap the same object
655
+ return true;
656
+ }
657
+
658
+ if ( wp_trash_post($this->container_id) ){
659
+ return true;
660
+ } else {
661
+ return new WP_Error(
662
+ 'trash_failed',
663
+ sprintf(
664
+ __('Failed to move post "%s" (%d) to the trash', 'broken-link-checker'),
665
+ get_the_title($this->container_id),
666
+ $this->container_id
667
+ )
668
+ );
669
+ }
670
+ }
671
+
672
+ /**
673
+ * Check if the current user can delete/trash this post.
674
+ *
675
+ * @return bool
676
+ */
677
+ function current_user_can_delete(){
678
+ $post = $this->get_wrapped_object();
679
+ $post_type_object = get_post_type_object($post->post_type);
680
+ return current_user_can( $post_type_object->cap->delete_post, $this->container_id );
681
+ }
682
+
683
+ function can_be_trashed(){
684
+ return defined('EMPTY_TRASH_DAYS') && EMPTY_TRASH_DAYS;
685
+ }
686
+ }
687
+
688
+
689
+
690
+ /**
691
+ * Universal manager usable for most post types.
692
+ *
693
+ * @package Broken Link Checker
694
+ * @access public
695
+ */
696
+ class blcAnyPostContainerManager extends blcContainerManager {
697
+ var $container_class_name = 'blcAnyPostContainer';
698
+ var $fields = array('post_content' => 'html');
699
+
700
+ function init(){
701
+ parent::init();
702
+
703
+ //Notify the overlord that the post/container type that this instance is
704
+ //responsible for is enabled.
705
+ $overlord = blcPostTypeOverlord::getInstance();
706
+ $overlord->post_type_enabled($this->container_type);
707
+ }
708
+
709
+ /**
710
+ * Instantiate multiple containers of the container type managed by this class.
711
+ *
712
+ * @param array $containers Array of assoc. arrays containing container data.
713
+ * @param string $purpose An optional code indicating how the retrieved containers will be used.
714
+ * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
715
+ *
716
+ * @return array of blcPostContainer indexed by "container_type|container_id"
717
+ */
718
+ function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
719
+ $containers = $this->make_containers($containers);
720
+
721
+ //Preload post data if it is likely to be useful later
722
+ $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_PARSING));
723
+ if ( $preload ){
724
+ $post_ids = array();
725
+ foreach($containers as $container){
726
+ $post_ids[] = $container->container_id;
727
+ }
728
+
729
+ $args = array('include' => implode(',', $post_ids));
730
+ $posts = get_posts($args);
731
+
732
+ foreach($posts as $post){
733
+ $key = $this->container_type . '|' . $post->ID;
734
+ if ( isset($containers[$key]) ){
735
+ $containers[$key]->wrapped_object = $post;
736
+ }
737
+ }
738
+ }
739
+
740
+ return $containers;
741
+ }
742
+
743
+ /**
744
+ * Create or update synchronization records for all posts.
745
+ *
746
+ * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
747
+ * @return void
748
+ */
749
+ function resynch($forced = false){
750
+ $overlord = blcPostTypeOverlord::getInstance();
751
+ $overlord->resynch($this->container_type, $forced);
752
+ }
753
+
754
+ /**
755
+ * Get the message to display after $n posts have been deleted.
756
+ *
757
+ * @param int $n Number of deleted posts.
758
+ * @return string A delete confirmation message, e.g. "5 posts were moved deleted"
759
+ */
760
+ function ui_bulk_delete_message($n){
761
+ //Since the "Trash" feature has been introduced, calling wp_delete_post
762
+ //doesn't actually delete the post (unless you set force_delete to True),
763
+ //just moves it to the trash. So we pick the message accordingly.
764
+ //(If possible, BLC *always* moves to trash instead of deleting permanently.)
765
+ if ( function_exists('wp_trash_post') && EMPTY_TRASH_DAYS ){
766
+ return blcAnyPostContainerManager::ui_bulk_trash_message($n);
767
+ } else {
768
+ $post_type_object = get_post_type_object($this->container_type);
769
+ $type_name = '';
770
+
771
+ if ( $this->container_type == 'post' || is_null($post_type_object) ){
772
+ $delete_msg = _n("%d post deleted.", "%d posts deleted.", $n, 'broken-link-checker');
773
+ } elseif ( $this->container_type == 'page' ){
774
+ $delete_msg = _n("%d page deleted.", "%d pages deleted.", $n, 'broken-link-checker');
775
+ } else {
776
+ $delete_msg = _n('%d "%s" deleted.', '%d "%s" deleted.', $n, 'broken-link-checker');
777
+ $type_name = ($n == 1 ? $post_type_object->labels->singular_name : $post_type_object->labels->name);
778
+ }
779
+ return sprintf($delete_msg, $n, $type_name);
780
+ }
781
+ }
782
+
783
+
784
+ /**
785
+ * Get the message to display after $n posts have been trashed.
786
+ *
787
+ * @param int $n Number of deleted posts.
788
+ * @return string A confirmation message, e.g. "5 posts were moved to trash"
789
+ */
790
+ function ui_bulk_trash_message($n){
791
+ $post_type_object = get_post_type_object($this->container_type);
792
+ $type_name = '';
793
+
794
+ if ( $this->container_type == 'post' || is_null($post_type_object) ){
795
+ $delete_msg = _n("%d post moved to the Trash.", "%d posts moved to the Trash.", $n, 'broken-link-checker');
796
+ } elseif ( $this->container_type == 'page' ){
797
+ $delete_msg = _n("%d page moved to the Trash.", "%d pages moved to the Trash.", $n, 'broken-link-checker');
798
+ } else {
799
+ $delete_msg = _n('%d "%s" moved to the Trash.', '%d "%s" moved to the Trash.', $n, 'broken-link-checker');
800
+ $type_name = ($n == 1 ? $post_type_object->labels->singular_name : $post_type_object->labels->name);
801
+ }
802
+ return sprintf($delete_msg, $n, $type_name);
803
+ }
804
+ }
includes/checkers.php CHANGED
@@ -1,120 +1,120 @@
1
- <?php
2
-
3
- /**
4
- * Base class for link checking algorithms.
5
- *
6
- * All link checkering algorithms should extend this class.
7
- *
8
- * @package Broken Link Checker
9
- * @access public
10
- */
11
- class blcChecker extends blcModule {
12
-
13
- /**
14
- * Priority determines the order in which the plugin will try all registered checkers
15
- * when looking for one that can check a particular URL. Registered checkers will be
16
- * tried in order, from highest to lowest priority, and the first one that returns
17
- * true when its can_check() method is called will be used.
18
- *
19
- * Checker implementations should set their priority depending on how specific they are
20
- * in choosing the URLs that they check.
21
- *
22
- * -10 .. 10 : checks all URLs that have a certain protocol, e.g. all HTTP URLs.
23
- * 11 .. 100 : checks only URLs from a restricted number of domains, e.g. video site URLs.
24
- * 100+ : checks only certain URLs from a certain domain, e.g. YouTube video links.
25
- *
26
- */
27
- var $priority = -100;
28
-
29
- /**
30
- * Check if this checker knows how to check a particular URL.
31
- *
32
- * @param string $url
33
- * @param array|bool $parsed_url The result of parsing $url with parse_url(). See PHP docs for details.
34
- * @return bool
35
- */
36
- function can_check($url, $parsed_url){
37
- return false;
38
- }
39
-
40
- /**
41
- * Check an URL.
42
- *
43
- * This method returns an associative array containing results of
44
- * the check. The following array keys are recognized by the plugin and
45
- * their values will be stored in the link's DB record :
46
- * 'broken' (bool) - True if the URL points to a missing/broken page. Required.
47
- * 'http_code' (int) - HTTP code returned when requesting the URL. Defaults to 0.
48
- * 'redirect_count' (int) - The number of redirects. Defaults to 0.
49
- * 'final_url' (string) - The redirected-to URL. Assumed to be equal to the checked URL by default.
50
- * 'request_duration' (float) - How long it took for the server to respond. Defaults to 0 seconds.
51
- * 'timeout' (bool) - True if checking the URL resulted in a timeout. Defaults to false.
52
- * 'may_recheck' (bool) - Allow the plugin to re-check the URL after 'recheck_threshold' seconds (see broken-link-checker.php).
53
- * 'log' (string) - Free-form log of the performed check. It will be displayed in the "Details" section of the checked link.
54
- * 'result_hash' (string) - A free-form hash or code uniquely identifying the detected link status. See sub-classes for examples. Max 200 characters.
55
- *
56
- * @see blcLink:check()
57
- *
58
- * @param string $url
59
- * @return array
60
- */
61
- function check($url){
62
- trigger_error('Function blcChecker::check() must be over-ridden in a subclass', E_USER_ERROR);
63
- }
64
- }
65
-
66
- class blcCheckerHelper {
67
-
68
- /**
69
- * Get a reference to a specific checker.
70
- *
71
- * @uses blcModuleManager::get_module()
72
- *
73
- * @param string $checker_id
74
- * @return blcChecker
75
- */
76
- static function get_checker($checker_id){
77
- $manager = blcModuleManager::getInstance();
78
- return $manager->get_module($checker_id, true, 'checker');
79
- }
80
-
81
- /**
82
- * Get a checker object that can check the specified URL.
83
- *
84
- * @param string $url
85
- * @return blcChecker|null
86
- */
87
- static function get_checker_for($url){
88
- $parsed = @parse_url($url);
89
-
90
- $manager = blcModuleManager::getInstance();
91
- $active_checkers = $manager->get_active_by_category('checker');
92
-
93
- foreach($active_checkers as $module_id => $module_data){
94
- //Try the URL pattern in the header first. If it doesn't match,
95
- //we can avoid loading the module altogether.
96
- if ( !empty($module_data['ModuleCheckerUrlPattern']) ){
97
- if ( !preg_match($module_data['ModuleCheckerUrlPattern'], $url) ){
98
- continue;
99
- }
100
- }
101
-
102
- $checker = $manager->get_module($module_id);
103
-
104
- if ( !$checker ){
105
- continue;
106
- }
107
-
108
- //The can_check() method can perform more sophisticated filtering,
109
- //or just return true if the checker thinks matching the URL regex
110
- //is sufficient.
111
- if ( $checker->can_check($url, $parsed) ){
112
- return $checker;
113
- }
114
- }
115
-
116
- $checker = null;
117
- return $checker;
118
- }
119
- }
120
-
1
+ <?php
2
+
3
+ /**
4
+ * Base class for link checking algorithms.
5
+ *
6
+ * All link checkering algorithms should extend this class.
7
+ *
8
+ * @package Broken Link Checker
9
+ * @access public
10
+ */
11
+ class blcChecker extends blcModule {
12
+
13
+ /**
14
+ * Priority determines the order in which the plugin will try all registered checkers
15
+ * when looking for one that can check a particular URL. Registered checkers will be
16
+ * tried in order, from highest to lowest priority, and the first one that returns
17
+ * true when its can_check() method is called will be used.
18
+ *
19
+ * Checker implementations should set their priority depending on how specific they are
20
+ * in choosing the URLs that they check.
21
+ *
22
+ * -10 .. 10 : checks all URLs that have a certain protocol, e.g. all HTTP URLs.
23
+ * 11 .. 100 : checks only URLs from a restricted number of domains, e.g. video site URLs.
24
+ * 100+ : checks only certain URLs from a certain domain, e.g. YouTube video links.
25
+ *
26
+ */
27
+ var $priority = -100;
28
+
29
+ /**
30
+ * Check if this checker knows how to check a particular URL.
31
+ *
32
+ * @param string $url
33
+ * @param array|bool $parsed_url The result of parsing $url with parse_url(). See PHP docs for details.
34
+ * @return bool
35
+ */
36
+ function can_check($url, $parsed_url){
37
+ return false;
38
+ }
39
+
40
+ /**
41
+ * Check an URL.
42
+ *
43
+ * This method returns an associative array containing results of
44
+ * the check. The following array keys are recognized by the plugin and
45
+ * their values will be stored in the link's DB record :
46
+ * 'broken' (bool) - True if the URL points to a missing/broken page. Required.
47
+ * 'http_code' (int) - HTTP code returned when requesting the URL. Defaults to 0.
48
+ * 'redirect_count' (int) - The number of redirects. Defaults to 0.
49
+ * 'final_url' (string) - The redirected-to URL. Assumed to be equal to the checked URL by default.
50
+ * 'request_duration' (float) - How long it took for the server to respond. Defaults to 0 seconds.
51
+ * 'timeout' (bool) - True if checking the URL resulted in a timeout. Defaults to false.
52
+ * 'may_recheck' (bool) - Allow the plugin to re-check the URL after 'recheck_threshold' seconds (see broken-link-checker.php).
53
+ * 'log' (string) - Free-form log of the performed check. It will be displayed in the "Details" section of the checked link.
54
+ * 'result_hash' (string) - A free-form hash or code uniquely identifying the detected link status. See sub-classes for examples. Max 200 characters.
55
+ *
56
+ * @see blcLink:check()
57
+ *
58
+ * @param string $url
59
+ * @return array
60
+ */
61
+ function check($url){
62
+ trigger_error('Function blcChecker::check() must be over-ridden in a subclass', E_USER_ERROR);
63
+ }
64
+ }
65
+
66
+ class blcCheckerHelper {
67
+
68
+ /**
69
+ * Get a reference to a specific checker.
70
+ *
71
+ * @uses blcModuleManager::get_module()
72
+ *
73
+ * @param string $checker_id
74
+ * @return blcChecker
75
+ */
76
+ static function get_checker($checker_id){
77
+ $manager = blcModuleManager::getInstance();
78
+ return $manager->get_module($checker_id, true, 'checker');
79
+ }
80
+
81
+ /**
82
+ * Get a checker object that can check the specified URL.
83
+ *
84
+ * @param string $url
85
+ * @return blcChecker|null
86
+ */
87
+ static function get_checker_for($url){
88
+ $parsed = @parse_url($url);
89
+
90
+ $manager = blcModuleManager::getInstance();
91
+ $active_checkers = $manager->get_active_by_category('checker');
92
+
93
+ foreach($active_checkers as $module_id => $module_data){
94
+ //Try the URL pattern in the header first. If it doesn't match,
95
+ //we can avoid loading the module altogether.
96
+ if ( !empty($module_data['ModuleCheckerUrlPattern']) ){
97
+ if ( !preg_match($module_data['ModuleCheckerUrlPattern'], $url) ){
98
+ continue;
99
+ }
100
+ }
101
+
102
+ $checker = $manager->get_module($module_id);
103
+
104
+ if ( !$checker ){
105
+ continue;
106
+ }
107
+
108
+ //The can_check() method can perform more sophisticated filtering,
109
+ //or just return true if the checker thinks matching the URL regex
110
+ //is sufficient.
111
+ if ( $checker->can_check($url, $parsed) ){
112
+ return $checker;
113
+ }
114
+ }
115
+
116
+ $checker = null;
117
+ return $checker;
118
+ }
119
+ }
120
+
includes/config-manager.php CHANGED
@@ -1,127 +1,127 @@
1
- <?php
2
-
3
- /**
4
- * @author W-Shadow
5
- * @copyright 2009
6
- */
7
-
8
- if ( !class_exists('blcConfigurationManager') ){
9
-
10
- class blcConfigurationManager {
11
-
12
- var $option_name;
13
-
14
- var $options;
15
- var $defaults;
16
- var $loaded_values;
17
-
18
- /**
19
- * @var bool Whether options have been successfully loaded from the database.
20
- */
21
- public $db_option_loaded = false;
22
-
23
- function __construct( $option_name = '', $default_settings = null ){
24
- $this->option_name = $option_name;
25
-
26
- if ( is_array($default_settings) ){
27
- $this->defaults = $default_settings;
28
- } else {
29
- $this->defaults = array();
30
- }
31
- $this->loaded_values = array();
32
-
33
- $this->options = $this->defaults;
34
-
35
- if ( !empty( $this->option_name ) ) {
36
- $this->load_options();
37
- }
38
- }
39
-
40
- function set_defaults( $default_settings = null ){
41
- if ( is_array($default_settings) ){
42
- $this->defaults = array();
43
- } else {
44
- $this->defaults = $default_settings;
45
- }
46
- $this->options = array_merge($this->defaults, $this->loaded_values);
47
- }
48
-
49
- /**
50
- * blcOptionManager::load_options()
51
- * Load plugin options from the database. The current $options values are not affected
52
- * if this function fails.
53
- *
54
- * @param string $option_name
55
- * @return bool True if options were loaded, false otherwise.
56
- */
57
- function load_options( $option_name = '' ){
58
- $this->db_option_loaded = false;
59
-
60
- if ( !empty($option_name) ){
61
- $this->option_name = $option_name;
62
- }
63
-
64
- if ( empty($this->option_name) ) return false;
65
-
66
- $new_options = get_option($this->option_name);
67
-
68
- //Decode JSON (if applicable).
69
- if ( is_string($new_options) && !empty($new_options) ) {
70
- $new_options = json_decode($new_options, true);
71
- }
72
-
73
- if( !is_array( $new_options ) ){
74
- return false;
75
- } else {
76
- $this->loaded_values = $new_options;
77
- $this->options = array_merge( $this->defaults, $this->loaded_values );
78
- $this->db_option_loaded = true;
79
- return true;
80
- }
81
- }
82
-
83
- /**
84
- * blcOptionManager::save_options()
85
- * Save plugin options to the database.
86
- *
87
- * @param string $option_name (Optional) Save the options under this name
88
- * @return bool True if settings were saved, false if settings haven't been changed or if there was an error.
89
- */
90
- function save_options( $option_name = '' ){
91
- if ( !empty($option_name) ){
92
- $this->option_name = $option_name;
93
- }
94
-
95
- if ( empty($this->option_name) ) return false;
96
-
97
- return update_option( $this->option_name, json_encode($this->options) );
98
- }
99
-
100
- /**
101
- * Retrieve a specific setting.
102
- *
103
- * @param string $key
104
- * @param mixed $default
105
- * @return mixed
106
- */
107
- function get($key, $default = null){
108
- if ( array_key_exists($key, $this->options) ){
109
- return $this->options[$key];
110
- } else {
111
- return $default;
112
- }
113
- }
114
-
115
- /**
116
- * Update or add a setting.
117
- *
118
- * @param string $key
119
- * @param mixed $value
120
- * @return void
121
- */
122
- function set($key, $value){
123
- $this->options[$key] = $value;
124
- }
125
- }
126
-
127
- }
1
+ <?php
2
+
3
+ /**
4
+ * @author W-Shadow
5
+ * @copyright 2009
6
+ */
7
+
8
+ if ( !class_exists('blcConfigurationManager') ){
9
+
10
+ class blcConfigurationManager {
11
+
12
+ var $option_name;
13
+
14
+ var $options;
15
+ var $defaults;
16
+ var $loaded_values;
17
+
18
+ /**
19
+ * @var bool Whether options have been successfully loaded from the database.
20
+ */
21
+ public $db_option_loaded = false;
22
+
23
+ function __construct( $option_name = '', $default_settings = null ){
24
+ $this->option_name = $option_name;
25
+
26
+ if ( is_array($default_settings) ){
27
+ $this->defaults = $default_settings;
28
+ } else {
29
+ $this->defaults = array();
30
+ }
31
+ $this->loaded_values = array();
32
+
33
+ $this->options = $this->defaults;
34
+
35
+ if ( !empty( $this->option_name ) ) {
36
+ $this->load_options();
37
+ }
38
+ }
39
+
40
+ function set_defaults( $default_settings = null ){
41
+ if ( is_array($default_settings) ){
42
+ $this->defaults = array();
43
+ } else {
44
+ $this->defaults = $default_settings;
45
+ }
46
+ $this->options = array_merge($this->defaults, $this->loaded_values);
47
+ }
48
+
49
+ /**
50
+ * blcOptionManager::load_options()
51
+ * Load plugin options from the database. The current $options values are not affected
52
+ * if this function fails.
53
+ *
54
+ * @param string $option_name
55
+ * @return bool True if options were loaded, false otherwise.
56
+ */
57
+ function load_options( $option_name = '' ){
58
+ $this->db_option_loaded = false;
59
+
60
+ if ( !empty($option_name) ){
61
+ $this->option_name = $option_name;
62
+ }
63
+
64
+ if ( empty($this->option_name) ) return false;
65
+
66
+ $new_options = get_option($this->option_name);
67
+
68
+ //Decode JSON (if applicable).
69
+ if ( is_string($new_options) && !empty($new_options) ) {
70
+ $new_options = json_decode($new_options, true);
71
+ }
72
+
73
+ if( !is_array( $new_options ) ){
74
+ return false;
75
+ } else {
76
+ $this->loaded_values = $new_options;
77
+ $this->options = array_merge( $this->defaults, $this->loaded_values );
78
+ $this->db_option_loaded = true;
79
+ return true;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * blcOptionManager::save_options()
85
+ * Save plugin options to the database.
86
+ *
87
+ * @param string $option_name (Optional) Save the options under this name
88
+ * @return bool True if settings were saved, false if settings haven't been changed or if there was an error.
89
+ */
90
+ function save_options( $option_name = '' ){
91
+ if ( !empty($option_name) ){
92
+ $this->option_name = $option_name;
93
+ }
94
+
95
+ if ( empty($this->option_name) ) return false;
96
+
97
+ return update_option( $this->option_name, json_encode($this->options) );
98
+ }
99
+
100
+ /**
101
+ * Retrieve a specific setting.
102
+ *
103
+ * @param string $key
104
+ * @param mixed $default
105
+ * @return mixed
106
+ */
107
+ function get($key, $default = null){
108
+ if ( array_key_exists($key, $this->options) ){
109
+ return $this->options[$key];
110
+ } else {
111
+ return $default;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Update or add a setting.
117
+ *
118
+ * @param string $key
119
+ * @param mixed $value
120
+ * @return void
121
+ */
122
+ function set($key, $value){
123
+ $this->options[$key] = $value;
124
+ }
125
+ }
126
+
127
+ }
includes/containers.php CHANGED
@@ -1,911 +1,911 @@
1
- <?php
2
-
3
- /**
4
- * The base class for link container managers.
5
- *
6
- * Sub-classes should override at least the get_containers() and resynch() methods.
7
- *
8
- * @package Broken Link Checker
9
- * @access public
10
- */
11
- class blcContainerManager extends blcModule {
12
-
13
- var $container_type = '';
14
- var $fields = array();
15
- var $container_class_name = 'blcContainer';
16
-
17
- /**
18
- * Do whatever setup necessary that wasn't already done in the constructor.
19
- *
20
- * This method was added so that sub-classes would have something "safe" to
21
- * over-ride without having to deal with PHP4/5 constructors.
22
- *
23
- * @return void
24
- */
25
- function init(){
26
- parent::init();
27
- $this->container_type = $this->module_id;
28
- //Sub-classes might also use it to set up hooks, etc.
29
- }
30
-
31
- /**
32
- * Instantiate a link container.
33
- *
34
- * @param array $container An associative array of container data.
35
- * @return blcContainer
36
- */
37
- function get_container($container){
38
- $container['fields'] = $this->get_parseable_fields();
39
- $container_obj = new $this->container_class_name($container);
40
- return $container_obj;
41
- }
42
-
43
- /**
44
- * Instantiate multiple containers of the container type managed by this class and optionally
45
- * pre-load container data used for display/parsing.
46
- *
47
- * Sub-classes should, if possible, use the $purpose argument to pre-load any extra data required for
48
- * the specified task right away, instead of making multiple DB roundtrips later. For example, if
49
- * $purpose is set to the BLC_FOR_DISPLAY constant, you might want to preload any DB data that the
50
- * container will need in blcContainer::ui_get_source().
51
- *
52
- * @see blcContainer::make_containers()
53
- * @see blcContainer::ui_get_source()
54
- * @see blcContainer::ui_get_action_links()
55
- *
56
- * @param array $containers Array of assoc. arrays containing container data.
57
- * @param string $purpose An optional code indicating how the retrieved containers will be used.
58
- * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
59
- *
60
- * @return array of blcContainer indexed by "container_type|container_id"
61
- */
62
- function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
63
- return $this->make_containers($containers);
64
- }
65
-
66
- /**
67
- * Instantiate multiple containers of the container type managed by this class
68
- *
69
- * @param array $containers Array of assoc. arrays containing container data.
70
- * @return array of blcContainer indexed by "container_type|container_id"
71
- */
72
- function make_containers($containers){
73
- $results = array();
74
- foreach($containers as $container){
75
- $key = $container['container_type'] . '|' . $container['container_id'];
76
- $results[ $key ] = $this->get_container($container);
77
- }
78
- return $results;
79
- }
80
-
81
- /**
82
- * Create or update synchronization records for all containers managed by this class.
83
- *
84
- * Must be over-ridden in subclasses.
85
- *
86
- * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
87
- * @return void
88
- */
89
- function resynch($forced = false){
90
- trigger_error('Function blcContainerManager::resynch() must be over-ridden in a sub-class', E_USER_ERROR);
91
- }
92
-
93
- /**
94
- * Resynch when activated.
95
- *
96
- * @uses blcContainerManager::resynch()
97
- *
98
- * @return void
99
- */
100
- function activated(){
101
- $this->resynch();
102
- blc_got_unsynched_items();
103
- }
104
-
105
- /**
106
- * Get a list of the parseable fields and their formats common to all containers of this type.
107
- *
108
- * @return array Associative array of formats indexed by field name.
109
- */
110
- function get_parseable_fields(){
111
- return $this->fields;
112
- }
113
-
114
- /**
115
- * Get the message to display after $n containers have been deleted.
116
- *
117
- * @param int $n Number of deleted containers.
118
- * @return string A delete confirmation message, e.g. "5 posts were moved to trash"
119
- */
120
- function ui_bulk_delete_message($n){
121
- return sprintf(
122
- _n(
123
- "%d '%s' has been deleted",
124
- "%d '%s' have been deleted",
125
- $n,
126
- 'broken-link-checker'
127
- ),
128
- $n,
129
- $this->container_type
130
- );
131
- }
132
-
133
- /**
134
- * Get the message to display after $n containers have been moved to the trash.
135
- *
136
- * @param int $n Number of trashed containers.
137
- * @return string A delete confirmation message, e.g. "5 posts were moved to trash"
138
- */
139
- function ui_bulk_trash_message($n){
140
- return $this->ui_bulk_delete_message($n);
141
- }
142
- }
143
-
144
- /**
145
- * The base class for link containers. All containers should extend this class.
146
- *
147
- * @package Broken Link Checker
148
- * @access public
149
- */
150
- class blcContainer {
151
-
152
- var $fields = array();
153
- var $default_field = '';
154
-
155
- var $container_type;
156
- var $container_id = 0;
157
-
158
- var $synched = false;
159
- var $last_synch = '0000-00-00 00:00:00';
160
-
161
- var $wrapped_object = null;
162
-
163
- /**
164
- * Constructor
165
- *
166
- * @param array $data
167
- * @param object $wrapped_object
168
- * @return void
169
- */
170
- function __construct( $data = null, $wrapped_object = null ){
171
- $this->wrapped_object = $wrapped_object;
172
- if ( !empty($data) && is_array($data) ){
173
- foreach($data as $name => $value){
174
- $this->$name = $value;
175
- }
176
- }
177
- }
178
-
179
- /**
180
- * Get the value of the specified field of the object wrapped by this container.
181
- *
182
- * @access protected
183
- *
184
- * @param string $field Field name. If omitted, the value of the default field will be returned.
185
- * @return string
186
- */
187
- function get_field($field = ''){
188
- if ( empty($field) ){
189
- $field = $this->default_field;
190
- }
191
-
192
- $w = $this->get_wrapped_object();
193
- return $w->$field;
194
- }
195
-
196
- /**
197
- * Update the value of the specified field in the wrapped object.
198
- * This method will also immediately save the changed value by calling update_wrapped_object().
199
- *
200
- * @access protected
201
- *
202
- * @param string $field Field name.
203
- * @param string $new_value Set the field to this value.
204
- * @param string $old_value The previous value of the field. Optional, but can be useful for container that need the old value to distinguish between several instances of the same field (e.g. post metadata).
205
- * @return bool|WP_Error True on success, an error object if something went wrong.
206
- */
207
- function update_field($field, $new_value, $old_value = ''){
208
- $w = $this->get_wrapped_object();
209
- $w->$field = $new_value;
210
- return $this->update_wrapped_object();
211
- }
212
-
213
- /**
214
- * Retrieve the entity wrapped by this container.
215
- * The fetched object will also be cached in the $wrapped_object variable.
216
- *
217
- * @access protected
218
- *
219
- * @param bool $ensure_consistency Set this to true to ignore the cached $wrapped_object value and retrieve an up-to-date copy of the wrapped object from the DB (or WP's internal cache).
220
- * @return object The wrapped object.
221
- */
222
- function get_wrapped_object($ensure_consistency = false){
223
- trigger_error('Function blcContainer::get_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
224
- }
225
-
226
- /**
227
- * Update the entity wrapped by the container with values currently in the $wrapped_object.
228
- *
229
- * @access protected
230
- *
231
- * @return bool|WP_Error True on success, an error if something went wrong.
232
- */
233
- function update_wrapped_object(){
234
- trigger_error('Function blcContainer::update_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
235
- }
236
-
237
- /**
238
- * Parse the container for links and save the results to the DB.
239
- *
240
- * @return void
241
- */
242
- function synch(){
243
- //FB::log("Parsing {$this->container_type}[{$this->container_id}]");
244
-
245
- //Remove any existing link instance records associated with the container
246
- $this->delete_instances();
247
-
248
- //Load the wrapped object, if not done already
249
- $this->get_wrapped_object();
250
-
251
- //FB::log($this->fields, "Parseable fields :");
252
-
253
- //Iterate over all parse-able fields
254
- foreach($this->fields as $name => $format){
255
- //Get the field value
256
- $value = $this->get_field($name);
257
- if ( empty($value) ){
258
- //FB::log($name, "Skipping empty field");
259
- continue;
260
- }
261
- //FB::log($name, "Parsing field");
262
-
263
- //Get all parsers applicable to this field
264
- $parsers = blcParserHelper::get_parsers( $format, $this->container_type );
265
- //FB::log($parsers, "Applicable parsers");
266
-
267
- if ( empty($parsers) ) continue;
268
-
269
- $base_url = $this->base_url();
270
- $default_link_text = $this->default_link_text($name);
271
-
272
- //Parse the field with each parser
273
- foreach($parsers as $parser){
274
- //FB::log("Parsing $name with '{$parser->parser_type}' parser");
275
- $found_instances = $parser->parse( $value, $base_url, $default_link_text );
276
- //FB::log($found_instances, "Found instances");
277
-
278
- $transactionManager = TransactionManager::getInstance();
279
- $transactionManager->start();
280
-
281
- //Complete the link instances by adding container info, then save them to the DB.
282
- foreach($found_instances as $instance){
283
- $instance->set_container($this, $name);
284
- $instance->save();
285
- }
286
-
287
- $transactionManager->commit();
288
-
289
- }
290
- }
291
-
292
- $this->mark_as_synched();
293
- }
294
-
295
- /**
296
- * Mark the container as successfully synchronized (parsed for links).
297
- *
298
- * @return bool
299
- */
300
- function mark_as_synched(){
301
- global $wpdb; /* @var wpdb $wpdb */
302
-
303
- $this->last_synch = time();
304
-
305
- $q = "INSERT INTO {$wpdb->prefix}blc_synch( container_id, container_type, synched, last_synch)
306
- VALUES( %d, %s, %d, NOW() )
307
- ON DUPLICATE KEY UPDATE synched = VALUES(synched), last_synch = VALUES(last_synch)";
308
- $rez = $wpdb->query( $wpdb->prepare( $q, $this->container_id, $this->container_type, 1 ) );
309
-
310
- return ($rez !== false);
311
- }
312
-
313
- /**
314
- * blcContainer::mark_as_unsynched()
315
- * Mark the container as not synchronized (not parsed, or modified since the last parse).
316
- * The plugin will attempt to (re)parse the container at the earliest opportunity.
317
- *
318
- * @return bool
319
- */
320
- function mark_as_unsynched(){
321
- global $wpdb; /* @var wpdb $wpdb */
322
-
323
- $q = "INSERT INTO {$wpdb->prefix}blc_synch( container_id, container_type, synched, last_synch)
324
- VALUES( %d, %s, %d, '0000-00-00 00:00:00' )
325
- ON DUPLICATE KEY UPDATE synched = VALUES(synched)";
326
- $rez = $wpdb->query( $wpdb->prepare( $q, $this->container_id, $this->container_type, 0 ) );
327
-
328
- blc_got_unsynched_items();
329
-
330
- return ($rez !== false);
331
- }
332
-
333
- /**
334
- * Get the base URL of the container. Used to normalize relative URLs found
335
- * in the container. For example, for posts this would be the post permalink.
336
- *
337
- * @return string
338
- */
339
- function base_url(){
340
- return home_url();
341
- }
342
-
343
- /**
344
- * Get the default link text to use for links found in a specific container field.
345
- *
346
- * This is generally only meaningful for non-HTML container fields.
347
- * For example, if the container is post metadata, the default
348
- * link text might be equal to the name of the custom field.
349
- *
350
- * @param string $field
351
- * @return string
352
- */
353
- function default_link_text($field = ''){
354
- return '';
355
- }
356
-
357
-
358
-
359
- /**
360
- * Delete the DB record of this container.
361
- * Also deletes the DB records of all link instances associated with it.
362
- * Calling this method will not affect the WP entity (e.g. a post) corresponding to this container.
363
- *
364
- * @return bool
365
- */
366
- function delete(){
367
- global $wpdb; /* @var wpdb $wpdb */
368
-
369
- //Delete instances first.
370
- $rez = $this->delete_instances();
371
- if ( !$rez ){
372
- return false;
373
- }
374
-
375
- //Now delete the container record.
376
- $q = "DELETE FROM {$wpdb->prefix}blc_synch
377
- WHERE container_id = %d AND container_type = %s";
378
- $q = $wpdb->prepare($q, $this->container_id, $this->container_type);
379
-
380
- if ( $wpdb->query( $q ) === false ){
381
- return false;
382
- } else {
383
- return true;
384
- }
385
- }
386
-
387
- /**
388
- * Delete all link instance records associated with this container.
389
- * NB: Calling this method will not affect the WP entity (e.g. a post) corresponding to this container.
390
- *
391
- * @return bool
392
- */
393
- function delete_instances(){
394
- global $wpdb; /* @var wpdb $wpdb */
395
-
396
- //Remove instances associated with this container
397
- $q = "DELETE FROM {$wpdb->prefix}blc_instances
398
- WHERE container_id = %d AND container_type = %s";
399
- $q = $wpdb->prepare($q, $this->container_id, $this->container_type);
400
-
401
- if ( $wpdb->query( $q ) === false ){
402
- return false;
403
- } else {
404
- return true;
405
- }
406
- }
407
-
408
- /**
409
- * Delete or trash the WP entity corresponding to this container. Should prefer moving to trash, if possible.
410
- * Also remove the synch. record of the container and all associated instances.
411
- *
412
- * Must be over-ridden in a sub-class.
413
- *
414
- * @return bool|WP_Error
415
- */
416
- function delete_wrapped_object(){
417
- trigger_error('Function blcContainer::delete_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
418
- }
419
-
420
- /**
421
- * Move the WP entity corresponding to this container to the Trash.
422
- *
423
- * Must be over-riden in a subclass.
424
- *
425
- * @return bool|WP_Error
426
- */
427
- function trash_wrapped_object(){
428
- trigger_error('Function blcContainer::trash_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
429
- }
430
-
431
- /**
432
- * Check if the current user can delete/trash this container.
433
- *
434
- * Should be over-ridden in a subclass.
435
- *
436
- * @return bool
437
- */
438
- function current_user_can_delete(){
439
- return false;
440
- }
441
-
442
- /**
443
- * Determine if this container can be moved to the trash.
444
- *
445
- * Should be over-ridden in a subclass.
446
- *
447
- * @return bool
448
- */
449
- function can_be_trashed(){
450
- return false;
451
- }
452
-
453
-
454
- /**
455
- * Change all links with the specified URL to a new URL.
456
- *
457
- * @param string $field_name
458
- * @param blcParser $parser
459
- * @param string $new_url
460
- * @param string $old_url
461
- * @param string $old_raw_url
462
- * @param string $new_text Optional.
463
- *
464
- * @return array|WP_Error The new value of raw_url on success, or an error object if something went wrong.
465
- */
466
- function edit_link($field_name, $parser, $new_url, $old_url = '', $old_raw_url = '', $new_text = null){
467
- //Ensure we're operating on a consistent copy of the wrapped object.
468
- /*
469
- Explanation
470
-
471
- Consider this scenario where the container object wraps a blog post :
472
- 1) The container object gets created and loads the post data.
473
- 2) Someone modifies the DB data corresponding to the post.
474
- 3) The container tries to edit a link present in the post. However, the post
475
- has changed since the time it was first cached, so when the container updates
476
- the post with it's changes, it will overwrite whatever modifications were made
477
- in step 2.
478
-
479
- This would not be a problem if WP entities like posts and comments were
480
- actually real objects, not just bags of key=>value pairs, but oh well.
481
-
482
- Therefore, it is necessary to re-load the wrapped object before editing it.
483
- */
484
- $this->get_wrapped_object(true);
485
-
486
- //Get the current value of the field that needs to be edited.
487
- $old_value = $this->get_field($field_name);
488
-
489
- //Have the parser modify the specified link. If successful, the parser will
490
- //return an associative array with two keys - 'content' and 'raw_url'.
491
- //Otherwise we'll get an instance of WP_Error.
492
- if ( $parser->is_link_text_editable() ) {
493
- $edit_result = $parser->edit($old_value, $new_url, $old_url, $old_raw_url, $new_text);
494
- } else {
495
- $edit_result = $parser->edit($old_value, $new_url, $old_url, $old_raw_url);
496
- }
497
- if ( is_wp_error($edit_result) ){
498
- return $edit_result;
499
- }
500
-
501
- //Update the field with the new value returned by the parser.
502
- $update_result = $this->update_field( $field_name, $edit_result['content'], $old_value );
503
- if ( is_wp_error($update_result) ){
504
- return $update_result;
505
- }
506
-
507
- //Return the new values to the instance.
508
- unset($edit_result['content']); //(Except content, which it doesn't need.)
509
- return $edit_result;
510
- }
511
-
512
- /**
513
- * Remove all links with the specified URL, leaving their anchor text intact.
514
- *
515
- * @param string $field_name
516
- * @param blcParser $parser
517
- * @param string $url
518
- * @param string $raw_url
519
- * @return bool|WP_Error True on success, or an error object if something went wrong.
520
- */
521
- function unlink($field_name, $parser, $url, $raw_url =''){
522
- //Ensure we're operating on a consistent copy of the wrapped object.
523
- $this->get_wrapped_object(true);
524
-
525
- $old_value = $this->get_field($field_name);
526
-
527
- $new_value = $parser->unlink($old_value, $url, $raw_url);
528
- if ( is_wp_error($new_value) ){
529
- return $new_value;
530
- }
531
-
532
- return $this->update_field( $field_name, $new_value, $old_value );
533
- }
534
-
535
- /**
536
- * Retrieve a list of links found in this container.
537
- *
538
- * @access public
539
- *
540
- * @return array of blcLink
541
- */
542
- function get_links(){
543
- $params = array(
544
- 's_container_type' => $this->container_type,
545
- 's_container_id' => $this->container_id,
546
- );
547
- return blc_get_links($params);
548
- }
549
-
550
-
551
- /**
552
- * Get action links to display in the "Source" column of the Tools -> Broken Links link table.
553
- *
554
- * @param string $container_field
555
- * @return array
556
- */
557
- function ui_get_action_links($container_field){
558
- return array();
559
- }
560
-
561
- /**
562
- * Get the container name to display in the "Source" column of the Tools -> Broken Links link table.
563
- *
564
- * @param string $container_field
565
- * @param string $context
566
- * @return string
567
- */
568
- function ui_get_source($container_field, $context = 'display'){
569
- return sprintf('%s[%d] : %s', $this->container_type, $this->container_id, $container_field);
570
- }
571
-
572
- /**
573
- * Get edit URL. Returns the URL of the Dashboard page where the item associated with this
574
- * container can be edited.
575
- *
576
- * HTML entities like '&' will be properly escaped for display.
577
- *
578
- * @access protected
579
- *
580
- * @return string
581
- */
582
- function get_edit_url(){
583
- //Should be over-ridden in a sub-class.
584
- return '';
585
- }
586
-
587
- }
588
-
589
-
590
- /**
591
- * An utility class for working with link container types.
592
- * All methods of this class should be called statically.
593
- *
594
- * @package Broken Link Checker
595
- */
596
- class blcContainerHelper {
597
-
598
- /**
599
- * Get the manager associated with a container type.
600
- *
601
- * @param string $container_type
602
- * @param string $fallback If there is no manager associated with $container_type, return the manager of this container type instead.
603
- * @return blcContainerManager|null
604
- */
605
- static function get_manager( $container_type, $fallback = '' ){
606
- $module_manager = blcModuleManager::getInstance();
607
- $container_manager = null;
608
-
609
- if ( $container_manager = $module_manager->get_module($container_type, true, 'container') ){
610
- return $container_manager;
611
- } elseif ( !empty($fallback) && ( $container_manager = $module_manager->get_module($fallback, true, 'container') ) ) {
612
- return $container_manager;
613
- } else {
614
- return null;
615
- }
616
- }
617
-
618
- /**
619
- * Retrieve or instantiate a container object.
620
- *
621
- * Pass an array containing the container type (string) and ID (int) to retrieve the container
622
- * from the database. Alternatively, pass an associative array to create a new container object
623
- * from the data in the array.
624
- *
625
- * @param array $container Either [container_type, container_id], or an assoc. array of container data.
626
- * @return blcContainer|null
627
- */
628
- static function get_container( $container ){
629
- global $wpdb; /* @var wpdb $wpdb */
630
-
631
- if ( !is_array($container) || ( count($container) < 2 ) ){
632
- return null;
633
- }
634
-
635
- if ( is_string($container[0]) && is_numeric($container[1]) ){
636
- //The argument is in the [container_type, id] format
637
- //Fetch the container's synch record.
638
- $q = "SELECT * FROM {$wpdb->prefix}blc_synch WHERE container_type = %s AND container_id = %d";
639
- $q = $wpdb->prepare($q, $container[0], $container[1]);
640
- $rez = $wpdb->get_row($q, ARRAY_A);
641
-
642
- if ( empty($rez) ){
643
- //The container wasn't found, so we'll create a new one.
644
- $container = array(
645
- 'container_type' => $container[0],
646
- 'container_id' => $container[1],
647
- );
648
- } else {
649
- $container = $rez;
650
- }
651
- }
652
-
653
- if ( !($manager = blcContainerHelper::get_manager($container['container_type'])) ){
654
- return null;
655
- }
656
-
657
- return $manager->get_container($container);
658
- }
659
-
660
- /**
661
- * Retrieve or instantiate multiple link containers.
662
- *
663
- * Takes an array of container specifications and returns an array of container objects.
664
- * Each input array entry should be an array and consist either of a container type (string)
665
- * and container ID (int), or name => value pairs describing a container object.
666
- *
667
- * @see blcContainerHelper::get_container()
668
- *
669
- * @param array $containers
670
- * @param string $purpose Optional code indicating how the retrieved containers will be used.
671
- * @param string $fallback The fallback container type to use for unrecognized containers.
672
- * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
673
- * @return blcContainer[] Array of blcContainer indexed by "container_type|container_id"
674
- */
675
- static function get_containers( $containers, $purpose = '', $fallback = '', $load_wrapped_objects = false ){
676
- global $wpdb; /* @var wpdb $wpdb */
677
-
678
- //If the input is invalid or empty, return an empty array.
679
- if ( !is_array($containers) || (count($containers) < 1) ) {
680
- return array();
681
- }
682
-
683
- $first = reset($containers);
684
- if ( !is_array($first) ){
685
- return array();
686
- }
687
-
688
- if ( isset($first[0]) && is_string($first[0]) && is_numeric($first[1]) ){
689
- //The argument is an array of [container_type, id].
690
- //Divide the container IDs by container type.
691
- $by_type = array();
692
-
693
- foreach($containers as $container){
694
- if ( isset($by_type[$container[0]]) ){
695
- array_push($by_type[$container[0]], intval($container[1]));
696
- } else {
697
- $by_type[$container[0]] = array( intval($container[1]) );
698
- }
699
- }
700
-
701
- //Build the SQL to fetch all the specified containers
702
- $q = "SELECT *
703
- FROM {$wpdb->prefix}blc_synch
704
- WHERE";
705
-
706
- $pieces = array();
707
- foreach($by_type as $container_type => $container_ids){
708
- $pieces[] = '( container_type = "'. esc_sql($container_type) .'" AND container_id IN ('. implode(', ', $container_ids) .') )';
709
- }
710
-
711
- $q .= implode("\n\t OR ", $pieces);
712
-
713
- //Fetch the container synch. records from the DB.
714
- $containers = $wpdb->get_results($q, ARRAY_A);
715
- }
716
-
717
- /*
718
- Divide the inputs into separate arrays by container type (again), then invoke
719
- the appropriate manager for each type to instantiate the container objects.
720
- */
721
-
722
- //At this point, $containers is an array of assoc. arrays comprising container data.
723
- $by_type = array();
724
- foreach($containers as $container){
725
- if ( isset($by_type[$container['container_type']]) ){
726
- array_push($by_type[$container['container_type']], $container);
727
- } else {
728
- $by_type[$container['container_type']] = array($container);
729
- }
730
- }
731
-
732
- $results = array();
733
- foreach($by_type as $container_type => $entries){
734
- $manager = blcContainerHelper::get_manager($container_type, $fallback);
735
- if ( !is_null($manager) ){
736
- $partial_results = $manager->get_containers($entries, $purpose, $load_wrapped_objects);
737
- $results = array_merge($results, $partial_results);
738
- }
739
- }
740
-
741
- return $results;
742
- }
743
-
744
- /**
745
- * Retrieve link containers that need to be synchronized (parsed).
746
- *
747
- * @param integer $max_results The maximum number of containers to return. Defaults to returning all unsynched containers.
748
- * @return blcContainer[]
749
- */
750
- static function get_unsynched_containers($max_results = 0){
751
- global $wpdb; /* @var wpdb $wpdb */
752
-
753
- $q = "SELECT * FROM {$wpdb->prefix}blc_synch WHERE synched = 0";
754
- if ( $max_results > 0 ){
755
- $q .= " LIMIT $max_results";
756
- }
757
-
758
- $container_data = $wpdb->get_results($q, ARRAY_A);
759
- //FB::log($container_data, "Unsynched containers");
760
- if( empty($container_data) ){
761
- return array();
762
- }
763
-
764
- $containers = blcContainerHelper::get_containers($container_data, BLC_FOR_PARSING, 'dummy');
765
- return $containers;
766
- }
767
-
768
- /**
769
- * (Re)create and update synchronization records for all supported containers.
770
- * Calls the resynch() method of all registered managers.
771
- *
772
- * @param bool $forced If true, assume that no synch. records exist and build all of them from scratch.
773
- * @return void
774
- */
775
- static function resynch($forced = false){
776
- global $wpdb;
777
-
778
- $module_manager = blcModuleManager::getInstance();
779
- $active_managers = $module_manager->get_active_by_category('container');
780
- foreach($active_managers as $module_id => $module_data){
781
- $manager = $module_manager->get_module($module_id);
782
- if ( $manager ){
783
- $manager->resynch($forced);
784
- }
785
- }
786
- }
787
-
788
- /**
789
- * Mark as unparsed all containers that match one of the the specified formats or
790
- * container types and that were last parsed after a specific timestamp.
791
- *
792
- * Used by newly activated parsers to force the containers they're interested in
793
- * to resynchronize and thus let the parser process them.
794
- *
795
- * @param array $formats Associative array of timestamps, indexed by format IDs.
796
- * @param array $container_types Associative array of timestamps, indexed by container types.
797
- * @return bool
798
- */
799
- static function mark_as_unsynched_where($formats, $container_types){
800
- global $wpdb; /* @var wpdb $wpdb */
801
- global $blclog;
802
-
803
- //Find containers that match any of the specified formats and add them to
804
- //the list of container types that need to be marked as unsynched.
805
- $module_manager = blcModuleManager::getInstance();
806
- $containers = $module_manager->get_active_by_category('container');
807
-
808
- foreach($containers as $module_id => $module_data){
809
- if ( $container_manager = $module_manager->get_module($module_id) ){
810
- $fields = $container_manager->get_parseable_fields();
811
- $container_type = $container_manager->container_type;
812
- foreach($formats as $format => $timestamp){
813
- if ( in_array($format, $fields) ){
814
- //Choose the earliest timestamp
815
- if ( isset($container_types[$container_type]) ){
816
- $container_types[$container_type] = min($timestamp, $container_types[$container_type]);
817
- } else {
818
- $container_types[$container_type] = $timestamp;
819
- }
820
- }
821
- }
822
- };
823
- }
824
-
825
- if ( empty($container_types) ){
826
- return true;
827
- }
828
-
829
- //Build the query to update all synch. records that match one of the specified
830
- //container types and have been parsed after the specified time.
831
- $q = "UPDATE {$wpdb->prefix}blc_synch SET synched = 0 WHERE ";
832
-
833
- $pieces = array();
834
- foreach($container_types as $container_type => $timestamp){
835
- $pieces[] = $wpdb->prepare(
836
- '(container_type = %s AND last_synch >= %s)',
837
- $container_type,
838
- date('Y-m-d H:i:s', $timestamp)
839
- );
840
- }
841
-
842
- $q .= implode(' OR ', $pieces);
843
- $blclog->log('...... Executing query: ' . $q);
844
-
845
- $start_time = microtime(true);
846
- $rez = ($wpdb->query($q) !== false);
847
- $blclog->log(sprintf('...... %d rows affected, %.3f seconds', $wpdb->rows_affected, microtime(true) - $start_time));
848
-
849
- blc_got_unsynched_items();
850
-
851
- return $rez;
852
- }
853
-
854
- /**
855
- * Remove synch. records that reference container types not currently loaded
856
- *
857
- * @return bool
858
- */
859
- static function cleanup_containers(){
860
- global $wpdb; /* @var wpdb $wpdb */
861
- global $blclog;
862
-
863
- $module_manager = blcModuleManager::getInstance();
864
-
865
- $start = microtime(true);
866
- $active_containers = $module_manager->get_escaped_ids('container');
867
- $q = "DELETE synch.*
868
- FROM {$wpdb->prefix}blc_synch AS synch
869
- WHERE
870
- synch.container_type NOT IN ({$active_containers})";
871
- $rez = $wpdb->query($q);
872
- $elapsed = microtime(true) - $start;
873
- $blclog->log(sprintf('... %d synch records deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
874
-
875
- return $rez !== false;
876
- }
877
-
878
- /**
879
- * Get the message to display after $n containers of a specific type have been deleted.
880
- *
881
- * @param string $container_type
882
- * @param int $n Number of deleted containers.
883
- * @return string A delete confirmation message, e.g. "5 posts were moved to trash"
884
- */
885
- static function ui_bulk_delete_message($container_type, $n){
886
- $manager = blcContainerHelper::get_manager($container_type);
887
- if ( is_null($manager) ){
888
- return sprintf(__("Container type '%s' not recognized", 'broken-link-checker'), $container_type);
889
- } else {
890
- return $manager->ui_bulk_delete_message($n);
891
- }
892
- }
893
-
894
- /**
895
- * Get the message to display after $n containers of a specific type have been moved to the trash.
896
- *
897
- * @see blcContainerHelper::ui_bulk_delete_message()
898
- *
899
- * @param string $container_type
900
- * @param int $n
901
- * @return string
902
- */
903
- static function ui_bulk_trash_message($container_type, $n){
904
- $manager = blcContainerHelper::get_manager($container_type);
905
- if ( is_null($manager) ){
906
- return sprintf(__("Container type '%s' not recognized", 'broken-link-checker'), $container_type);
907
- } else {
908
- return $manager->ui_bulk_trash_message($n);
909
- }
910
- }
911
- }
1
+ <?php
2
+
3
+ /**
4
+ * The base class for link container managers.
5
+ *
6
+ * Sub-classes should override at least the get_containers() and resynch() methods.
7
+ *
8
+ * @package Broken Link Checker
9
+ * @access public
10
+ */
11
+ class blcContainerManager extends blcModule {
12
+
13
+ var $container_type = '';
14
+ var $fields = array();
15
+ var $container_class_name = 'blcContainer';
16
+
17
+ /**
18
+ * Do whatever setup necessary that wasn't already done in the constructor.
19
+ *
20
+ * This method was added so that sub-classes would have something "safe" to
21
+ * over-ride without having to deal with PHP4/5 constructors.
22
+ *
23
+ * @return void
24
+ */
25
+ function init(){
26
+ parent::init();
27
+ $this->container_type = $this->module_id;
28
+ //Sub-classes might also use it to set up hooks, etc.
29
+ }
30
+
31
+ /**
32
+ * Instantiate a link container.
33
+ *
34
+ * @param array $container An associative array of container data.
35
+ * @return blcContainer
36
+ */
37
+ function get_container($container){
38
+ $container['fields'] = $this->get_parseable_fields();
39
+ $container_obj = new $this->container_class_name($container);
40
+ return $container_obj;
41
+ }
42
+
43
+ /**
44
+ * Instantiate multiple containers of the container type managed by this class and optionally
45
+ * pre-load container data used for display/parsing.
46
+ *
47
+ * Sub-classes should, if possible, use the $purpose argument to pre-load any extra data required for
48
+ * the specified task right away, instead of making multiple DB roundtrips later. For example, if
49
+ * $purpose is set to the BLC_FOR_DISPLAY constant, you might want to preload any DB data that the
50
+ * container will need in blcContainer::ui_get_source().
51
+ *
52
+ * @see blcContainer::make_containers()
53
+ * @see blcContainer::ui_get_source()
54
+ * @see blcContainer::ui_get_action_links()
55
+ *
56
+ * @param array $containers Array of assoc. arrays containing container data.
57
+ * @param string $purpose An optional code indicating how the retrieved containers will be used.
58
+ * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
59
+ *
60
+ * @return array of blcContainer indexed by "container_type|container_id"
61
+ */
62
+ function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
63
+ return $this->make_containers($containers);
64
+ }
65
+
66
+ /**
67
+ * Instantiate multiple containers of the container type managed by this class
68
+ *
69
+ * @param array $containers Array of assoc. arrays containing container data.
70
+ * @return array of blcContainer indexed by "container_type|container_id"
71
+ */
72
+ function make_containers($containers){
73
+ $results = array();
74
+ foreach($containers as $container){
75
+ $key = $container['container_type'] . '|' . $container['container_id'];
76
+ $results[ $key ] = $this->get_container($container);
77
+ }
78
+ return $results;
79
+ }
80
+
81
+ /**
82
+ * Create or update synchronization records for all containers managed by this class.
83
+ *
84
+ * Must be over-ridden in subclasses.
85
+ *
86
+ * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
87
+ * @return void
88
+ */
89
+ function resynch($forced = false){
90
+ trigger_error('Function blcContainerManager::resynch() must be over-ridden in a sub-class', E_USER_ERROR);
91
+ }
92
+
93
+ /**
94
+ * Resynch when activated.
95
+ *
96
+ * @uses blcContainerManager::resynch()
97
+ *
98
+ * @return void
99
+ */
100
+ function activated(){
101
+ $this->resynch();
102
+ blc_got_unsynched_items();
103
+ }
104
+
105
+ /**
106
+ * Get a list of the parseable fields and their formats common to all containers of this type.
107
+ *
108
+ * @return array Associative array of formats indexed by field name.
109
+ */
110
+ function get_parseable_fields(){
111
+ return $this->fields;
112
+ }
113
+
114
+ /**
115
+ * Get the message to display after $n containers have been deleted.
116
+ *
117
+ * @param int $n Number of deleted containers.
118
+ * @return string A delete confirmation message, e.g. "5 posts were moved to trash"
119
+ */
120
+ function ui_bulk_delete_message($n){
121
+ return sprintf(
122
+ _n(
123
+ "%d '%s' has been deleted",
124
+ "%d '%s' have been deleted",
125
+ $n,
126
+ 'broken-link-checker'
127
+ ),
128
+ $n,
129
+ $this->container_type
130
+ );
131
+ }
132
+
133
+ /**
134
+ * Get the message to display after $n containers have been moved to the trash.
135
+ *
136
+ * @param int $n Number of trashed containers.
137
+ * @return string A delete confirmation message, e.g. "5 posts were moved to trash"
138
+ */
139
+ function ui_bulk_trash_message($n){
140
+ return $this->ui_bulk_delete_message($n);
141
+ }
142
+ }
143
+
144
+ /**
145
+ * The base class for link containers. All containers should extend this class.
146
+ *
147
+ * @package Broken Link Checker
148
+ * @access public
149
+ */
150
+ class blcContainer {
151
+
152
+ var $fields = array();
153
+ var $default_field = '';
154
+
155
+ var $container_type;
156
+ var $container_id = 0;
157
+
158
+ var $synched = false;
159
+ var $last_synch = '0000-00-00 00:00:00';
160
+
161
+ var $wrapped_object = null;
162
+
163
+ /**
164
+ * Constructor
165
+ *
166
+ * @param array $data
167
+ * @param object $wrapped_object
168
+ * @return void
169
+ */
170
+ function __construct( $data = null, $wrapped_object = null ){
171
+ $this->wrapped_object = $wrapped_object;
172
+ if ( !empty($data) && is_array($data) ){
173
+ foreach($data as $name => $value){
174
+ $this->$name = $value;
175
+ }
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Get the value of the specified field of the object wrapped by this container.
181
+ *
182
+ * @access protected
183
+ *
184
+ * @param string $field Field name. If omitted, the value of the default field will be returned.
185
+ * @return string
186
+ */
187
+ function get_field($field = ''){
188
+ if ( empty($field) ){
189
+ $field = $this->default_field;
190
+ }
191
+
192
+ $w = $this->get_wrapped_object();
193
+ return $w->$field;
194
+ }
195
+
196
+ /**
197
+ * Update the value of the specified field in the wrapped object.
198
+ * This method will also immediately save the changed value by calling update_wrapped_object().
199
+ *
200
+ * @access protected
201
+ *
202
+ * @param string $field Field name.
203
+ * @param string $new_value Set the field to this value.
204
+ * @param string $old_value The previous value of the field. Optional, but can be useful for container that need the old value to distinguish between several instances of the same field (e.g. post metadata).
205
+ * @return bool|WP_Error True on success, an error object if something went wrong.
206
+ */
207
+ function update_field($field, $new_value, $old_value = ''){
208
+ $w = $this->get_wrapped_object();
209
+ $w->$field = $new_value;
210
+ return $this->update_wrapped_object();
211
+ }
212
+
213
+ /**
214
+ * Retrieve the entity wrapped by this container.
215
+ * The fetched object will also be cached in the $wrapped_object variable.
216
+ *
217
+ * @access protected
218
+ *
219
+ * @param bool $ensure_consistency Set this to true to ignore the cached $wrapped_object value and retrieve an up-to-date copy of the wrapped object from the DB (or WP's internal cache).
220
+ * @return object The wrapped object.
221
+ */
222
+ function get_wrapped_object($ensure_consistency = false){
223
+ trigger_error('Function blcContainer::get_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
224
+ }
225
+
226
+ /**
227
+ * Update the entity wrapped by the container with values currently in the $wrapped_object.
228
+ *
229
+ * @access protected
230
+ *
231
+ * @return bool|WP_Error True on success, an error if something went wrong.
232
+ */
233
+ function update_wrapped_object(){
234
+ trigger_error('Function blcContainer::update_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
235
+ }
236
+
237
+ /**
238
+ * Parse the container for links and save the results to the DB.
239
+ *
240
+ * @return void
241
+ */
242
+ function synch(){
243
+ //FB::log("Parsing {$this->container_type}[{$this->container_id}]");
244
+
245
+ //Remove any existing link instance records associated with the container
246
+ $this->delete_instances();
247
+
248
+ //Load the wrapped object, if not done already
249
+ $this->get_wrapped_object();
250
+
251
+ //FB::log($this->fields, "Parseable fields :");
252
+
253
+ //Iterate over all parse-able fields
254
+ foreach($this->fields as $name => $format){
255
+ //Get the field value
256
+ $value = $this->get_field($name);
257
+ if ( empty($value) ){
258
+ //FB::log($name, "Skipping empty field");
259
+ continue;
260
+ }
261
+ //FB::log($name, "Parsing field");
262
+
263
+ //Get all parsers applicable to this field
264
+ $parsers = blcParserHelper::get_parsers( $format, $this->container_type );
265
+ //FB::log($parsers, "Applicable parsers");
266
+
267
+ if ( empty($parsers) ) continue;
268
+
269
+ $base_url = $this->base_url();
270
+ $default_link_text = $this->default_link_text($name);
271
+
272
+ //Parse the field with each parser
273
+ foreach($parsers as $parser){
274
+ //FB::log("Parsing $name with '{$parser->parser_type}' parser");
275
+ $found_instances = $parser->parse( $value, $base_url, $default_link_text );
276
+ //FB::log($found_instances, "Found instances");
277
+
278
+ $transactionManager = TransactionManager::getInstance();
279
+ $transactionManager->start();
280
+
281
+ //Complete the link instances by adding container info, then save them to the DB.
282
+ foreach($found_instances as $instance){
283
+ $instance->set_container($this, $name);
284
+ $instance->save();
285
+ }
286
+
287
+ $transactionManager->commit();
288
+
289
+ }
290
+ }
291
+
292
+ $this->mark_as_synched();
293
+ }
294
+
295
+ /**
296
+ * Mark the container as successfully synchronized (parsed for links).
297
+ *
298
+ * @return bool
299
+ */
300
+ function mark_as_synched(){
301
+ global $wpdb; /* @var wpdb $wpdb */
302
+
303
+ $this->last_synch = time();
304
+
305
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch( container_id, container_type, synched, last_synch)
306
+ VALUES( %d, %s, %d, NOW() )
307
+ ON DUPLICATE KEY UPDATE synched = VALUES(synched), last_synch = VALUES(last_synch)";
308
+ $rez = $wpdb->query( $wpdb->prepare( $q, $this->container_id, $this->container_type, 1 ) );
309
+
310
+ return ($rez !== false);
311
+ }
312
+
313
+ /**
314
+ * blcContainer::mark_as_unsynched()
315
+ * Mark the container as not synchronized (not parsed, or modified since the last parse).
316
+ * The plugin will attempt to (re)parse the container at the earliest opportunity.
317
+ *
318
+ * @return bool
319
+ */
320
+ function mark_as_unsynched(){
321
+ global $wpdb; /* @var wpdb $wpdb */
322
+
323
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch( container_id, container_type, synched, last_synch)
324
+ VALUES( %d, %s, %d, '0000-00-00 00:00:00' )
325
+ ON DUPLICATE KEY UPDATE synched = VALUES(synched)";
326
+ $rez = $wpdb->query( $wpdb->prepare( $q, $this->container_id, $this->container_type, 0 ) );
327
+
328
+ blc_got_unsynched_items();
329
+
330
+ return ($rez !== false);
331
+ }
332
+
333
+ /**
334
+ * Get the base URL of the container. Used to normalize relative URLs found
335
+ * in the container. For example, for posts this would be the post permalink.
336
+ *
337
+ * @return string
338
+ */
339
+ function base_url(){
340
+ return home_url();
341
+ }
342
+
343
+ /**
344
+ * Get the default link text to use for links found in a specific container field.
345
+ *
346
+ * This is generally only meaningful for non-HTML container fields.
347
+ * For example, if the container is post metadata, the default
348
+ * link text might be equal to the name of the custom field.
349
+ *
350
+ * @param string $field
351
+ * @return string
352
+ */
353
+ function default_link_text($field = ''){
354
+ return '';
355
+ }
356
+
357
+
358
+
359
+ /**
360
+ * Delete the DB record of this container.
361
+ * Also deletes the DB records of all link instances associated with it.
362
+ * Calling this method will not affect the WP entity (e.g. a post) corresponding to this container.
363
+ *
364
+ * @return bool
365
+ */
366
+ function delete(){
367
+ global $wpdb; /* @var wpdb $wpdb */
368
+
369
+ //Delete instances first.
370
+ $rez = $this->delete_instances();
371
+ if ( !$rez ){
372
+ return false;
373
+ }
374
+
375
+ //Now delete the container record.
376
+ $q = "DELETE FROM {$wpdb->prefix}blc_synch
377
+ WHERE container_id = %d AND container_type = %s";
378
+ $q = $wpdb->prepare($q, $this->container_id, $this->container_type);
379
+
380
+ if ( $wpdb->query( $q ) === false ){
381
+ return false;
382
+ } else {
383
+ return true;
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Delete all link instance records associated with this container.
389
+ * NB: Calling this method will not affect the WP entity (e.g. a post) corresponding to this container.
390
+ *
391
+ * @return bool
392
+ */
393
+ function delete_instances(){
394
+ global $wpdb; /* @var wpdb $wpdb */
395
+
396
+ //Remove instances associated with this container
397
+ $q = "DELETE FROM {$wpdb->prefix}blc_instances
398
+ WHERE container_id = %d AND container_type = %s";
399
+ $q = $wpdb->prepare($q, $this->container_id, $this->container_type);
400
+
401
+ if ( $wpdb->query( $q ) === false ){
402
+ return false;
403
+ } else {
404
+ return true;
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Delete or trash the WP entity corresponding to this container. Should prefer moving to trash, if possible.
410
+ * Also remove the synch. record of the container and all associated instances.
411
+ *
412
+ * Must be over-ridden in a sub-class.
413
+ *
414
+ * @return bool|WP_Error
415
+ */
416
+ function delete_wrapped_object(){
417
+ trigger_error('Function blcContainer::delete_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
418
+ }
419
+
420
+ /**
421
+ * Move the WP entity corresponding to this container to the Trash.
422
+ *
423
+ * Must be over-riden in a subclass.
424
+ *
425
+ * @return bool|WP_Error
426
+ */
427
+ function trash_wrapped_object(){
428
+ trigger_error('Function blcContainer::trash_wrapped_object() must be over-ridden in a sub-class', E_USER_ERROR);
429
+ }
430
+
431
+ /**
432
+ * Check if the current user can delete/trash this container.
433
+ *
434
+ * Should be over-ridden in a subclass.
435
+ *
436
+ * @return bool
437
+ */
438
+ function current_user_can_delete(){
439
+ return false;
440
+ }
441
+
442
+ /**
443
+ * Determine if this container can be moved to the trash.
444
+ *
445
+ * Should be over-ridden in a subclass.
446
+ *
447
+ * @return bool
448
+ */
449
+ function can_be_trashed(){
450
+ return false;
451
+ }
452
+
453
+
454
+ /**
455
+ * Change all links with the specified URL to a new URL.
456
+ *
457
+ * @param string $field_name
458
+ * @param blcParser $parser
459
+ * @param string $new_url
460
+ * @param string $old_url
461
+ * @param string $old_raw_url
462
+ * @param string $new_text Optional.
463
+ *
464
+ * @return array|WP_Error The new value of raw_url on success, or an error object if something went wrong.
465
+ */
466
+ function edit_link($field_name, $parser, $new_url, $old_url = '', $old_raw_url = '', $new_text = null){
467
+ //Ensure we're operating on a consistent copy of the wrapped object.
468
+ /*
469
+ Explanation
470
+
471
+ Consider this scenario where the container object wraps a blog post :
472
+ 1) The container object gets created and loads the post data.
473
+ 2) Someone modifies the DB data corresponding to the post.
474
+ 3) The container tries to edit a link present in the post. However, the post
475
+ has changed since the time it was first cached, so when the container updates
476
+ the post with it's changes, it will overwrite whatever modifications were made
477
+ in step 2.
478
+
479
+ This would not be a problem if WP entities like posts and comments were
480
+ actually real objects, not just bags of key=>value pairs, but oh well.
481
+
482
+ Therefore, it is necessary to re-load the wrapped object before editing it.
483
+ */
484
+ $this->get_wrapped_object(true);
485
+
486
+ //Get the current value of the field that needs to be edited.
487
+ $old_value = $this->get_field($field_name);
488
+
489
+ //Have the parser modify the specified link. If successful, the parser will
490
+ //return an associative array with two keys - 'content' and 'raw_url'.
491
+ //Otherwise we'll get an instance of WP_Error.
492
+ if ( $parser->is_link_text_editable() ) {
493
+ $edit_result = $parser->edit($old_value, $new_url, $old_url, $old_raw_url, $new_text);
494
+ } else {
495
+ $edit_result = $parser->edit($old_value, $new_url, $old_url, $old_raw_url);
496
+ }
497
+ if ( is_wp_error($edit_result) ){
498
+ return $edit_result;
499
+ }
500
+
501
+ //Update the field with the new value returned by the parser.
502
+ $update_result = $this->update_field( $field_name, $edit_result['content'], $old_value );
503
+ if ( is_wp_error($update_result) ){
504
+ return $update_result;
505
+ }
506
+
507
+ //Return the new values to the instance.
508
+ unset($edit_result['content']); //(Except content, which it doesn't need.)
509
+ return $edit_result;
510
+ }
511
+
512
+ /**
513
+ * Remove all links with the specified URL, leaving their anchor text intact.
514
+ *
515
+ * @param string $field_name
516
+ * @param blcParser $parser
517
+ * @param string $url
518
+ * @param string $raw_url
519
+ * @return bool|WP_Error True on success, or an error object if something went wrong.
520
+ */
521
+ function unlink($field_name, $parser, $url, $raw_url =''){
522
+ //Ensure we're operating on a consistent copy of the wrapped object.
523
+ $this->get_wrapped_object(true);
524
+
525
+ $old_value = $this->get_field($field_name);
526
+
527
+ $new_value = $parser->unlink($old_value, $url, $raw_url);
528
+ if ( is_wp_error($new_value) ){
529
+ return $new_value;
530
+ }
531
+
532
+ return $this->update_field( $field_name, $new_value, $old_value );
533
+ }
534
+
535
+ /**
536
+ * Retrieve a list of links found in this container.
537
+ *
538
+ * @access public
539
+ *
540
+ * @return array of blcLink
541
+ */
542
+ function get_links(){
543
+ $params = array(
544
+ 's_container_type' => $this->container_type,
545
+ 's_container_id' => $this->container_id,
546
+ );
547
+ return blc_get_links($params);
548
+ }
549
+
550
+
551
+ /**
552
+ * Get action links to display in the "Source" column of the Tools -> Broken Links link table.
553
+ *
554
+ * @param string $container_field
555
+ * @return array
556
+ */
557
+ function ui_get_action_links($container_field){
558
+ return array();
559
+ }
560
+
561
+ /**
562
+ * Get the container name to display in the "Source" column of the Tools -> Broken Links link table.
563
+ *
564
+ * @param string $container_field
565
+ * @param string $context
566
+ * @return string
567
+ */
568
+ function ui_get_source($container_field, $context = 'display'){
569
+ return sprintf('%s[%d] : %s', $this->container_type, $this->container_id, $container_field);
570
+ }
571
+
572
+ /**
573
+ * Get edit URL. Returns the URL of the Dashboard page where the item associated with this
574
+ * container can be edited.
575
+ *
576
+ * HTML entities like '&' will be properly escaped for display.
577
+ *
578
+ * @access protected
579
+ *
580
+ * @return string
581
+ */
582
+ function get_edit_url(){
583
+ //Should be over-ridden in a sub-class.
584
+ return '';
585
+ }
586
+
587
+ }
588
+
589
+
590
+ /**
591
+ * An utility class for working with link container types.
592
+ * All methods of this class should be called statically.
593
+ *
594
+ * @package Broken Link Checker
595
+ */
596
+ class blcContainerHelper {
597
+
598
+ /**
599
+ * Get the manager associated with a container type.
600
+ *
601
+ * @param string $container_type
602
+ * @param string $fallback If there is no manager associated with $container_type, return the manager of this container type instead.
603
+ * @return blcContainerManager|null
604
+ */
605
+ static function get_manager( $container_type, $fallback = '' ){
606
+ $module_manager = blcModuleManager::getInstance();
607
+ $container_manager = null;
608
+
609
+ if ( $container_manager = $module_manager->get_module($container_type, true, 'container') ){
610
+ return $container_manager;
611
+ } elseif ( !empty($fallback) && ( $container_manager = $module_manager->get_module($fallback, true, 'container') ) ) {
612
+ return $container_manager;
613
+ } else {
614
+ return null;
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Retrieve or instantiate a container object.
620
+ *
621
+ * Pass an array containing the container type (string) and ID (int) to retrieve the container
622
+ * from the database. Alternatively, pass an associative array to create a new container object
623
+ * from the data in the array.
624
+ *
625
+ * @param array $container Either [container_type, container_id], or an assoc. array of container data.
626
+ * @return blcContainer|null
627
+ */
628
+ static function get_container( $container ){
629
+ global $wpdb; /* @var wpdb $wpdb */
630
+
631
+ if ( !is_array($container) || ( count($container) < 2 ) ){
632
+ return null;
633
+ }
634
+
635
+ if ( is_string($container[0]) && is_numeric($container[1]) ){
636
+ //The argument is in the [container_type, id] format
637
+ //Fetch the container's synch record.
638
+ $q = "SELECT * FROM {$wpdb->prefix}blc_synch WHERE container_type = %s AND container_id = %d";
639
+ $q = $wpdb->prepare($q, $container[0], $container[1]);
640
+ $rez = $wpdb->get_row($q, ARRAY_A);
641
+
642
+ if ( empty($rez) ){
643
+ //The container wasn't found, so we'll create a new one.
644
+ $container = array(
645
+ 'container_type' => $container[0],
646
+ 'container_id' => $container[1],
647
+ );
648
+ } else {
649
+ $container = $rez;
650
+ }
651
+ }
652
+
653
+ if ( !($manager = blcContainerHelper::get_manager($container['container_type'])) ){
654
+ return null;
655
+ }
656
+
657
+ return $manager->get_container($container);
658
+ }
659
+
660
+ /**
661
+ * Retrieve or instantiate multiple link containers.
662
+ *
663
+ * Takes an array of container specifications and returns an array of container objects.
664
+ * Each input array entry should be an array and consist either of a container type (string)
665
+ * and container ID (int), or name => value pairs describing a container object.
666
+ *
667
+ * @see blcContainerHelper::get_container()
668
+ *
669
+ * @param array $containers
670
+ * @param string $purpose Optional code indicating how the retrieved containers will be used.
671
+ * @param string $fallback The fallback container type to use for unrecognized containers.
672
+ * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
673
+ * @return blcContainer[] Array of blcContainer indexed by "container_type|container_id"
674
+ */
675
+ static function get_containers( $containers, $purpose = '', $fallback = '', $load_wrapped_objects = false ){
676
+ global $wpdb; /* @var wpdb $wpdb */
677
+
678
+ //If the input is invalid or empty, return an empty array.
679
+ if ( !is_array($containers) || (count($containers) < 1) ) {
680
+ return array();
681
+ }
682
+
683
+ $first = reset($containers);
684
+ if ( !is_array($first) ){
685
+ return array();
686
+ }
687
+
688
+ if ( isset($first[0]) && is_string($first[0]) && is_numeric($first[1]) ){
689
+ //The argument is an array of [container_type, id].
690
+ //Divide the container IDs by container type.
691
+ $by_type = array();
692
+
693
+ foreach($containers as $container){
694
+ if ( isset($by_type[$container[0]]) ){
695
+ array_push($by_type[$container[0]], intval($container[1]));
696
+ } else {
697
+ $by_type[$container[0]] = array( intval($container[1]) );
698
+ }
699
+ }
700
+
701
+ //Build the SQL to fetch all the specified containers
702
+ $q = "SELECT *
703
+ FROM {$wpdb->prefix}blc_synch
704
+ WHERE";
705
+
706
+ $pieces = array();
707
+ foreach($by_type as $container_type => $container_ids){
708
+ $pieces[] = '( container_type = "'. esc_sql($container_type) .'" AND container_id IN ('. implode(', ', $container_ids) .') )';
709
+ }
710
+
711
+ $q .= implode("\n\t OR ", $pieces);
712
+
713
+ //Fetch the container synch. records from the DB.
714
+ $containers = $wpdb->get_results($q, ARRAY_A);
715
+ }
716
+
717
+ /*
718
+ Divide the inputs into separate arrays by container type (again), then invoke
719
+ the appropriate manager for each type to instantiate the container objects.
720
+ */
721
+
722
+ //At this point, $containers is an array of assoc. arrays comprising container data.
723
+ $by_type = array();
724
+ foreach($containers as $container){
725
+ if ( isset($by_type[$container['container_type']]) ){
726
+ array_push($by_type[$container['container_type']], $container);
727
+ } else {
728
+ $by_type[$container['container_type']] = array($container);
729
+ }
730
+ }
731
+
732
+ $results = array();
733
+ foreach($by_type as $container_type => $entries){
734
+ $manager = blcContainerHelper::get_manager($container_type, $fallback);
735
+ if ( !is_null($manager) ){
736
+ $partial_results = $manager->get_containers($entries, $purpose, $load_wrapped_objects);
737
+ $results = array_merge($results, $partial_results);
738
+ }
739
+ }
740
+
741
+ return $results;
742
+ }
743
+
744
+ /**
745
+ * Retrieve link containers that need to be synchronized (parsed).
746
+ *
747
+ * @param integer $max_results The maximum number of containers to return. Defaults to returning all unsynched containers.
748
+ * @return blcContainer[]
749
+ */
750
+ static function get_unsynched_containers($max_results = 0){
751
+ global $wpdb; /* @var wpdb $wpdb */
752
+
753
+ $q = "SELECT * FROM {$wpdb->prefix}blc_synch WHERE synched = 0";
754
+ if ( $max_results > 0 ){
755
+ $q .= " LIMIT $max_results";
756
+ }
757
+
758
+ $container_data = $wpdb->get_results($q, ARRAY_A);
759
+ //FB::log($container_data, "Unsynched containers");
760
+ if( empty($container_data) ){
761
+ return array();
762
+ }
763
+
764
+ $containers = blcContainerHelper::get_containers($container_data, BLC_FOR_PARSING, 'dummy');
765
+ return $containers;
766
+ }
767
+
768
+ /**
769
+ * (Re)create and update synchronization records for all supported containers.
770
+ * Calls the resynch() method of all registered managers.
771
+ *
772
+ * @param bool $forced If true, assume that no synch. records exist and build all of them from scratch.
773
+ * @return void
774
+ */
775
+ static function resynch($forced = false){
776
+ global $wpdb;
777
+
778
+ $module_manager = blcModuleManager::getInstance();
779
+ $active_managers = $module_manager->get_active_by_category('container');
780
+ foreach($active_managers as $module_id => $module_data){
781
+ $manager = $module_manager->get_module($module_id);
782
+ if ( $manager ){
783
+ $manager->resynch($forced);
784
+ }
785
+ }
786
+ }
787
+
788
+ /**
789
+ * Mark as unparsed all containers that match one of the the specified formats or
790
+ * container types and that were last parsed after a specific timestamp.
791
+ *
792
+ * Used by newly activated parsers to force the containers they're interested in
793
+ * to resynchronize and thus let the parser process them.
794
+ *
795
+ * @param array $formats Associative array of timestamps, indexed by format IDs.
796
+ * @param array $container_types Associative array of timestamps, indexed by container types.
797
+ * @return bool
798
+ */
799
+ static function mark_as_unsynched_where($formats, $container_types){
800
+ global $wpdb; /* @var wpdb $wpdb */
801
+ global $blclog;
802
+
803
+ //Find containers that match any of the specified formats and add them to
804
+ //the list of container types that need to be marked as unsynched.
805
+ $module_manager = blcModuleManager::getInstance();
806
+ $containers = $module_manager->get_active_by_category('container');
807
+
808
+ foreach($containers as $module_id => $module_data){
809
+ if ( $container_manager = $module_manager->get_module($module_id) ){
810
+ $fields = $container_manager->get_parseable_fields();
811
+ $container_type = $container_manager->container_type;
812
+ foreach($formats as $format => $timestamp){
813
+ if ( in_array($format, $fields) ){
814
+ //Choose the earliest timestamp
815
+ if ( isset($container_types[$container_type]) ){
816
+ $container_types[$container_type] = min($timestamp, $container_types[$container_type]);
817
+ } else {
818
+ $container_types[$container_type] = $timestamp;
819
+ }
820
+ }
821
+ }
822
+ };
823
+ }
824
+
825
+ if ( empty($container_types) ){
826
+ return true;
827
+ }
828
+
829
+ //Build the query to update all synch. records that match one of the specified
830
+ //container types and have been parsed after the specified time.
831
+ $q = "UPDATE {$wpdb->prefix}blc_synch SET synched = 0 WHERE ";
832
+
833
+ $pieces = array();
834
+ foreach($container_types as $container_type => $timestamp){
835
+ $pieces[] = $wpdb->prepare(
836
+ '(container_type = %s AND last_synch >= %s)',
837
+ $container_type,
838
+ date('Y-m-d H:i:s', $timestamp)
839
+ );
840
+ }
841
+
842
+ $q .= implode(' OR ', $pieces);
843
+ $blclog->log('...... Executing query: ' . $q);
844
+
845
+ $start_time = microtime(true);
846
+ $rez = ($wpdb->query($q) !== false);
847
+ $blclog->log(sprintf('...... %d rows affected, %.3f seconds', $wpdb->rows_affected, microtime(true) - $start_time));
848
+
849
+ blc_got_unsynched_items();
850
+
851
+ return $rez;
852
+ }
853
+
854
+ /**
855
+ * Remove synch. records that reference container types not currently loaded
856
+ *
857
+ * @return bool
858
+ */
859
+ static function cleanup_containers(){
860
+ global $wpdb; /* @var wpdb $wpdb */
861
+ global $blclog;
862
+
863
+ $module_manager = blcModuleManager::getInstance();
864
+
865
+ $start = microtime(true);
866
+ $active_containers = $module_manager->get_escaped_ids('container');
867
+ $q = "DELETE synch.*
868
+ FROM {$wpdb->prefix}blc_synch AS synch
869
+ WHERE
870
+ synch.container_type NOT IN ({$active_containers})";
871
+ $rez = $wpdb->query($q);
872
+ $elapsed = microtime(true) - $start;
873
+ $blclog->log(sprintf('... %d synch records deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
874
+
875
+ return $rez !== false;
876
+ }
877
+
878
+ /**
879
+ * Get the message to display after $n containers of a specific type have been deleted.
880
+ *
881
+ * @param string $container_type
882
+ * @param int $n Number of deleted containers.
883
+ * @return string A delete confirmation message, e.g. "5 posts were moved to trash"
884
+ */
885
+ static function ui_bulk_delete_message($container_type, $n){
886
+ $manager = blcContainerHelper::get_manager($container_type);
887
+ if ( is_null($manager) ){
888
+ return sprintf(__("Container type '%s' not recognized", 'broken-link-checker'), $container_type);
889
+ } else {
890
+ return $manager->ui_bulk_delete_message($n);
891
+ }
892
+ }
893
+
894
+ /**
895
+ * Get the message to display after $n containers of a specific type have been moved to the trash.
896
+ *
897
+ * @see blcContainerHelper::ui_bulk_delete_message()
898
+ *
899
+ * @param string $container_type
900
+ * @param int $n
901
+ * @return string
902
+ */
903
+ static function ui_bulk_trash_message($container_type, $n){
904
+ $manager = blcContainerHelper::get_manager($container_type);
905
+ if ( is_null($manager) ){
906
+ return sprintf(__("Container type '%s' not recognized", 'broken-link-checker'), $container_type);
907
+ } else {
908
+ return $manager->ui_bulk_trash_message($n);
909
+ }
910
+ }
911
+ }
includes/extra-strings.php CHANGED
File without changes
includes/instances.php CHANGED
@@ -1,639 +1,639 @@
1
- <?php
2
-
3
- /**
4
- * @author W-Shadow
5
- * @copyright 2009
6
- */
7
-
8
- if (!class_exists('blcLinkInstance')) {
9
- class blcLinkInstance {
10
-
11
- //Object state
12
- var $is_new = false;
13
-
14
- //DB fields
15
- var $instance_id = 0;
16
- var $link_id = 0;
17
-
18
- var $container_id = 0;
19
- var $container_type = '';
20
- var $container_field = '';
21
-
22
- var $parser_type = '';
23
-
24
- var $link_text = '';
25
- var $link_context = '';
26
- var $raw_url = '';
27
-
28
- /** @var blcContainer */
29
- var $_container = null;
30
- var $_parser = null;
31
- /** @var blcLink|null */
32
- var $_link = null;
33
-
34
- /**
35
- * blcLinkInstance::__construct()
36
- * Class constructor
37
- *
38
- * @param int|array $arg Either the instance ID or an associate array representing the instance's DB record. Should be NULL for new instances.
39
- */
40
- function __construct($arg = null){
41
- global $wpdb; /** @var wpdb $wpdb */
42
-
43
- if (is_int($arg)){
44
- //Load an instance with ID = $arg from the DB.
45
- $q = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}blc_instances WHERE instance_id=%d LIMIT 1", $arg);
46
- $arr = $wpdb->get_row( $q, ARRAY_A );
47
-
48
- if ( is_array($arr) ){ //Loaded successfully
49
- $this->set_values($arr);
50
- } else {
51
- //Link instance not found. The object is invalid.
52
- }
53
-
54
- } else if (is_array($arg)){
55
- $this->set_values($arg);
56
-
57
- //Is this a new instance?
58
- $this->is_new = empty($this->instance_id);
59
-
60
- } else {
61
- $this->is_new = true;
62
- }
63
- }
64
-
65
- /**
66
- * blcLinkInstance::blcLinkInstance()
67
- * Old-style constructor for PHP 4. Do not use.
68
- *
69
- * @param mixed $arg
70
- * @return void
71
- */
72
- function blcLinkInstance($arg = null){
73
- $this->__construct($arg);
74
- }
75
-
76
- /**
77
- * blcLinkInstance::set_values()
78
- * Set property values to the ones provided in an array (doesn't sanitize).
79
- *
80
- * @param array $arr An associative array
81
- * @return void
82
- */
83
- function set_values($arr){
84
- foreach( $arr as $key => $value ){
85
- $this->$key = $value;
86
- }
87
- }
88
-
89
- /**
90
- * Replace this instance's URL with a new one.
91
- * Warning : this shouldn't be called directly. Use blcLink->edit() instead.
92
- *
93
- * @param string $new_url
94
- * @param string $old_url
95
- * @param string $new_text
96
- * @return bool|WP_Error True on success, or an instance of WP_Error if something went wrong.
97
- */
98
- function edit($new_url, $old_url = '', $new_text = null){
99
-
100
- //Get the container that contains this link
101
- $container = $this->get_container();
102
- if ( is_null($container) ){
103
- return new WP_Error(
104
- 'container_not_found',
105
- sprintf(__("Container %s[%d] not found", 'broken-link-checker'), $this->container_type, $this->container_id)
106
- );
107
- }
108
-
109
- //Get the parser.
110
- $parser = $this->get_parser();
111
- if ( is_null($parser) ){
112
- return new WP_Error(
113
- 'parser_not_found',
114
- sprintf(__("Parser '%s' not found.", 'broken-link-checker'), $this->parser_type)
115
- );
116
- }
117
-
118
- //If the old URL isn't specified get it from the link record
119
- if ( empty($old_url) ){
120
- $old_url = $this->get_url();
121
- }
122
-
123
- //Attempt to modify the link(s)
124
- $result = $container->edit_link($this->container_field, $parser, $new_url, $old_url, $this->raw_url, $new_text);
125
- if ( is_string($result) ){
126
- //If the modification was successful, the container will return
127
- //the new raw_url for the instance. Save the URL and return true,
128
- //indicating success.
129
- $this->raw_url = $result;
130
- return true;
131
- } elseif ( is_array($result) ){
132
- //More advanced containers/parsers may return an array of values to
133
- //modify several fields at once.
134
- $allowed_fields = array('raw_url', 'link_text', 'link_context');
135
- foreach($result as $key => $value){
136
- if ( in_array($key, $allowed_fields) ){
137
- $this->$key = $value;
138
- }
139
- }
140
- return true;
141
- } else {
142
- //Otherwise, it will return an error object. In this case we'll
143
- //just pass it back to the caller and let them sort it out.
144
- return $result;
145
- }
146
- }
147
-
148
- /**
149
- * blcLinkInstance::unlink()
150
- * Remove this instance from the post/blogroll/etc. Also deletes the appropriate DB record(s).
151
- *
152
- * @return bool|WP_Error
153
- */
154
- function unlink( $url = null ) {
155
-
156
- //Get the container that contains this link
157
- $container = $this->get_container();
158
- if ( is_null($container) ){
159
- return new WP_Error(
160
- 'container_not_found',
161
- sprintf(__("Container %s[%d] not found", 'broken-link-checker'), $this->container_type, $this->container_id)
162
- );
163
- }
164
-
165
- //Get the parser.
166
- $parser = $this->get_parser();
167
- if ( is_null($parser) ){
168
- return new WP_Error(
169
- 'parser_not_found',
170
- sprintf(__("Parser '%s' not found.", 'broken-link-checker'), $this->parser_type)
171
- );
172
- }
173
-
174
- //If the old URL isn't specified get it from the link record
175
- if ( empty($url) ){
176
- $url = $this->get_url();
177
- }
178
-
179
- //Attempt to remove the link(s)
180
- return $container->unlink($this->container_field, $parser, $url, $this->raw_url);
181
- }
182
-
183
- /**
184
- * Remove the link instance record from database. Doesn't affect the thing that contains the link.
185
- *
186
- * @return mixed 1 on success, 0 if the instance wasn't found, false on error
187
- */
188
- function forget(){
189
- global $wpdb; /** @var wpdb $wpdb */
190
-
191
- if ( !empty($this->instance_id) ) {
192
- $rez = $wpdb->query( $wpdb->prepare("DELETE FROM {$wpdb->prefix}blc_instances WHERE instance_id=%d", $this->instance_id) );
193
- return $rez;
194
- } else {
195
- return false;
196
- }
197
- }
198
-
199
- /**
200
- * Store the link instance in the database.
201
- * Saving the instance will also implicitly save the link record associated with it, if it wasn't already saved.
202
- *
203
- * @return bool TRUE on success, FALSE on error
204
- */
205
- function save(){
206
- global $wpdb; /** @var wpdb $wpdb */
207
-
208
- //Refresh the locally cached link & container properties, in case
209
- //the objects have changed since they were set.
210
-
211
- if ( !is_null($this->_link) ){
212
-
213
- //If we have a link object assigned, but it's new, it won't have a DB ID yet.
214
- //We need to save the link to get the ID and be able to maintain the link <-> instance
215
- //association.
216
- if ( $this->_link->is_new ){
217
- $rez = $this->_link->save();
218
- if ( !$rez ){
219
- return false;
220
- }
221
- }
222
-
223
- $this->link_id = $this->_link->link_id;
224
- }
225
-
226
- if ( !is_null($this->_container) ){
227
- $this->container_type = $this->_container->container_type;
228
- $this->container_id = $this->_container->container_id;
229
- }
230
-
231
- //If the link is new, insert a new row into the DB. Otherwise update the existing row.
232
- if ( $this->is_new ){
233
-
234
- $q = "
235
- INSERT INTO {$wpdb->prefix}blc_instances
236
- ( link_id, container_type, container_id, container_field, parser_type, link_text, link_context, raw_url )
237
- VALUES( %d, %s, %d, %s, %s, %s, %s, %s )";
238
-
239
- $q = $wpdb->prepare(
240
- $q,
241
-
242
- $this->link_id,
243
- $this->container_type,
244
- $this->container_id,
245
- $this->container_field,
246
- $this->parser_type,
247
- $this->link_text,
248
- $this->link_context,
249
- $this->raw_url
250
- );
251
-
252
- $rez = $wpdb->query($q) !== false;
253
-
254
- if ($rez){
255
- $this->instance_id = $wpdb->insert_id;
256
- //If the instance was successfully saved then it's no longer "new".
257
- $this->is_new = !$rez;
258
- }
259
-
260
- return $rez;
261
-
262
- } else {
263
-
264
- $q = "UPDATE {$wpdb->prefix}blc_instances
265
-
266
- SET
267
- link_id = %d,
268
- container_type = %s,
269
- container_id = %d,
270
- container_field = %s,
271
- parser_type = %s,
272
- link_text = %s,
273
- link_context = %s,
274
- raw_url = %s
275
-
276
- WHERE instance_id = %d";
277
-
278
- $q = $wpdb->prepare(
279
- $q,
280
-
281
- $this->link_id,
282
- $this->container_type,
283
- $this->container_id,
284
- $this->container_field,
285
- $this->parser_type,
286
- $this->link_text,
287
- $this->link_context,
288
- $this->raw_url,
289
-
290
- $this->instance_id
291
- );
292
-
293
- $rez = $wpdb->query($q) !== false;
294
-
295
- if ($rez){
296
- //FB::info($this, "Instance updated");
297
- } else {
298
- //FB::error("DB error while updating instance {$this->instance_id} : {$wpdb->last_error}");
299
- }
300
-
301
- return $rez;
302
-
303
- }
304
- }
305
-
306
- /**
307
- * Get the URL associated with this instance.
308
- *
309
- * @return string The associated URL, or an empty string if the instance is currently not assigned to any link.
310
- */
311
- function get_url(){
312
- $link = $this->get_link();
313
-
314
- if ( !is_null($link) ){
315
- return $link->url;
316
- } else {
317
- return '';
318
- }
319
- }
320
-
321
- /**
322
- * Get the container object associated with this link instance
323
- *
324
- * @return blcContainer|null
325
- */
326
- function get_container(){
327
- if( is_null($this->_container) ){
328
- $this->_container = blcContainerHelper::get_container( array($this->container_type, $this->container_id) );
329
- }
330
-
331
- return $this->_container;
332
- }
333
-
334
- /**
335
- * Set a new container for the link instance.
336
- *
337
- * @param blcContainer $new_container
338
- * @param string $field
339
- * @return void
340
- */
341
- function set_container(&$new_container, $field = ''){
342
- $this->_container = &$new_container;
343
-
344
- $this->container_field = $field;
345
-
346
- if( !is_null($new_container) ){
347
- $this->container_type = $new_container->container_type;
348
- $this->container_id = $new_container->container_id;
349
- } else {
350
- $this->container_type = '';
351
- $this->container_id = 0;
352
- }
353
- }
354
-
355
- /**
356
- * Get the parser associated with this link instance.
357
- *
358
- * @return blcParser|null
359
- */
360
- function get_parser(){
361
- if ( is_null($this->_parser) ){
362
- $this->_parser = blcParserHelper::get_parser($this->parser_type);
363
- }
364
-
365
- return $this->_parser;
366
- }
367
-
368
- /**
369
- * Set a new parser fo this link instance.
370
- *
371
- * @param blcParser|null $new_parser
372
- * @return void
373
- */
374
- function set_parser(&$new_parser){
375
- $this->_parser = &$new_parser;
376
-
377
- if ( is_null($new_parser) ){
378
- $this->parser_type = '';
379
- } else {
380
- $this->parser_type = $new_parser->parser_type;
381
- }
382
- }
383
-
384
- /**
385
- * Get the link object associated with this link intance.
386
- *
387
- * @return blcLink|null
388
- */
389
- function get_link(){
390
- if ( !is_null($this->_link) ){
391
- return $this->_link;
392
- }
393
-
394
- if ( empty($this->link_id) ) {
395
- return null;
396
- }
397
-
398
- $this->_link = new blcLink($this->link_id);
399
- return $this->_link;
400
- }
401
-
402
- /**
403
- * Set the link associated with this link instance.
404
- *
405
- * @param blcLink $new_link
406
- * @return void
407
- */
408
- function set_link($new_link){
409
- $this->_link = $new_link;
410
-
411
- if ( is_null($new_link) ){
412
- $this->link_id = 0;
413
- } else {
414
- $this->link_id = $new_link->link_id;
415
- }
416
- }
417
-
418
- /**
419
- * Get the link text for printing in the "Broken Links" table.
420
- *
421
- * @param string $context How to filter the link text. Optional, defaults to 'display'.
422
- * @return string HTML
423
- */
424
- function ui_get_link_text($context = 'display'){
425
- $parser = $this->get_parser();
426
-
427
- if ( !is_null($parser) ){
428
- $text = $parser->ui_get_link_text($this, $context);
429
- } else {
430
- $text = strip_tags($this->link_text);
431
- }
432
-
433
- if ( empty($text) ){
434
- $text = "<em>(None)</em>";
435
- }
436
-
437
- return $text;
438
- }
439
-
440
- /**
441
- * Get action links that should be displayed in the "Source" column of the "Broken Links" table.
442
- *
443
- * @return array An array of HTML links.
444
- */
445
- function ui_get_action_links(){
446
- //The container is responsible for generating the links.
447
- $container = $this->get_container();
448
- if ( !is_null($container) ){
449
- return $container->ui_get_action_links($this->container_field);
450
- } else {
451
- //No valid container = no links.
452
- return array();
453
- }
454
- }
455
-
456
- /**
457
- * Get the HTML describing the "source" of the instance. For example, for links found in posts,
458
- * this could be the post title.
459
- *
460
- * @param string $context How to filter the output. Optional, defaults to 'display'.
461
- * @return string HTML
462
- */
463
- function ui_get_source($context = 'display'){
464
- //The container is also responsible for generating the "Source" column HTML.
465
- $container = $this->get_container();
466
- if ( !is_null($container) ){
467
- return $container->ui_get_source($this->container_field, $context);
468
- } else {
469
- //No valid container = generate some bare-bones debug output.
470
- return sprintf('%s[%d] : %s', $this->container_type, $this->container_id, $this->container_field);
471
- }
472
- }
473
-
474
- /**
475
- * Check if the link text associated with this instance can be edited.
476
- *
477
- * @return bool
478
- */
479
- public function is_link_text_editable() {
480
- $parser = $this->get_parser();
481
- if ( $parser === null ) {
482
- return false;
483
- }
484
- return $parser->is_link_text_editable();
485
- }
486
-
487
- /**
488
- * Check if the URL of this instance can be edited.
489
- *
490
- * @return bool
491
- */
492
- public function is_url_editable() {
493
- $parser = $this->get_parser();
494
- if ( $parser === null ) {
495
- return false;
496
- }
497
- return $parser->is_url_editable();
498
- }
499
-
500
- }
501
-
502
- /**
503
- * Get all link instances associated with one or more links.
504
- *
505
- * @param array $link_ids Array of link IDs.
506
- * @param string $purpose An optional code indicating how the instances will be used. Available predefined constants : BLC_FOR_DISPLAY, BLC_FOR_EDITING
507
- * @param bool $load_containers Preload containers regardless of purpose. Defaults to false.
508
- * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose. Defaults to false.
509
- * @param bool $include_invalid Include instances that refer to not-loaded containers or parsers. Defaults to false.
510
- * @return blcLinkInstance[] An array indexed by link ID. Each item of the array will be an array of blcLinkInstance objects.
511
- */
512
- function blc_get_instances( $link_ids, $purpose = '', $load_containers = false, $load_wrapped_objects = false, $include_invalid = false ){
513
- global $wpdb; /** @var wpdb $wpdb */
514
-
515
- if ( empty($link_ids) ){
516
- return array();
517
- }
518
-
519
- $link_ids_in = implode(', ', $link_ids);
520
-
521
- $q = "SELECT * FROM {$wpdb->prefix}blc_instances WHERE link_id IN ($link_ids_in)";
522
-
523
- //Skip instances that reference containers or parsers that aren't currently loaded
524
- if ( !$include_invalid ){
525
- $manager = blcModuleManager::getInstance();
526
- $active_containers = $manager->get_escaped_ids('container');
527
- $active_parsers = $manager->get_escaped_ids('parser');
528
-
529
- $q .= " AND container_type IN ({$active_containers}) ";
530
- $q .= " AND parser_type IN ({$active_parsers}) ";
531
- }
532
-
533
- $results = $wpdb->get_results($q, ARRAY_A);
534
-
535
- if ( empty($results) ) {
536
- return array();
537
- }
538
-
539
- //Also retrieve the containers, if it could be useful.
540
- $load_containers = $load_containers || in_array( $purpose, array(BLC_FOR_DISPLAY, BLC_FOR_EDITING) );
541
- if ( $load_containers ){
542
- //Collect a list of (container_type, container_id) pairs
543
- $container_ids = array();
544
-
545
- foreach($results as $result){
546
- array_push(
547
- $container_ids,
548
- array( $result['container_type'], intval($result['container_id']) )
549
- );
550
- }
551
- $containers = blcContainerHelper::get_containers($container_ids, $purpose, '', $load_wrapped_objects);
552
- }
553
-
554
- //Create an object for each instance and group them by link ID
555
- $instances = array();
556
- foreach ($results as $result){
557
- $instance = new blcLinkInstance($result);
558
-
559
- //Assign a container to the link instance, if available
560
- if( $load_containers && !empty($containers) ){
561
- $key = $instance->container_type . '|' . $instance->container_id;
562
- if( isset($containers[$key]) ){
563
- $instance->_container = $containers[$key];
564
- }
565
- }
566
-
567
- if ( isset($instances[$instance->link_id]) ){
568
- array_push( $instances[$instance->link_id], $instance );
569
- } else {
570
- $instances[$instance->link_id] = array($instance);
571
- }
572
- }
573
-
574
- return $instances;
575
- }
576
-
577
- /**
578
- * Get the number of instances that reference only currently loaded containers and parsers.
579
- *
580
- * @return int
581
- */
582
- function blc_get_usable_instance_count(){
583
- global $wpdb; /** @var wpdb $wpdb */
584
-
585
- $q = "SELECT COUNT(instance_id) FROM {$wpdb->prefix}blc_instances WHERE 1";
586
-
587
- //Skip instances that reference containers or parsers that aren't currently loaded
588
- $manager = blcModuleManager::getInstance();
589
- $active_containers = $manager->get_escaped_ids('container');
590
- $active_parsers = $manager->get_escaped_ids('parser');
591
-
592
- $q .= " AND container_type IN ({$active_containers}) ";
593
- $q .= " AND parser_type IN ({$active_parsers}) ";
594
-
595
- return $wpdb->get_var($q);
596
- }
597
-
598
- /**
599
- * Remove instances that reference invalid containers or containers/parsers that are not currently loaded
600
- *
601
- * @return bool
602
- */
603
- function blc_cleanup_instances(){
604
- global $wpdb; /** @var wpdb $wpdb */
605
- global $blclog;
606
-
607
- //Delete all instances that reference non-existent containers
608
- $start = microtime(true);
609
- $q = "DELETE instances.*
610
- FROM
611
- {$wpdb->prefix}blc_instances AS instances LEFT JOIN {$wpdb->prefix}blc_synch AS synch
612
- ON instances.container_type = synch.container_type AND instances.container_id = synch.container_id
613
- WHERE
614
- synch.container_id IS NULL";
615
- $rez = $wpdb->query($q);
616
- $elapsed = microtime(true) - $start;
617
- $blclog->log(sprintf('... %d instances deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
618
-
619
- //Delete instances that reference containers and parsers that are no longer active
620
- $start = microtime(true);
621
- $manager = blcModuleManager::getInstance();
622
- $active_containers = $manager->get_escaped_ids('container');
623
- $active_parsers = $manager->get_escaped_ids('parser');
624
-
625
- $q = "DELETE instances.*
626
- FROM {$wpdb->prefix}blc_instances AS instances
627
- WHERE
628
- instances.container_type NOT IN ({$active_containers}) OR
629
- instances.parser_type NOT IN ({$active_parsers})";
630
- $rez2 = $wpdb->query($q);
631
- $elapsed = microtime(true) - $start;
632
- $blclog->log(sprintf('... %d more instances deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
633
-
634
- return ($rez !== false) && ($rez2 !== false);
635
- }
636
-
637
-
638
- }//class_exists
639
-
1
+ <?php
2
+
3
+ /**
4
+ * @author W-Shadow
5
+ * @copyright 2009
6
+ */
7
+
8
+ if (!class_exists('blcLinkInstance')) {
9
+ class blcLinkInstance {
10
+
11
+ //Object state
12
+ var $is_new = false;
13
+
14
+ //DB fields
15
+ var $instance_id = 0;
16
+ var $link_id = 0;
17
+
18
+ var $container_id = 0;
19
+ var $container_type = '';
20
+ var $container_field = '';
21
+
22
+ var $parser_type = '';
23
+
24
+ var $link_text = '';
25
+ var $link_context = '';
26
+ var $raw_url = '';
27
+
28
+ /** @var blcContainer */
29
+ var $_container = null;
30
+ var $_parser = null;
31
+ /** @var blcLink|null */
32
+ var $_link = null;
33
+
34
+ /**
35
+ * blcLinkInstance::__construct()
36
+ * Class constructor
37
+ *
38
+ * @param int|array $arg Either the instance ID or an associate array representing the instance's DB record. Should be NULL for new instances.
39
+ */
40
+ function __construct($arg = null){
41
+ global $wpdb; /** @var wpdb $wpdb */
42
+
43
+ if (is_int($arg)){
44
+ //Load an instance with ID = $arg from the DB.
45
+ $q = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}blc_instances WHERE instance_id=%d LIMIT 1", $arg);
46
+ $arr = $wpdb->get_row( $q, ARRAY_A );
47
+
48
+ if ( is_array($arr) ){ //Loaded successfully
49
+ $this->set_values($arr);
50
+ } else {
51
+ //Link instance not found. The object is invalid.
52
+ }
53
+
54
+ } else if (is_array($arg)){
55
+ $this->set_values($arg);
56
+
57
+ //Is this a new instance?
58
+ $this->is_new = empty($this->instance_id);
59
+
60
+ } else {
61
+ $this->is_new = true;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * blcLinkInstance::blcLinkInstance()
67
+ * Old-style constructor for PHP 4. Do not use.
68
+ *
69
+ * @param mixed $arg
70
+ * @return void
71
+ */
72
+ function blcLinkInstance($arg = null){
73
+ $this->__construct($arg);
74
+ }
75
+
76
+ /**
77
+ * blcLinkInstance::set_values()
78
+ * Set property values to the ones provided in an array (doesn't sanitize).
79
+ *
80
+ * @param array $arr An associative array
81
+ * @return void
82
+ */
83
+ function set_values($arr){
84
+ foreach( $arr as $key => $value ){
85
+ $this->$key = $value;
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Replace this instance's URL with a new one.
91
+ * Warning : this shouldn't be called directly. Use blcLink->edit() instead.
92
+ *
93
+ * @param string $new_url
94
+ * @param string $old_url
95
+ * @param string $new_text
96
+ * @return bool|WP_Error True on success, or an instance of WP_Error if something went wrong.
97
+ */
98
+ function edit($new_url, $old_url = '', $new_text = null){
99
+
100
+ //Get the container that contains this link
101
+ $container = $this->get_container();
102
+ if ( is_null($container) ){
103
+ return new WP_Error(
104
+ 'container_not_found',
105
+ sprintf(__("Container %s[%d] not found", 'broken-link-checker'), $this->container_type, $this->container_id)
106
+ );
107
+ }
108
+
109
+ //Get the parser.
110
+ $parser = $this->get_parser();
111
+ if ( is_null($parser) ){
112
+ return new WP_Error(
113
+ 'parser_not_found',
114
+ sprintf(__("Parser '%s' not found.", 'broken-link-checker'), $this->parser_type)
115
+ );
116
+ }
117
+
118
+ //If the old URL isn't specified get it from the link record
119
+ if ( empty($old_url) ){
120
+ $old_url = $this->get_url();
121
+ }
122
+
123
+ //Attempt to modify the link(s)
124
+ $result = $container->edit_link($this->container_field, $parser, $new_url, $old_url, $this->raw_url, $new_text);
125
+ if ( is_string($result) ){
126
+ //If the modification was successful, the container will return
127
+ //the new raw_url for the instance. Save the URL and return true,
128
+ //indicating success.
129
+ $this->raw_url = $result;
130
+ return true;
131
+ } elseif ( is_array($result) ){
132
+ //More advanced containers/parsers may return an array of values to
133
+ //modify several fields at once.
134
+ $allowed_fields = array('raw_url', 'link_text', 'link_context');
135
+ foreach($result as $key => $value){
136
+ if ( in_array($key, $allowed_fields) ){
137
+ $this->$key = $value;
138
+ }
139
+ }
140
+ return true;
141
+ } else {
142
+ //Otherwise, it will return an error object. In this case we'll
143
+ //just pass it back to the caller and let them sort it out.
144
+ return $result;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * blcLinkInstance::unlink()
150
+ * Remove this instance from the post/blogroll/etc. Also deletes the appropriate DB record(s).
151
+ *
152
+ * @return bool|WP_Error
153
+ */
154
+ function unlink( $url = null ) {
155
+
156
+ //Get the container that contains this link
157
+ $container = $this->get_container();
158
+ if ( is_null($container) ){
159
+ return new WP_Error(
160
+ 'container_not_found',
161
+ sprintf(__("Container %s[%d] not found", 'broken-link-checker'), $this->container_type, $this->container_id)
162
+ );
163
+ }
164
+
165
+ //Get the parser.
166
+ $parser = $this->get_parser();
167
+ if ( is_null($parser) ){
168
+ return new WP_Error(
169
+ 'parser_not_found',
170
+ sprintf(__("Parser '%s' not found.", 'broken-link-checker'), $this->parser_type)
171
+ );
172
+ }
173
+
174
+ //If the old URL isn't specified get it from the link record
175
+ if ( empty($url) ){
176
+ $url = $this->get_url();
177
+ }
178
+
179
+ //Attempt to remove the link(s)
180
+ return $container->unlink($this->container_field, $parser, $url, $this->raw_url);
181
+ }
182
+
183
+ /**
184
+ * Remove the link instance record from database. Doesn't affect the thing that contains the link.
185
+ *
186
+ * @return mixed 1 on success, 0 if the instance wasn't found, false on error
187
+ */
188
+ function forget(){
189
+ global $wpdb; /** @var wpdb $wpdb */
190
+
191
+ if ( !empty($this->instance_id) ) {
192
+ $rez = $wpdb->query( $wpdb->prepare("DELETE FROM {$wpdb->prefix}blc_instances WHERE instance_id=%d", $this->instance_id) );
193
+ return $rez;
194
+ } else {
195
+ return false;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Store the link instance in the database.
201
+ * Saving the instance will also implicitly save the link record associated with it, if it wasn't already saved.
202
+ *
203
+ * @return bool TRUE on success, FALSE on error
204
+ */
205
+ function save(){
206
+ global $wpdb; /** @var wpdb $wpdb */
207
+
208
+ //Refresh the locally cached link & container properties, in case
209
+ //the objects have changed since they were set.
210
+
211
+ if ( !is_null($this->_link) ){
212
+
213
+ //If we have a link object assigned, but it's new, it won't have a DB ID yet.
214
+ //We need to save the link to get the ID and be able to maintain the link <-> instance
215
+ //association.
216
+ if ( $this->_link->is_new ){
217
+ $rez = $this->_link->save();
218
+ if ( !$rez ){
219
+ return false;
220
+ }
221
+ }
222
+
223
+ $this->link_id = $this->_link->link_id;
224
+ }
225
+
226
+ if ( !is_null($this->_container) ){
227
+ $this->container_type = $this->_container->container_type;
228
+ $this->container_id = $this->_container->container_id;
229
+ }
230
+
231
+ //If the link is new, insert a new row into the DB. Otherwise update the existing row.
232
+ if ( $this->is_new ){
233
+
234
+ $q = "
235
+ INSERT INTO {$wpdb->prefix}blc_instances
236
+ ( link_id, container_type, container_id, container_field, parser_type, link_text, link_context, raw_url )
237
+ VALUES( %d, %s, %d, %s, %s, %s, %s, %s )";
238
+
239
+ $q = $wpdb->prepare(
240
+ $q,
241
+
242
+ $this->link_id,
243
+ $this->container_type,
244
+ $this->container_id,
245
+ $this->container_field,
246
+ $this->parser_type,
247
+ $this->link_text,
248
+ $this->link_context,
249
+ $this->raw_url
250
+ );
251
+
252
+ $rez = $wpdb->query($q) !== false;
253
+
254
+ if ($rez){
255
+ $this->instance_id = $wpdb->insert_id;
256
+ //If the instance was successfully saved then it's no longer "new".
257
+ $this->is_new = !$rez;
258
+ }
259
+
260
+ return $rez;
261
+
262
+ } else {
263
+
264
+ $q = "UPDATE {$wpdb->prefix}blc_instances
265
+
266
+ SET
267
+ link_id = %d,
268
+ container_type = %s,
269
+ container_id = %d,
270
+ container_field = %s,
271
+ parser_type = %s,
272
+ link_text = %s,
273
+ link_context = %s,
274
+ raw_url = %s
275
+
276
+ WHERE instance_id = %d";
277
+
278
+ $q = $wpdb->prepare(
279
+ $q,
280
+
281
+ $this->link_id,
282
+ $this->container_type,
283
+ $this->container_id,
284
+ $this->container_field,
285
+ $this->parser_type,
286
+ $this->link_text,
287
+ $this->link_context,
288
+ $this->raw_url,
289
+
290
+ $this->instance_id
291
+ );
292
+
293
+ $rez = $wpdb->query($q) !== false;
294
+
295
+ if ($rez){
296
+ //FB::info($this, "Instance updated");
297
+ } else {
298
+ //FB::error("DB error while updating instance {$this->instance_id} : {$wpdb->last_error}");
299
+ }
300
+
301
+ return $rez;
302
+
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Get the URL associated with this instance.
308
+ *
309
+ * @return string The associated URL, or an empty string if the instance is currently not assigned to any link.
310
+ */
311
+ function get_url(){
312
+ $link = $this->get_link();
313
+
314
+ if ( !is_null($link) ){
315
+ return $link->url;
316
+ } else {
317
+ return '';
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Get the container object associated with this link instance
323
+ *
324
+ * @return blcContainer|null
325
+ */
326
+ function get_container(){
327
+ if( is_null($this->_container) ){
328
+ $this->_container = blcContainerHelper::get_container( array($this->container_type, $this->container_id) );
329
+ }
330
+
331
+ return $this->_container;
332
+ }
333
+
334
+ /**
335
+ * Set a new container for the link instance.
336
+ *
337
+ * @param blcContainer $new_container
338
+ * @param string $field
339
+ * @return void
340
+ */
341
+ function set_container(&$new_container, $field = ''){
342
+ $this->_container = &$new_container;
343
+
344
+ $this->container_field = $field;
345
+
346
+ if( !is_null($new_container) ){
347
+ $this->container_type = $new_container->container_type;
348
+ $this->container_id = $new_container->container_id;
349
+ } else {
350
+ $this->container_type = '';
351
+ $this->container_id = 0;
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Get the parser associated with this link instance.
357
+ *
358
+ * @return blcParser|null
359
+ */
360
+ function get_parser(){
361
+ if ( is_null($this->_parser) ){
362
+ $this->_parser = blcParserHelper::get_parser($this->parser_type);
363
+ }
364
+
365
+ return $this->_parser;
366
+ }
367
+
368
+ /**
369
+ * Set a new parser fo this link instance.
370
+ *
371
+ * @param blcParser|null $new_parser
372
+ * @return void
373
+ */
374
+ function set_parser(&$new_parser){
375
+ $this->_parser = &$new_parser;
376
+
377
+ if ( is_null($new_parser) ){
378
+ $this->parser_type = '';
379
+ } else {
380
+ $this->parser_type = $new_parser->parser_type;
381
+ }
382
+ }
383
+
384
+ /**
385
+ * Get the link object associated with this link intance.
386
+ *
387
+ * @return blcLink|null
388
+ */
389
+ function get_link(){
390
+ if ( !is_null($this->_link) ){
391
+ return $this->_link;
392
+ }
393
+
394
+ if ( empty($this->link_id) ) {
395
+ return null;
396
+ }
397
+
398
+ $this->_link = new blcLink($this->link_id);
399
+ return $this->_link;
400
+ }
401
+
402
+ /**
403
+ * Set the link associated with this link instance.
404
+ *
405
+ * @param blcLink $new_link
406
+ * @return void
407
+ */
408
+ function set_link($new_link){
409
+ $this->_link = $new_link;
410
+
411
+ if ( is_null($new_link) ){
412
+ $this->link_id = 0;
413
+ } else {
414
+ $this->link_id = $new_link->link_id;
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Get the link text for printing in the "Broken Links" table.
420
+ *
421
+ * @param string $context How to filter the link text. Optional, defaults to 'display'.
422
+ * @return string HTML
423
+ */
424
+ function ui_get_link_text($context = 'display'){
425
+ $parser = $this->get_parser();
426
+
427
+ if ( !is_null($parser) ){
428
+ $text = $parser->ui_get_link_text($this, $context);
429
+ } else {
430
+ $text = strip_tags($this->link_text);
431
+ }
432
+
433
+ if ( empty($text) ){
434
+ $text = "<em>(None)</em>";
435
+ }
436
+
437
+ return $text;
438
+ }
439
+
440
+ /**
441
+ * Get action links that should be displayed in the "Source" column of the "Broken Links" table.
442
+ *
443
+ * @return array An array of HTML links.
444
+ */
445
+ function ui_get_action_links(){
446
+ //The container is responsible for generating the links.
447
+ $container = $this->get_container();
448
+ if ( !is_null($container) ){
449
+ return $container->ui_get_action_links($this->container_field);
450
+ } else {
451
+ //No valid container = no links.
452
+ return array();
453
+ }
454
+ }
455
+
456
+ /**
457
+ * Get the HTML describing the "source" of the instance. For example, for links found in posts,
458
+ * this could be the post title.
459
+ *
460
+ * @param string $context How to filter the output. Optional, defaults to 'display'.
461
+ * @return string HTML
462
+ */
463
+ function ui_get_source($context = 'display'){
464
+ //The container is also responsible for generating the "Source" column HTML.
465
+ $container = $this->get_container();
466
+ if ( !is_null($container) ){
467
+ return $container->ui_get_source($this->container_field, $context);
468
+ } else {
469
+ //No valid container = generate some bare-bones debug output.
470
+ return sprintf('%s[%d] : %s', $this->container_type, $this->container_id, $this->container_field);
471
+ }
472
+ }
473
+
474
+ /**
475
+ * Check if the link text associated with this instance can be edited.
476
+ *
477
+ * @return bool
478
+ */
479
+ public function is_link_text_editable() {
480
+ $parser = $this->get_parser();
481
+ if ( $parser === null ) {
482
+ return false;
483
+ }
484
+ return $parser->is_link_text_editable();
485
+ }
486
+
487
+ /**
488
+ * Check if the URL of this instance can be edited.
489
+ *
490
+ * @return bool
491
+ */
492
+ public function is_url_editable() {
493
+ $parser = $this->get_parser();
494
+ if ( $parser === null ) {
495
+ return false;
496
+ }
497
+ return $parser->is_url_editable();
498
+ }
499
+
500
+ }
501
+
502
+ /**
503
+ * Get all link instances associated with one or more links.
504
+ *
505
+ * @param array $link_ids Array of link IDs.
506
+ * @param string $purpose An optional code indicating how the instances will be used. Available predefined constants : BLC_FOR_DISPLAY, BLC_FOR_EDITING
507
+ * @param bool $load_containers Preload containers regardless of purpose. Defaults to false.
508
+ * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose. Defaults to false.
509
+ * @param bool $include_invalid Include instances that refer to not-loaded containers or parsers. Defaults to false.
510
+ * @return blcLinkInstance[] An array indexed by link ID. Each item of the array will be an array of blcLinkInstance objects.
511
+ */
512
+ function blc_get_instances( $link_ids, $purpose = '', $load_containers = false, $load_wrapped_objects = false, $include_invalid = false ){
513
+ global $wpdb; /** @var wpdb $wpdb */
514
+
515
+ if ( empty($link_ids) ){
516
+ return array();
517
+ }
518
+
519
+ $link_ids_in = implode(', ', $link_ids);
520
+
521
+ $q = "SELECT * FROM {$wpdb->prefix}blc_instances WHERE link_id IN ($link_ids_in)";
522
+
523
+ //Skip instances that reference containers or parsers that aren't currently loaded
524
+ if ( !$include_invalid ){
525
+ $manager = blcModuleManager::getInstance();
526
+ $active_containers = $manager->get_escaped_ids('container');
527
+ $active_parsers = $manager->get_escaped_ids('parser');
528
+
529
+ $q .= " AND container_type IN ({$active_containers}) ";
530
+ $q .= " AND parser_type IN ({$active_parsers}) ";
531
+ }
532
+
533
+ $results = $wpdb->get_results($q, ARRAY_A);
534
+
535
+ if ( empty($results) ) {
536
+ return array();
537
+ }
538
+
539
+ //Also retrieve the containers, if it could be useful.
540
+ $load_containers = $load_containers || in_array( $purpose, array(BLC_FOR_DISPLAY, BLC_FOR_EDITING) );
541
+ if ( $load_containers ){
542
+ //Collect a list of (container_type, container_id) pairs
543
+ $container_ids = array();
544
+
545
+ foreach($results as $result){
546
+ array_push(
547
+ $container_ids,
548
+ array( $result['container_type'], intval($result['container_id']) )
549
+ );
550
+ }
551
+ $containers = blcContainerHelper::get_containers($container_ids, $purpose, '', $load_wrapped_objects);
552
+ }
553
+
554
+ //Create an object for each instance and group them by link ID
555
+ $instances = array();
556
+ foreach ($results as $result){
557
+ $instance = new blcLinkInstance($result);
558
+
559
+ //Assign a container to the link instance, if available
560
+ if( $load_containers && !empty($containers) ){
561
+ $key = $instance->container_type . '|' . $instance->container_id;
562
+ if( isset($containers[$key]) ){
563
+ $instance->_container = $containers[$key];
564
+ }
565
+ }
566
+
567
+ if ( isset($instances[$instance->link_id]) ){
568
+ array_push( $instances[$instance->link_id], $instance );
569
+ } else {
570
+ $instances[$instance->link_id] = array($instance);
571
+ }
572
+ }
573
+
574
+ return $instances;
575
+ }
576
+
577
+ /**
578
+ * Get the number of instances that reference only currently loaded containers and parsers.
579
+ *
580
+ * @return int
581
+ */
582
+ function blc_get_usable_instance_count(){
583
+ global $wpdb; /** @var wpdb $wpdb */
584
+
585
+ $q = "SELECT COUNT(instance_id) FROM {$wpdb->prefix}blc_instances WHERE 1";
586
+
587
+ //Skip instances that reference containers or parsers that aren't currently loaded
588
+ $manager = blcModuleManager::getInstance();
589
+ $active_containers = $manager->get_escaped_ids('container');
590
+ $active_parsers = $manager->get_escaped_ids('parser');
591
+
592
+ $q .= " AND container_type IN ({$active_containers}) ";
593
+ $q .= " AND parser_type IN ({$active_parsers}) ";
594
+
595
+ return $wpdb->get_var($q);
596
+ }
597
+
598
+ /**
599
+ * Remove instances that reference invalid containers or containers/parsers that are not currently loaded
600
+ *
601
+ * @return bool
602
+ */
603
+ function blc_cleanup_instances(){
604
+ global $wpdb; /** @var wpdb $wpdb */
605
+ global $blclog;
606
+
607
+ //Delete all instances that reference non-existent containers
608
+ $start = microtime(true);
609
+ $q = "DELETE instances.*
610
+ FROM
611
+ {$wpdb->prefix}blc_instances AS instances LEFT JOIN {$wpdb->prefix}blc_synch AS synch
612
+ ON instances.container_type = synch.container_type AND instances.container_id = synch.container_id
613
+ WHERE
614
+ synch.container_id IS NULL";
615
+ $rez = $wpdb->query($q);
616
+ $elapsed = microtime(true) - $start;
617
+ $blclog->log(sprintf('... %d instances deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
618
+
619
+ //Delete instances that reference containers and parsers that are no longer active
620
+ $start = microtime(true);
621
+ $manager = blcModuleManager::getInstance();
622
+ $active_containers = $manager->get_escaped_ids('container');
623
+ $active_parsers = $manager->get_escaped_ids('parser');
624
+
625
+ $q = "DELETE instances.*
626
+ FROM {$wpdb->prefix}blc_instances AS instances
627
+ WHERE
628
+ instances.container_type NOT IN ({$active_containers}) OR
629
+ instances.parser_type NOT IN ({$active_parsers})";
630
+ $rez2 = $wpdb->query($q);
631
+ $elapsed = microtime(true) - $start;
632
+ $blclog->log(sprintf('... %d more instances deleted in %.3f seconds', $wpdb->rows_affected, $elapsed));
633
+
634
+ return ($rez !== false) && ($rez2 !== false);
635
+ }
636
+
637
+
638
+ }//class_exists
639
+
includes/link-query.php CHANGED
@@ -1,866 +1,870 @@
1
- <?php
2
-
3
- /**
4
- * Class for querying, sorting and filtering links.
5
- * Used as a singleton.
6
- *
7
- * @package Broken Link Checker
8
- * @access public
9
- */
10
- class blcLinkQuery {
11
-
12
- var $native_filters;
13
- var $search_filter;
14
- var $custom_filters = array();
15
-
16
- var $valid_url_params = array();
17
-
18
- function __construct(){
19
- //Init. the available native filters.
20
- $this->native_filters = array(
21
- 'all' => array(
22
- 'params' => array(
23
- 'where_expr' => '1',
24
- ),
25
- 'name' => __('All', 'broken-link-checker'),
26
- 'heading' => __('Detected Links', 'broken-link-checker'),
27
- 'heading_zero' => __('No links found (yet)', 'broken-link-checker'),
28
- 'native' => true,
29
- ),
30
-
31
- 'broken' => array(
32
- 'params' => array(
33
- 'where_expr' => '( broken = 1 )',
34
- 's_include_dismissed' => false,
35
- ),
36
- 'name' => __('Broken', 'broken-link-checker'),
37
- 'heading' => __('Broken Links', 'broken-link-checker'),
38
- 'heading_zero' => __('No broken links found', 'broken-link-checker'),
39
- 'native' => true,
40
- ),
41
- 'warnings' => array(
42
- 'params' => array(
43
- 'where_expr' => '( warning = 1 )',
44
- 's_include_dismissed' => false,
45
- ),
46
- 'name' => _x('Warnings', 'filter name', 'broken-link-checker'),
47
- 'heading' => __('Warnings', 'filter heading', 'broken-link-checker'),
48
- 'heading_zero' => __('No warnings found', 'broken-link-checker'),
49
- 'native' => true,
50
- ),
51
- 'redirects' => array(
52
- 'params' => array(
53
- 'where_expr' => '( redirect_count > 0 )',
54
- 's_include_dismissed' => false,
55
- ),
56
- 'name' => __('Redirects', 'broken-link-checker'),
57
- 'heading' => __('Redirected Links', 'broken-link-checker'),
58
- 'heading_zero' => __('No redirects found', 'broken-link-checker'),
59
- 'native' => true,
60
- ),
61
-
62
- 'dismissed' => array(
63
- 'params' => array(
64
- 'where_expr' => '( dismissed = 1 )',
65
- ),
66
- 'name' => __('Dismissed', 'broken-link-checker'),
67
- 'heading' => __('Dismissed Links', 'broken-link-checker'),
68
- 'heading_zero' => __('No dismissed links found', 'broken-link-checker'),
69
- 'native' => true,
70
- ),
71
- );
72
-
73
- //The user can turn off warnings. In that case, all errors will show up in the "broken" filter instead.
74
- $conf = blc_get_configuration();
75
- if ( !$conf->get('warnings_enabled') ) {
76
- unset($this->native_filters['warnings']);
77
- }
78
-
79
- //Create the special "search" filter
80
- $this->search_filter = array(
81
- 'name' => __('Search', 'broken-link-checker'),
82
- 'heading' => __('Search Results', 'broken-link-checker'),
83
- 'heading_zero' => __('No links found for your query', 'broken-link-checker'),
84
- 'params' => array(),
85
- 'use_url_params' => true,
86
- 'hidden' => true,
87
- );
88
-
89
- //These search arguments may be passed via the URL if the filter's 'use_url_params' field is set to True.
90
- //They map to the fields of the search form on the Tools -> Broken Links page. Only these arguments
91
- //can be used in user-defined filters.
92
- $this->valid_url_params = array(
93
- 's_link_text',
94
- 's_link_url',
95
- 's_parser_type',
96
- 's_container_type',
97
- 's_link_type',
98
- 's_http_code',
99
- 's_filter',
100
- );
101
- }
102
-
103
- static function getInstance(){
104
- static $instance = null;
105
- if ( is_null($instance) ){
106
- $instance = new blcLinkQuery;
107
- }
108
- return $instance;
109
- }
110
-
111
- /**
112
- * Load and return the list of user-defined link filters.
113
- *
114
- * @return array An array of custom filter definitions. If there are no custom filters defined returns an empty array.
115
- */
116
- function load_custom_filters(){
117
- global $wpdb; /** @var wpdb $wpdb */
118
-
119
- $filter_data = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}blc_filters ORDER BY name ASC", ARRAY_A);
120
- $filters = array();
121
-
122
- if ( !empty($filter_data) ) {
123
- foreach($filter_data as $data){
124
- wp_parse_str($data['params'], $params);
125
-
126
- $filters[ 'f'.$data['id'] ] = array(
127
- 'name' => $data['name'],
128
- 'params' => $params,
129
- 'heading' => ucwords($data['name']),
130
- 'heading_zero' => __('No links found for your query', 'broken-link-checker'),
131
- 'custom' => true,
132
- );
133
- }
134
- }
135
-
136
- $this->custom_filters = $filters;
137
-
138
- return $filters;
139
- }
140
-
141
- /**
142
- * Add a custom link filter.
143
- *
144
- * @param string $name Filter name.
145
- * @param string|array $params Filter params. Either as a query string, or an array.
146
- * @return string|bool The ID of the newly added filter, or False.
147
- */
148
- function create_custom_filter($name, $params){
149
- global $wpdb; /** @var wpdb $wpdb */
150
-
151
- if ( is_array($params) ){
152
- $params = http_build_query($params, null, '&');
153
- }
154
-
155
- //Save the new filter
156
- $q = $wpdb->prepare(
157
- "INSERT INTO {$wpdb->prefix}blc_filters(name, params) VALUES (%s, %s)",
158
- $name, $params
159
- );
160
-
161
- if ( $wpdb->query($q) !== false ){
162
- $filter_id = 'f'.$wpdb->insert_id;
163
- return $filter_id;
164
- } else {
165
- return false;
166
- }
167
- }
168
-
169
- /**
170
- * Delete a custom filter
171
- *
172
- * @param string $filter_id
173
- * @return bool True on success, False if a database error occured.
174
- */
175
- function delete_custom_filter($filter_id){
176
- global $wpdb; /** @var wpdb $wpdb */
177
-
178
- if ( !isset($filter_id) ) {
179
- $filter_id = $_POST['filter_id'];
180
- }
181
- //Remove the "f" character from the filter ID to get its database key
182
- $filter_id = intval(ltrim($filter_id, 'f'));
183
-
184
- //Try to delete the filter
185
- $q = $wpdb->prepare("DELETE FROM {$wpdb->prefix}blc_filters WHERE id = %d", $filter_id);
186
- if ( $wpdb->query($q) !== false ){
187
- return true;
188
- } else {
189
- return false;
190
- }
191
- }
192
-
193
- function get_filters(){
194
- $filters = array_merge($this->native_filters, $this->custom_filters);
195
- $filters['search'] = $this->search_filter;
196
- return $filters;
197
- }
198
-
199
- /**
200
- * Get a link search filter by filter ID.
201
- *
202
- * @param string $filter_id
203
- * @return array|null
204
- */
205
- function get_filter($filter_id){
206
- $filters = $this->get_filters();
207
- if ( isset($filters[$filter_id]) ){
208
- return $filters[$filter_id];
209
- } else {
210
- return null;
211
- }
212
- }
213
-
214
- /**
215
- * Get link search parameters from the specified filter.
216
- *
217
- * @param array $filter
218
- * @return array An array of parameters suitable for use with blcLinkQuery::get_links()
219
- */
220
- function get_search_params( $filter = null ){
221
- //If present, the filter's parameters may be saved either as an array or a string.
222
- $params = array();
223
- if ( !empty($filter) && !empty($filter['params']) ){
224
- $params = $filter['params'];
225
- if ( is_string( $params ) ){
226
- wp_parse_str($params, $params);
227
- }
228
- }
229
-
230
- //Merge in the parameters from the current request, if required
231
- if ( isset($filter['use_url_params']) && $filter['use_url_params'] ){
232
- $params = array_merge($params, $this->get_url_search_params());
233
- }
234
-
235
- return $params;
236
- }
237
-
238
- /**
239
- * Extract search query parameters from the current URL
240
- *
241
- * @return array
242
- */
243
- function get_url_search_params(){
244
- $url_params = array();
245
- foreach ($_GET as $param => $value){
246
- if ( in_array($param, $this->valid_url_params) ){
247
- $url_params[$param] = $value;
248
- }
249
- }
250
- return $url_params;
251
- }
252
-
253
-
254
-
255
- /**
256
- * A helper method for parsing a list of search criteria and generating the parts of the SQL query.
257
- *
258
- * @see blcLinkQuery::get_links()
259
- *
260
- * @param array $params An array of search criteria.
261
- * @return array 'where_exprs' - an array of search expressions, 'join_instances' - whether joining the instance table is required.
262
- */
263
- function compile_search_params($params){
264
- global $wpdb; /** @var wpdb $wpdb */
265
-
266
- //Track whether we'll need to left-join the instance table to run the query.
267
- $join_instances = false;
268
-
269
- //Generate the individual clauses of the WHERE expression and store them in an array.
270
- $pieces = array();
271
-
272
- //Convert parser and container type lists to arrays of valid values
273
- $s_parser_type = array();
274
- if ( !empty($params['s_parser_type']) ){
275
- $s_parser_type = $params['s_parser_type'];
276
- if ( is_string($s_parser_type) ){
277
- $s_parser_type = preg_split('/[,\s]+/', $s_parser_type);
278
- }
279
- }
280
-
281
- $s_container_type = array();
282
- if ( !empty($params['s_container_type']) ){
283
- $s_container_type = $params['s_container_type'];
284
- if ( is_string($s_container_type) ){
285
- $s_container_type = preg_split('/[,\s]+/', $s_container_type);
286
- }
287
- }
288
-
289
- //Don't include links with instances that reference invalid (not currently loaded)
290
- //containers and parsers (unless specifically told to also include invalid links).
291
- if ( empty($params['include_invalid']) ){
292
- $join_instances = true;
293
-
294
- $module_manager = blcModuleManager::getInstance();
295
- $loaded_containers = array_keys($module_manager->get_active_by_category('container'));
296
- $loaded_parsers = array_keys($module_manager->get_active_by_category('parser'));
297
-
298
- if ( empty($s_parser_type) ){
299
- $s_parser_type = $loaded_parsers;
300
- } else {
301
- $s_parser_type = array_intersect($s_parser_type, $loaded_parsers);
302
- }
303
-
304
- if ( empty($s_container_type) ){
305
- $s_container_type = $loaded_containers;
306
- } else {
307
- $s_container_type = array_intersect($s_container_type, $loaded_containers);
308
- }
309
- }
310
-
311
- //Parser type should match the parser_type column in the instance table.
312
- if ( !empty($s_parser_type) ){
313
- $s_parser_type = array_map('trim', array_unique($s_parser_type));
314
- $s_parser_type = array_map('esc_sql', $s_parser_type);
315
-
316
- if ( count($s_parser_type) == 1 ){
317
- $pieces[] = sprintf("instances.parser_type = '%s'", reset($s_parser_type));
318
- } else {
319
- $pieces[] = "instances.parser_type IN ('" . implode("', '", $s_parser_type) . "')";
320
- }
321
-
322
- $join_instances = true;
323
- }
324
-
325
- //Container type should match the container_type column in the instance table.
326
- if ( !empty($s_container_type) ){
327
- //Sanitize for use in SQL
328
- $s_container_type = array_map('trim', array_unique($s_container_type));
329
- $s_container_type = array_map('esc_sql', $s_container_type);
330
-
331
- if ( count($s_container_type) == 1 ){
332
- $pieces[] = sprintf("instances.container_type = '%s'", reset($s_container_type));
333
- } else {
334
- $pieces[] = "instances.container_type IN ('" . implode("', '", $s_container_type) . "')";
335
- }
336
-
337
- $join_instances = true;
338
- }
339
-
340
- //A part of the WHERE expression can be specified explicitly
341
- if ( !empty($params['where_expr']) ){
342
- $pieces[] = $params['where_expr'];
343
- $join_instances = $join_instances || ( stripos($params['where_expr'], 'instances') !== false );
344
- }
345
-
346
- //List of allowed link ids (either an array or comma-separated)
347
- if ( !empty($params['link_ids']) ){
348
- $link_ids = $params['link_ids'];
349
-
350
- if ( is_string($link_ids) ){
351
- $link_ids = preg_split('/[,\s]+/', $link_ids);
352
- }
353
-
354
- //Only accept non-zero integers
355
- $sanitized_link_ids = array();
356
- foreach($link_ids as $id){
357
- $id = intval($id);
358
- if ( $id != 0 ){
359
- $sanitized_link_ids[] = $id;
360
- }
361
- }
362
-
363
- $pieces[] = 'links.link_id IN (' . implode(', ', $sanitized_link_ids) . ')';
364
- }
365
-
366
- //Anchor text - use LIKE search
367
- if ( !empty($params['s_link_text']) ){
368
- $s_link_text = esc_sql($this->esc_like($params['s_link_text']));
369
- $s_link_text = str_replace('*', '%', $s_link_text);
370
-
371
- $pieces[] = '(instances.link_text LIKE "%' . $s_link_text . '%")';
372
- $join_instances = true;
373
- }
374
-
375
- //URL - try to match both the initial URL and the final URL.
376
- //There is limited wildcard support, e.g. "google.*/search" will match both
377
- //"google.com/search" and "google.lv/search"
378
- if ( !empty($params['s_link_url']) ){
379
- $s_link_url = esc_sql($this->esc_like($params['s_link_url']));
380
- $s_link_url = str_replace('*', '%', $s_link_url);
381
-
382
- $pieces[] = '(links.url LIKE "%'. $s_link_url .'%") OR '.
383
- '(links.final_url LIKE "%'. $s_link_url .'%")';
384
- }
385
-
386
- //Container ID should match... you guessed it - container_id
387
- if ( !empty($params['s_container_id']) ){
388
- $s_container_id = intval($params['s_container_id']);
389
- if ( $s_container_id != 0 ){
390
- $pieces[] = "instances.container_id = $s_container_id";
391
- $join_instances = true;
392
- }
393
- }
394
-
395
- //Link type can match either the the parser_type or the container_type.
396
- if ( !empty($params['s_link_type']) ){
397
- $s_link_type = esc_sql($params['s_link_type']);
398
- $pieces[] = "instances.parser_type = '$s_link_type' OR instances.container_type='$s_link_type'";
399
- $join_instances = true;
400
- }
401
-
402
- //HTTP code - the user can provide a list of HTTP response codes and code ranges.
403
- //Example : 201,400-410,500
404
- if ( !empty($params['s_http_code']) ){
405
- //Strip spaces.
406
- $params['s_http_code'] = str_replace(' ', '', $params['s_http_code']);
407
- //Split by comma
408
- $codes = explode(',', $params['s_http_code']);
409
-
410
- $individual_codes = array();
411
- $ranges = array();
412
-
413
- //Try to parse each response code or range. Invalid ones are simply ignored.
414
- foreach($codes as $code){
415
- if ( is_numeric($code) ){
416
- //It's a single number
417
- $individual_codes[] = abs(intval($code));
418
- } elseif ( strpos($code, '-') !== false ) {
419
- //Try to parse it as a range
420
- $range = explode( '-', $code, 2 );
421
- if ( (count($range) == 2) && is_numeric($range[0]) && is_numeric($range[0]) ){
422
- //Make sure the smaller code comes first
423
- $range = array( intval($range[0]), intval($range[1]) );
424
- $ranges[] = array( min($range), max($range) );
425
- }
426
- }
427
- }
428
-
429
- $piece = array();
430
-
431
- //All individual response codes get one "http_code IN (...)" clause
432
- if ( !empty($individual_codes) ){
433
- $piece[] = '(links.http_code IN ('. implode(', ', $individual_codes) .'))';
434
- }
435
-
436
- //Ranges get a "http_code BETWEEN min AND max" clause each
437
- if ( !empty($ranges) ){
438
- $range_strings = array();
439
- foreach($ranges as $range){
440
- $range_strings[] = "(links.http_code BETWEEN $range[0] AND $range[1])";
441
- }
442
- $piece[] = '( ' . implode(' OR ', $range_strings) . ' )';
443
- }
444
-
445
- //Finally, generate a composite WHERE clause for both types of response code queries
446
- if ( !empty($piece) ){
447
- $pieces[] = implode(' OR ', $piece);
448
- }
449
-
450
- }
451
-
452
- //Dismissed links are included by default, but can explicitly included
453
- //or filtered out by passing a special param.
454
- if ( isset($params['s_include_dismissed']) ) {
455
- $s_include_dismissed = !empty($params['s_include_dismissed']);
456
- $pieces['filter_dismissed'] = $s_include_dismissed ? '1' : '(dismissed = 0)';
457
- }
458
-
459
- //Optionally sorting is also possible
460
- $order_exprs = array();
461
- if ( !empty($params['orderby']) ) {
462
- $allowed_columns = array(
463
- 'url' => 'links.url',
464
- 'link_text' => 'instances.link_text',
465
- 'redirect_url' => 'links.final_url',
466
- );
467
- $column = $params['orderby'];
468
-
469
- $direction = !empty($params['order']) ? strtolower($params['order']) : 'asc';
470
- if ( !in_array($direction, array('asc', 'desc')) ) {
471
- $direction = 'asc';
472
- }
473
-
474
- if ( array_key_exists($column, $allowed_columns) ) {
475
- if ( $column === 'redirect_url' ) {
476
- //Sort links that are not redirects last.
477
- $order_exprs[] = '(links.redirect_count > 0) DESC';
478
- }
479
-
480
- $order_exprs[] = $allowed_columns[$column] . ' ' . $direction;
481
- }
482
- }
483
-
484
- //Custom filters can optionally call one of the native filters
485
- //to narrow down the result set.
486
- if ( !empty($params['s_filter']) && isset($this->native_filters[$params['s_filter']]) ){
487
- $the_filter = $this->native_filters[$params['s_filter']];
488
- $extra_criteria = $this->compile_search_params($the_filter['params']);
489
-
490
- $pieces = array_merge($extra_criteria['where_exprs'], $pieces);
491
- $join_instances = $join_instances || $extra_criteria['join_instances'];
492
- }
493
-
494
- return array(
495
- 'where_exprs' => $pieces,
496
- 'join_instances' => $join_instances,
497
- 'order_exprs' => $order_exprs,
498
- );
499
- }
500
-
501
- private function esc_like($input) {
502
- global $wpdb; /** @var wpdb $wpdb */
503
- if ( method_exists($wpdb, 'esc_like') ) {
504
- return $wpdb->esc_like($input);
505
- } else {
506
- return like_escape($input);
507
- }
508
- }
509
-
510
- /**
511
- * blcLinkQuery::get_links()
512
- *
513
- * @see blc_get_links()
514
- *
515
- * @param array $params
516
- * @return array|int
517
- */
518
- function get_links($params = null){
519
- global $wpdb; /** @var wpdb $wpdb */
520
-
521
- if( !is_array($params) ){
522
- $params = array();
523
- }
524
-
525
- $defaults = array(
526
- 'offset' => 0,
527
- 'max_results' => 0,
528
- 'load_instances' => false,
529
- 'load_containers' => false,
530
- 'load_wrapped_objects' => false,
531
- 'count_only' => false,
532
- 'purpose' => '',
533
- 'include_invalid' => false,
534
- 'orderby' => '',
535
- 'order' => '',
536
- );
537
-
538
- $params = array_merge($defaults, $params);
539
-
540
- //Compile the search-related params into search expressions usable in a WHERE clause
541
- $criteria = $this->compile_search_params($params);
542
-
543
- //Build the WHERE clause
544
- if ( !empty($criteria['where_exprs']) ){
545
- $where_expr = "\t( " . implode(" ) AND\n\t( ", $criteria['where_exprs']) . ' ) ';
546
- } else {
547
- $where_expr = '1';
548
- }
549
-
550
- //Join the blc_instances table if it's required to perform the search.
551
- $joins = "";
552
- if ( $criteria['join_instances'] ){
553
- $joins = "JOIN {$wpdb->prefix}blc_instances AS instances ON links.link_id = instances.link_id";
554
- }
555
-
556
- //Optional sorting
557
- if ( !empty($criteria['order_exprs']) ) {
558
- $order_clause = 'ORDER BY ' . implode(', ', $criteria['order_exprs']);
559
- } else {
560
- $order_clause = '';
561
- }
562
-
563
- if ( $params['count_only'] ){
564
- //Only get the number of matching links.
565
- $q = "
566
- SELECT COUNT(*)
567
- FROM (
568
- SELECT 0
569
-
570
- FROM
571
- {$wpdb->prefix}blc_links AS links
572
- $joins
573
-
574
- WHERE
575
- $where_expr
576
-
577
- GROUP BY links.link_id) AS foo";
578
-
579
- return $wpdb->get_var($q);
580
- }
581
-
582
- //Select the required links.
583
- $q = "SELECT
584
- links.*
585
-
586
- FROM
587
- {$wpdb->prefix}blc_links AS links
588
- $joins
589
-
590
- WHERE
591
- $where_expr
592
-
593
- GROUP BY links.link_id
594
-
595
- {$order_clause}"; //Note: would be a lot faster without GROUP BY
596
-
597
- //Add the LIMIT clause
598
- if ( $params['max_results'] || $params['offset'] ){
599
- $q .= sprintf("\nLIMIT %d, %d", $params['offset'], $params['max_results']);
600
- }
601
-
602
- $results = $wpdb->get_results($q, ARRAY_A);
603
- if ( empty($results) ){
604
- return array();
605
- }
606
-
607
- //Create the link objects
608
- $links = array();
609
-
610
- foreach($results as $result){
611
- $link = new blcLink($result);
612
- $links[$link->link_id] = $link;
613
- }
614
-
615
- $purpose = $params['purpose'];
616
- /*
617
- Preload instances if :
618
- * It has been requested via the 'load_instances' argument.
619
- * The links are going to be displayed or edited, which involves instances.
620
- */
621
- $load_instances = $params['load_instances'] || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_EDITING));
622
-
623
- if ( $load_instances ){
624
- $link_ids = array_keys($links);
625
- $all_instances = blc_get_instances($link_ids, $purpose, $params['load_containers'], $params['load_wrapped_objects']);
626
- //Assign each batch of instances to the right link
627
- foreach($all_instances as $link_id => $instances){
628
- foreach($instances as $instance) { /** @var blcLinkInstance $instance */
629
- $instance->_link = $links[$link_id];
630
- }
631
- $links[$link_id]->_instances = $instances;
632
- }
633
- }
634
-
635
- return $links;
636
- }
637
-
638
- /**
639
- * Calculate the number of results for all known filters
640
- *
641
- * @return void
642
- */
643
- function count_filter_results(){
644
- foreach($this->native_filters as $filter_id => $filter){
645
- $this->native_filters[$filter_id]['count'] = $this->get_filter_links(
646
- $filter, array('count_only' => true)
647
- );
648
- }
649
-
650
- foreach($this->custom_filters as $filter_id => $filter){
651
- $this->custom_filters[$filter_id]['count'] = $this->get_filter_links(
652
- $filter, array('count_only' => true)
653
- );
654
- }
655
-
656
- $this->search_filter['count'] = $this->get_filter_links($this->search_filter, array('count_only' => true));
657
- }
658
-
659
- /**
660
- * Retrieve a list of links matching a filter.
661
- *
662
- * @uses blcLinkQuery::get_links()
663
- *
664
- * @param string|array $filter Either a filter ID or an array containing filter data.
665
- * @param array $extra_params Optional extra criteria that will override those set by the filter. See blc_get_links() for details.
666
- * @return array|int Either an array of blcLink objects, or an integer indicating the number of links that match the filter.
667
- */
668
- function get_filter_links($filter, $extra_params = null){
669
- if ( is_string($filter) ){
670
- $filter = $this->get_filter($filter);
671
- }
672
-
673
- $params = $this->get_search_params($filter);
674
-
675
-
676
- if ( !empty($extra_params) ){
677
- $params = array_merge($params, $extra_params);
678
- }
679
-
680
- return $this->get_links($params);
681
- }
682
-
683
- /**
684
- * Print a menu of available filters, both native and user-created.
685
- *
686
- * @param string $current Current filter ID.
687
- * @return void
688
- */
689
- function print_filter_menu($current = ''){
690
- $filters = $this->get_filters();
691
-
692
- echo '<ul class="subsubsub">';
693
-
694
- //Construct a submenu of filter types
695
- $items = array();
696
- foreach ($filters as $filter => $data){
697
- if ( !empty($data['hidden']) ) continue; //skip hidden filters
698
-
699
- $class = '';
700
- $number_class = 'filter-' . $filter . '-link-count';
701
-
702
- if ( $current == $filter ) {
703
- $class = 'class="current"';
704
- $number_class .= ' current-link-count';
705
- }
706
-
707
- $items[] = sprintf(
708
- "<li><a href='tools.php?page=view-broken-links&filter_id=%s' %s>%s</a> <span class='count'>(<span class='%s'>%d</span>)</span>",
709
- esc_attr($filter),
710
- $class,
711
- esc_html($data['name']),
712
- $number_class,
713
- $data['count']
714
- );
715
- }
716
- echo implode(' |</li>', $items);
717
-
718
- echo '</ul>';
719
- }
720
-
721
- /**
722
- * Print the appropriate heading for the given filter.
723
- *
724
- * @param array $current_filter
725
- * @return void
726
- */
727
- function print_filter_heading($current_filter){
728
- echo '<h2>';
729
- //Output a header matching the current filter
730
- if ( $current_filter['count'] > 0 ){
731
- echo $current_filter['heading'] . " (<span class='current-link-count'>{$current_filter['count']}</span>)";
732
- } else {
733
- echo $current_filter['heading_zero'] . "<span class='current-link-count'></span>";
734
- }
735
- echo '</h2>';
736
- }
737
-
738
- /**
739
- * Execute a filter.
740
- *
741
- * Gathers paging and search parameters from $_GET and executes the specified filter.
742
- * The returned array contains standard filter data plus several additional fields :
743
- * 'filter_id' - Which filter was used. May differ from the specified $filter_id due to fallback settings.
744
- * 'per_page' - How many results per page the method tried to retrieve.
745
- * 'page' - Which page of results was retrieved.
746
- * 'max_pages' - The total number of results pages, calculated using the above 'per_page' value.
747
- * 'links' - An array of retrieved links (blcLink objects).
748
- * 'search_params' - An associative array of the current search parameters as extracted either from the current URL or the filter itself.
749
- * 'is_broken_filter' - TRUE if the filter was set to retrieve only broken links, FALSE otherwise.
750
- *
751
- * @param string $filter_id Filter ID.
752
- * @param int $page Optional. Which page of results to retrieve. Defaults to returning the first page of results.
753
- * @param int $per_page Optional. The number of results per page. Defaults to 30.
754
- * @param string $fallback Optional. Which filter to use if none match the specified $filter_id. Defaults to the native broken link filter.
755
- * @param string $orderby Optional. Sort results by this column.
756
- * @param string $order Optional. Sort direction ('asc' or 'desc').
757
- * @return array Associative array of filter data and the results of its execution.
758
- */
759
- function exec_filter($filter_id, $page = 1, $per_page = 30, $fallback = 'broken', $orderby = '', $order = 'asc'){
760
- //The only valid sort directions are 'asc' and 'desc'.
761
- if ( !in_array($order, array('asc', 'desc')) ) {
762
- $order = 'asc';
763
- }
764
-
765
- //Get the selected filter (defaults to displaying broken links)
766
- $current_filter = $this->get_filter($filter_id);
767
- if ( empty($current_filter) ){
768
- $current_filter = $this->get_filter($fallback);
769
- $filter_id = $fallback;
770
- }
771
-
772
- //Page number must be > 0
773
- if ($page < 1) $page = 1;
774
-
775
- //Links per page [1 - 500]
776
- if ($per_page < 1){
777
- $per_page = 30;
778
- } else if ($per_page > 500){
779
- $per_page = 500;
780
- }
781
-
782
- //Calculate the maximum number of pages.
783
- $max_pages = ceil($current_filter['count'] / $per_page);
784
-
785
- //Select the required links
786
- $extra_params = array(
787
- 'offset' => ( ($page-1) * $per_page ),
788
- 'max_results' => $per_page,
789
- 'purpose' => BLC_FOR_DISPLAY,
790
- 'orderby' => $orderby,
791
- 'order' => $order,
792
- );
793
- $links = $this->get_filter_links($current_filter, $extra_params);
794
-
795
- //If the current request is a user-initiated search query (either directly or
796
- //via a custom filter), save the search params. They can later be used to pre-fill
797
- //the search form or build a new/modified custom filter.
798
- $search_params = array();
799
- if ( !empty($current_filter['custom']) || ($filter_id == 'search') ){
800
- $search_params = $this->get_search_params($current_filter);
801
- }
802
-
803
- $base_filter = '';
804
- if ( array_key_exists($filter_id, $this->native_filters) ) {
805
- $base_filter = $filter_id;
806
- } else if ( isset($current_filter['params']['s_filter']) && !empty($current_filter['params']['s_filter']) ) {
807
- $base_filter = $current_filter['params']['s_filter'];
808
- } else if ( isset($_GET['s_filter']) && !empty($_GET['s_filter']) ) {
809
- $base_filter = $_GET['s_filter'];
810
- }
811
-
812
- $is_broken_filter = ($base_filter == 'broken');
813
-
814
- //Save the effective filter data in the filter array.
815
- //It can be used later to print the link table.
816
- $current_filter = array_merge(array(
817
- 'filter_id' => $filter_id,
818
- 'page' => $page,
819
- 'per_page' => $per_page,
820
- 'max_pages' => $max_pages,
821
- 'links' => $links,
822
- 'search_params' => $search_params,
823
- 'is_broken_filter' => $is_broken_filter,
824
- 'base_filter' => $base_filter,
825
- ), $current_filter);
826
-
827
- return $current_filter;
828
- }
829
- }
830
-
831
- /**
832
- * Retrieve a list of links matching some criteria.
833
- *
834
- * The function argument should be an associative array describing the criteria.
835
- * The supported keys are :
836
- * 'offset' - Skip the first X results. Default is 0.
837
- * 'max_results' - The maximum number of links to return. Defaults to returning all results.
838
- * 'link_ids' - Retrieve only links with these IDs. This should either be a comma-separated list or an array.
839
- * 's_link_text' - Link text must match this keyphrase (performs a fulltext search).
840
- * 's_link_url' - Link URL must contain this string. You can use "*" as a wildcard.
841
- * 's_parser_type' - Filter links by the type of link parser that was used to find them.
842
- * 's_container_type' - Filter links by where they were found, e.g. 'post'.
843
- * 's_container_id' - Find links that belong to a container with this ID (should be used together with s_container_type).
844
- * 's_link_type' - Either parser type or container type must match this.
845
- * 's_http_code' - Filter by HTTP code. Example : 201,400-410,500
846
- * 's_filter' - Use a built-in filter. Available filters : 'broken', 'redirects', 'all'
847
- * 'where_expr' - Advanced. Lets you directly specify a part of the WHERE clause.
848
- * 'load_instances' - Pre-load all link instance data for each link. Default is false.
849
- * 'load_containers' - Pre-load container data for each instance. Default is false.
850
- * 'load_wrapped_objects' - Pre-load wrapped object data (e.g. posts, comments, etc) for each container. Default is false.
851
- * 'count_only' - Only return the number of results (int), not the whole result set. 'offset' and 'max_results' will be ignored if this is set. Default is false.
852
- * 'purpose' - An optional code indicating how the links will be used.
853
- * 'include_invalid' - Include links that have no instances and links that only have instances that reference not-loaded containers or parsers. Defaults to false.
854
- *
855
- * All keys are optional.
856
- *
857
- * @uses blcLinkQuery::get_links();
858
- *
859
- * @param array $params
860
- * @return int|blcLink[] Either an array of blcLink objects, or the number of results for the query.
861
- */
862
- function blc_get_links($params = null){
863
- $instance = blcLinkQuery::getInstance();
864
- return $instance->get_links($params);
865
- }
866
-
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Class for querying, sorting and filtering links.
5
+ * Used as a singleton.
6
+ *
7
+ * @package Broken Link Checker
8
+ * @access public
9
+ */
10
+ class blcLinkQuery {
11
+
12
+ var $native_filters;
13
+ var $search_filter;
14
+ var $custom_filters = array();
15
+
16
+ var $valid_url_params = array();
17
+
18
+ function __construct(){
19
+ //Init. the available native filters.
20
+ $this->native_filters = array(
21
+ 'all' => array(
22
+ 'params' => array(
23
+ 'where_expr' => '1',
24
+ ),
25
+ 'name' => __('All', 'broken-link-checker'),
26
+ 'heading' => __('Detected Links', 'broken-link-checker'),
27
+ 'heading_zero' => __('No links found (yet)', 'broken-link-checker'),
28
+ 'native' => true,
29
+ ),
30
+
31
+ 'broken' => array(
32
+ 'params' => array(
33
+ 'where_expr' => '( broken = 1 )',
34
+ 's_include_dismissed' => false,
35
+ ),
36
+ 'name' => __('Broken', 'broken-link-checker'),
37
+ 'heading' => __('Broken Links', 'broken-link-checker'),
38
+ 'heading_zero' => __('No broken links found', 'broken-link-checker'),
39
+ 'native' => true,
40
+ ),
41
+ 'warnings' => array(
42
+ 'params' => array(
43
+ 'where_expr' => '( warning = 1 )',
44
+ 's_include_dismissed' => false,
45
+ ),
46
+ 'name' => _x('Warnings', 'filter name', 'broken-link-checker'),
47
+ 'heading' => __('Warnings', 'filter heading', 'broken-link-checker'),
48
+ 'heading_zero' => __('No warnings found', 'broken-link-checker'),
49
+ 'native' => true,
50
+ ),
51
+ 'redirects' => array(
52
+ 'params' => array(
53
+ 'where_expr' => '( redirect_count > 0 )',
54
+ 's_include_dismissed' => false,
55
+ ),
56
+ 'name' => __('Redirects', 'broken-link-checker'),
57
+ 'heading' => __('Redirected Links', 'broken-link-checker'),
58
+ 'heading_zero' => __('No redirects found', 'broken-link-checker'),
59
+ 'native' => true,
60
+ ),
61
+
62
+ 'dismissed' => array(
63
+ 'params' => array(
64
+ 'where_expr' => '( dismissed = 1 )',
65
+ ),
66
+ 'name' => __('Dismissed', 'broken-link-checker'),
67
+ 'heading' => __('Dismissed Links', 'broken-link-checker'),
68
+ 'heading_zero' => __('No dismissed links found', 'broken-link-checker'),
69
+ 'native' => true,
70
+ ),
71
+ );
72
+
73
+ //The user can turn off warnings. In that case, all errors will show up in the "broken" filter instead.
74
+ $conf = blc_get_configuration();
75
+ if ( !$conf->get('warnings_enabled') ) {
76
+ unset($this->native_filters['warnings']);
77
+ }
78
+
79
+ //Create the special "search" filter
80
+ $this->search_filter = array(
81
+ 'name' => __('Search', 'broken-link-checker'),
82
+ 'heading' => __('Search Results', 'broken-link-checker'),
83
+ 'heading_zero' => __('No links found for your query', 'broken-link-checker'),
84
+ 'params' => array(),
85
+ 'use_url_params' => true,
86
+ 'hidden' => true,
87
+ );
88
+
89
+ //These search arguments may be passed via the URL if the filter's 'use_url_params' field is set to True.
90
+ //They map to the fields of the search form on the Tools -> Broken Links page. Only these arguments
91
+ //can be used in user-defined filters.
92
+ $this->valid_url_params = array(
93
+ 's_link_text',
94
+ 's_link_url',
95
+ 's_parser_type',
96
+ 's_container_type',
97
+ 's_link_type',
98
+ 's_http_code',
99
+ 's_filter',
100
+ );
101
+ }
102
+
103
+ static function getInstance(){
104
+ static $instance = null;
105
+ if ( is_null($instance) ){
106
+ $instance = new blcLinkQuery;
107
+ }
108
+ return $instance;
109
+ }
110
+
111
+ /**
112
+ * Load and return the list of user-defined link filters.
113
+ *
114
+ * @return array An array of custom filter definitions. If there are no custom filters defined returns an empty array.
115
+ */
116
+ function load_custom_filters(){
117
+ global $wpdb; /** @var wpdb $wpdb */
118
+
119
+ $filter_data = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}blc_filters ORDER BY name ASC", ARRAY_A);
120
+ $filters = array();
121
+
122
+ if ( !empty($filter_data) ) {
123
+ foreach($filter_data as $data){
124
+ wp_parse_str($data['params'], $params);
125
+
126
+ $filters[ 'f'.$data['id'] ] = array(
127
+ 'name' => $data['name'],
128
+ 'params' => $params,
129
+ 'heading' => ucwords($data['name']),
130
+ 'heading_zero' => __('No links found for your query', 'broken-link-checker'),
131
+ 'custom' => true,
132
+ );
133
+ }
134
+ }
135
+
136
+ $this->custom_filters = $filters;
137
+
138
+ return $filters;
139
+ }
140
+
141
+ /**
142
+ * Add a custom link filter.
143
+ *
144
+ * @param string $name Filter name.
145
+ * @param string|array $params Filter params. Either as a query string, or an array.
146
+ * @return string|bool The ID of the newly added filter, or False.
147
+ */
148
+ function create_custom_filter($name, $params){
149
+ global $wpdb; /** @var wpdb $wpdb */
150
+
151
+ if ( is_array($params) ){
152
+ $params = http_build_query($params, null, '&');
153
+ }
154
+
155
+ //Save the new filter
156
+ $q = $wpdb->prepare(
157
+ "INSERT INTO {$wpdb->prefix}blc_filters(name, params) VALUES (%s, %s)",
158
+ $name, $params
159
+ );
160
+
161
+ if ( $wpdb->query($q) !== false ){
162
+ $filter_id = 'f'.$wpdb->insert_id;
163
+ return $filter_id;
164
+ } else {
165
+ return false;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Delete a custom filter
171
+ *
172
+ * @param string $filter_id
173
+ * @return bool True on success, False if a database error occured.
174
+ */
175
+ function delete_custom_filter($filter_id){
176
+ global $wpdb; /** @var wpdb $wpdb */
177
+
178
+ if ( !isset($filter_id) ) {
179
+ $filter_id = $_POST['filter_id'];
180
+ }
181
+ //Remove the "f" character from the filter ID to get its database key
182
+ $filter_id = intval(ltrim($filter_id, 'f'));
183
+
184
+ //Try to delete the filter
185
+ $q = $wpdb->prepare("DELETE FROM {$wpdb->prefix}blc_filters WHERE id = %d", $filter_id);
186
+ if ( $wpdb->query($q) !== false ){
187
+ return true;
188
+ } else {
189
+ return false;
190
+ }
191
+ }
192
+
193
+ function get_filters(){
194
+ $filters = array_merge($this->native_filters, $this->custom_filters);
195
+ $filters['search'] = $this->search_filter;
196
+ return $filters;
197
+ }
198
+
199
+ /**
200
+ * Get a link search filter by filter ID.
201
+ *
202
+ * @param string $filter_id
203
+ * @return array|null
204
+ */
205
+ function get_filter($filter_id){
206
+ $filters = $this->get_filters();
207
+ if ( isset($filters[$filter_id]) ){
208
+ return $filters[$filter_id];
209
+ } else {
210
+ return null;
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Get link search parameters from the specified filter.
216
+ *
217
+ * @param array $filter
218
+ * @return array An array of parameters suitable for use with blcLinkQuery::get_links()
219
+ */
220
+ function get_search_params( $filter = null ){
221
+ //If present, the filter's parameters may be saved either as an array or a string.
222
+ $params = array();
223
+ if ( !empty($filter) && !empty($filter['params']) ){
224
+ $params = $filter['params'];
225
+ if ( is_string( $params ) ){
226
+ wp_parse_str($params, $params);
227
+ }
228
+ }
229
+
230
+ //Merge in the parameters from the current request, if required
231
+ if ( isset($filter['use_url_params']) && $filter['use_url_params'] ){
232
+ $params = array_merge($params, $this->get_url_search_params());
233
+ }
234
+
235
+ return $params;
236
+ }
237
+
238
+ /**
239
+ * Extract search query parameters from the current URL
240
+ *
241
+ * @return array
242
+ */
243
+ function get_url_search_params(){
244
+ $url_params = array();
245
+ foreach ($_GET as $param => $value){
246
+ if ( in_array($param, $this->valid_url_params) ){
247
+ $url_params[$param] = $value;
248
+ }
249
+ }
250
+ return $url_params;
251
+ }
252
+
253
+
254
+
255
+ /**
256
+ * A helper method for parsing a list of search criteria and generating the parts of the SQL query.
257
+ *
258
+ * @see blcLinkQuery::get_links()
259
+ *
260
+ * @param array $params An array of search criteria.
261
+ * @return array 'where_exprs' - an array of search expressions, 'join_instances' - whether joining the instance table is required.
262
+ */
263
+ function compile_search_params($params){
264
+ global $wpdb; /** @var wpdb $wpdb */
265
+
266
+ //Track whether we'll need to left-join the instance table to run the query.
267
+ $join_instances = false;
268
+
269
+ //Generate the individual clauses of the WHERE expression and store them in an array.
270
+ $pieces = array();
271
+
272
+ //Convert parser and container type lists to arrays of valid values
273
+ $s_parser_type = array();
274
+ if ( !empty($params['s_parser_type']) ){
275
+ $s_parser_type = $params['s_parser_type'];
276
+ if ( is_string($s_parser_type) ){
277
+ $s_parser_type = preg_split('/[,\s]+/', $s_parser_type);
278
+ }
279
+ }
280
+
281
+ $s_container_type = array();
282
+ if ( !empty($params['s_container_type']) ){
283
+ $s_container_type = $params['s_container_type'];
284
+ if ( is_string($s_container_type) ){
285
+ $s_container_type = preg_split('/[,\s]+/', $s_container_type);
286
+ }
287
+ }
288
+
289
+ //Don't include links with instances that reference invalid (not currently loaded)
290
+ //containers and parsers (unless specifically told to also include invalid links).
291
+ if ( empty($params['include_invalid']) ){
292
+ $join_instances = true;
293
+
294
+ $module_manager = blcModuleManager::getInstance();
295
+ $loaded_containers = array_keys($module_manager->get_active_by_category('container'));
296
+ $loaded_parsers = array_keys($module_manager->get_active_by_category('parser'));
297
+
298
+ if ( empty($s_parser_type) ){
299
+ $s_parser_type = $loaded_parsers;
300
+ } else {
301
+ $s_parser_type = array_intersect($s_parser_type, $loaded_parsers);
302
+ }
303
+
304
+ if ( empty($s_container_type) ){
305
+ $s_container_type = $loaded_containers;
306
+ } else {
307
+ $s_container_type = array_intersect($s_container_type, $loaded_containers);
308
+ }
309
+ }
310
+
311
+ //Parser type should match the parser_type column in the instance table.
312
+ if ( !empty($s_parser_type) ){
313
+ $s_parser_type = array_map('trim', array_unique($s_parser_type));
314
+ $s_parser_type = array_map('esc_sql', $s_parser_type);
315
+
316
+ if ( count($s_parser_type) == 1 ){
317
+ $pieces[] = sprintf("instances.parser_type = '%s'", reset($s_parser_type));
318
+ } else {
319
+ $pieces[] = "instances.parser_type IN ('" . implode("', '", $s_parser_type) . "')";
320
+ }
321
+
322
+ $join_instances = true;
323
+ }
324
+
325
+ //Container type should match the container_type column in the instance table.
326
+ if ( !empty($s_container_type) ){
327
+ //Sanitize for use in SQL
328
+ $s_container_type = array_map('trim', array_unique($s_container_type));
329
+ $s_container_type = array_map('esc_sql', $s_container_type);
330
+
331
+ if ( count($s_container_type) == 1 ){
332
+ $pieces[] = sprintf("instances.container_type = '%s'", reset($s_container_type));
333
+ } else {
334
+ $pieces[] = "instances.container_type IN ('" . implode("', '", $s_container_type) . "')";
335
+ }
336
+
337
+ $join_instances = true;
338
+ }
339
+
340
+ //A part of the WHERE expression can be specified explicitly
341
+ if ( !empty($params['where_expr']) ){
342
+ $pieces[] = $params['where_expr'];
343
+ $join_instances = $join_instances || ( stripos($params['where_expr'], 'instances') !== false );
344
+ }
345
+
346
+ //List of allowed link ids (either an array or comma-separated)
347
+ if ( !empty($params['link_ids']) ){
348
+ $link_ids = $params['link_ids'];
349
+
350
+ if ( is_string($link_ids) ){
351
+ $link_ids = preg_split('/[,\s]+/', $link_ids);
352
+ }
353
+
354
+ //Only accept non-zero integers
355
+ $sanitized_link_ids = array();
356
+ foreach($link_ids as $id){
357
+ $id = intval($id);
358
+ if ( $id != 0 ){
359
+ $sanitized_link_ids[] = $id;
360
+ }
361
+ }
362
+
363
+ $pieces[] = 'links.link_id IN (' . implode(', ', $sanitized_link_ids) . ')';
364
+ }
365
+
366
+ //Anchor text - use LIKE search
367
+ if ( !empty($params['s_link_text']) ){
368
+ $s_link_text = esc_sql($this->esc_like($params['s_link_text']));
369
+ $s_link_text = str_replace('*', '%', $s_link_text);
370
+
371
+ $pieces[] = '(instances.link_text LIKE "%' . $s_link_text . '%")';
372
+ $join_instances = true;
373
+ }
374
+
375
+ //URL - try to match both the initial URL and the final URL.
376
+ //There is limited wildcard support, e.g. "google.*/search" will match both
377
+ //"google.com/search" and "google.lv/search"
378
+ if ( !empty($params['s_link_url']) ){
379
+ $s_link_url = esc_sql($this->esc_like($params['s_link_url']));
380
+ $s_link_url = str_replace('*', '%', $s_link_url);
381
+
382
+ $pieces[] = '(links.url LIKE "%'. $s_link_url .'%") OR '.
383
+ '(links.final_url LIKE "%'. $s_link_url .'%")';
384
+ }
385
+
386
+ //Container ID should match... you guessed it - container_id
387
+ if ( !empty($params['s_container_id']) ){
388
+ $s_container_id = intval($params['s_container_id']);
389
+ if ( $s_container_id != 0 ){
390
+ $pieces[] = "instances.container_id = $s_container_id";
391
+ $join_instances = true;
392
+ }
393
+ }
394
+
395
+ //Link type can match either the the parser_type or the container_type.
396
+ if ( !empty($params['s_link_type']) ){
397
+ $s_link_type = esc_sql($params['s_link_type']);
398
+ $pieces[] = "instances.parser_type = '$s_link_type' OR instances.container_type='$s_link_type'";
399
+ $join_instances = true;
400
+ }
401
+
402
+ //HTTP code - the user can provide a list of HTTP response codes and code ranges.
403
+ //Example : 201,400-410,500
404
+ if ( !empty($params['s_http_code']) ){
405
+ //Strip spaces.
406
+ $params['s_http_code'] = str_replace(' ', '', $params['s_http_code']);
407
+ //Split by comma
408
+ $codes = explode(',', $params['s_http_code']);
409
+
410
+ $individual_codes = array();
411
+ $ranges = array();
412
+
413
+ //Try to parse each response code or range. Invalid ones are simply ignored.
414
+ foreach($codes as $code){
415
+ if ( is_numeric($code) ){
416
+ //It's a single number
417
+ $individual_codes[] = abs(intval($code));
418
+ } elseif ( strpos($code, '-') !== false ) {
419
+ //Try to parse it as a range
420
+ $range = explode( '-', $code, 2 );
421
+ if ( (count($range) == 2) && is_numeric($range[0]) && is_numeric($range[0]) ){
422
+ //Make sure the smaller code comes first
423
+ $range = array( intval($range[0]), intval($range[1]) );
424
+ $ranges[] = array( min($range), max($range) );
425
+ }
426
+ }
427
+ }
428
+
429
+ $piece = array();
430
+
431
+ //All individual response codes get one "http_code IN (...)" clause
432
+ if ( !empty($individual_codes) ){
433
+ $piece[] = '(links.http_code IN ('. implode(', ', $individual_codes) .'))';
434
+ }
435
+
436
+ //Ranges get a "http_code BETWEEN min AND max" clause each
437
+ if ( !empty($ranges) ){
438
+ $range_strings = array();
439
+ foreach($ranges as $range){
440
+ $range_strings[] = "(links.http_code BETWEEN $range[0] AND $range[1])";
441
+ }
442
+ $piece[] = '( ' . implode(' OR ', $range_strings) . ' )';
443
+ }
444
+
445
+ //Finally, generate a composite WHERE clause for both types of response code queries
446
+ if ( !empty($piece) ){
447
+ $pieces[] = implode(' OR ', $piece);
448
+ }
449
+
450
+ }
451
+
452
+ //Dismissed links are included by default, but can explicitly included
453
+ //or filtered out by passing a special param.
454
+ if ( isset($params['s_include_dismissed']) ) {
455
+ $s_include_dismissed = !empty($params['s_include_dismissed']);
456
+ $pieces['filter_dismissed'] = $s_include_dismissed ? '1' : '(dismissed = 0)';
457
+ }
458
+
459
+ //Optionally sorting is also possible
460
+ $order_exprs = array();
461
+ if ( !empty($params['orderby']) ) {
462
+ $allowed_columns = array(
463
+ 'url' => 'links.url',
464
+ 'link_text' => 'instances.link_text',
465
+ 'redirect_url' => 'links.final_url',
466
+ );
467
+ $column = $params['orderby'];
468
+
469
+ $direction = !empty($params['order']) ? strtolower($params['order']) : 'asc';
470
+ if ( !in_array($direction, array('asc', 'desc')) ) {
471
+ $direction = 'asc';
472
+ }
473
+
474
+ if ( array_key_exists($column, $allowed_columns) ) {
475
+ if ( $column === 'redirect_url' ) {
476
+ //Sort links that are not redirects last.
477
+ $order_exprs[] = '(links.redirect_count > 0) DESC';
478
+ }
479
+
480
+ $order_exprs[] = $allowed_columns[$column] . ' ' . $direction;
481
+ }
482
+ }
483
+
484
+ //Custom filters can optionally call one of the native filters
485
+ //to narrow down the result set.
486
+ if ( !empty($params['s_filter']) && isset($this->native_filters[$params['s_filter']]) ){
487
+ $the_filter = $this->native_filters[$params['s_filter']];
488
+ $extra_criteria = $this->compile_search_params($the_filter['params']);
489
+
490
+ $pieces = array_merge($extra_criteria['where_exprs'], $pieces);
491
+ $join_instances = $join_instances || $extra_criteria['join_instances'];
492
+ }
493
+
494
+ return array(
495
+ 'where_exprs' => $pieces,
496
+ 'join_instances' => $join_instances,
497
+ 'order_exprs' => $order_exprs,
498
+ );
499
+ }
500
+
501
+ private function esc_like($input) {
502
+ global $wpdb; /** @var wpdb $wpdb */
503
+ if ( method_exists($wpdb, 'esc_like') ) {
504
+ return $wpdb->esc_like($input);
505
+ } else {
506
+ return like_escape($input);
507
+ }
508
+ }
509
+
510
+ /**
511
+ * blcLinkQuery::get_links()
512
+ *
513
+ * @see blc_get_links()
514
+ *
515
+ * @param array $params
516
+ * @return array|int
517
+ */
518
+ function get_links($params = null){
519
+ global $wpdb; /** @var wpdb $wpdb */
520
+
521
+ if( !is_array($params) ){
522
+ $params = array();
523
+ }
524
+
525
+ $defaults = array(
526
+ 'offset' => 0,
527
+ 'max_results' => 0,
528
+ 'load_instances' => false,
529
+ 'load_containers' => false,
530
+ 'load_wrapped_objects' => false,
531
+ 'count_only' => false,
532
+ 'purpose' => '',
533
+ 'include_invalid' => false,
534
+ 'orderby' => '',
535
+ 'order' => '',
536
+ );
537
+
538
+ $params = array_merge($defaults, $params);
539
+
540
+ //Compile the search-related params into search expressions usable in a WHERE clause
541
+ $criteria = $this->compile_search_params($params);
542
+
543
+ //Build the WHERE clause
544
+ if ( !empty($criteria['where_exprs']) ){
545
+ $where_expr = "\t( " . implode(" ) AND\n\t( ", $criteria['where_exprs']) . ' ) ';
546
+ } else {
547
+ $where_expr = '1';
548
+ }
549
+
550
+ //Join the blc_instances table if it's required to perform the search.
551
+ $joins = "";
552
+ if ( $criteria['join_instances'] ){
553
+ $joins = "JOIN {$wpdb->prefix}blc_instances AS instances ON links.link_id = instances.link_id";
554
+ }
555
+
556
+ //Optional sorting
557
+ if ( !empty($criteria['order_exprs']) ) {
558
+ $order_clause = 'ORDER BY ' . implode(', ', $criteria['order_exprs']);
559
+ } else {
560
+ $order_clause = '';
561
+ }
562
+
563
+ if ( $params['count_only'] ){
564
+ //Only get the number of matching links.
565
+ $q = "
566
+ SELECT COUNT(*)
567
+ FROM (
568
+ SELECT 0
569
+
570
+ FROM
571
+ {$wpdb->prefix}blc_links AS links
572
+ $joins
573
+
574
+ WHERE
575
+ $where_expr
576
+
577
+ GROUP BY links.link_id) AS foo";
578
+
579
+ return $wpdb->get_var($q);
580
+ }
581
+
582
+ //Select the required links.
583
+ $q = "SELECT
584
+ links.*
585
+
586
+ FROM
587
+ {$wpdb->prefix}blc_links AS links
588
+ $joins
589
+
590
+ WHERE
591
+ $where_expr
592
+
593
+ GROUP BY links.link_id
594
+
595
+ {$order_clause}"; //Note: would be a lot faster without GROUP BY
596
+
597
+ //Add the LIMIT clause
598
+ if ( $params['max_results'] || $params['offset'] ){
599
+ $q .= sprintf("\nLIMIT %d, %d", $params['offset'], $params['max_results']);
600
+ }
601
+
602
+ $results = $wpdb->get_results($q, ARRAY_A);
603
+ if ( empty($results) ){
604
+ return array();
605
+ }
606
+
607
+ //Create the link objects
608
+ $links = array();
609
+
610
+ foreach($results as $result){
611
+ $link = new blcLink($result);
612
+ $links[$link->link_id] = $link;
613
+ }
614
+
615
+ $purpose = $params['purpose'];
616
+ /*
617
+ Preload instances if :
618
+ * It has been requested via the 'load_instances' argument.
619
+ * The links are going to be displayed or edited, which involves instances.
620
+ */
621
+ $load_instances = $params['load_instances'] || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_EDITING));
622
+
623
+ if ( $load_instances ){
624
+ $link_ids = array_keys($links);
625
+ $all_instances = blc_get_instances($link_ids, $purpose, $params['load_containers'], $params['load_wrapped_objects']);
626
+ //Assign each batch of instances to the right link
627
+ foreach($all_instances as $link_id => $instances){
628
+ foreach($instances as $instance) { /** @var blcLinkInstance $instance */
629
+ $instance->_link = $links[$link_id];
630
+ }
631
+ $links[$link_id]->_instances = $instances;
632
+ }
633
+ }
634
+
635
+ return $links;
636
+ }
637
+
638
+ /**
639
+ * Calculate the number of results for all known filters
640
+ *
641
+ * @return void
642
+ */
643
+ function count_filter_results(){
644
+ foreach($this->native_filters as $filter_id => $filter){
645
+ $this->native_filters[$filter_id]['count'] = $this->get_filter_links(
646
+ $filter, array('count_only' => true)
647
+ );
648
+ }
649
+
650
+ foreach($this->custom_filters as $filter_id => $filter){
651
+ $this->custom_filters[$filter_id]['count'] = $this->get_filter_links(
652
+ $filter, array('count_only' => true)
653
+ );
654
+ }
655
+
656
+ $this->search_filter['count'] = $this->get_filter_links($this->search_filter, array('count_only' => true));
657
+ }
658
+
659
+ /**
660
+ * Retrieve a list of links matching a filter.
661
+ *
662
+ * @uses blcLinkQuery::get_links()
663
+ *
664
+ * @param string|array $filter Either a filter ID or an array containing filter data.
665
+ * @param array $extra_params Optional extra criteria that will override those set by the filter. See blc_get_links() for details.
666
+ * @return array|int Either an array of blcLink objects, or an integer indicating the number of links that match the filter.
667
+ */
668
+ function get_filter_links($filter, $extra_params = null){
669
+ if ( is_string($filter) ){
670
+ $filter = $this->get_filter($filter);
671
+ }
672
+
673
+ $params = $this->get_search_params($filter);
674
+
675
+
676
+ if ( !empty($extra_params) ){
677
+ $params = array_merge($params, $extra_params);
678
+ }
679
+
680
+ return $this->get_links($params);
681
+ }
682
+
683
+ /**
684
+ * Print a menu of available filters, both native and user-created.
685
+ *
686
+ * @param string $current Current filter ID.
687
+ * @return void
688
+ */
689
+ function print_filter_menu($current = ''){
690
+ $filters = $this->get_filters();
691
+
692
+ echo '<ul class="subsubsub">';
693
+
694
+ //Construct a submenu of filter types
695
+ $items = array();
696
+ foreach ($filters as $filter => $data){
697
+ if ( !empty($data['hidden']) ) continue; //skip hidden filters
698
+
699
+ $class = '';
700
+ $number_class = 'filter-' . $filter . '-link-count';
701
+
702
+ if ( $current == $filter ) {
703
+ $class = 'class="current"';
704
+ $number_class .= ' current-link-count';
705
+ }
706
+
707
+ $items[] = sprintf(
708
+ "<li><a href='tools.php?page=view-broken-links&filter_id=%s' %s>%s</a> <span class='count'>(<span class='%s'>%d</span>)</span>",
709
+ esc_attr($filter),
710
+ $class,
711
+ esc_html($data['name']),
712
+ $number_class,
713
+ $data['count']
714
+ );
715
+ }
716
+ echo implode(' |</li>', $items);
717
+
718
+ echo '</ul>';
719
+ }
720
+
721
+ /**
722
+ * Print the appropriate heading for the given filter.
723
+ *
724
+ * @param array $current_filter
725
+ * @return void
726
+ */
727
+ function print_filter_heading($current_filter){
728
+ echo '<h2>';
729
+ //Output a header matching the current filter
730
+ if ( $current_filter['count'] > 0 ){
731
+ echo $current_filter['heading'] . " (<span class='current-link-count'>{$current_filter['count']}</span>)";
732
+ } else {
733
+ echo $current_filter['heading_zero'] . "<span class='current-link-count'></span>";
734
+ }
735
+ echo '</h2>';
736
+ }
737
+
738
+ /**
739
+ * Execute a filter.
740
+ *
741
+ * Gathers paging and search parameters from $_GET and executes the specified filter.
742
+ * The returned array contains standard filter data plus several additional fields :
743
+ * 'filter_id' - Which filter was used. May differ from the specified $filter_id due to fallback settings.
744
+ * 'per_page' - How many results per page the method tried to retrieve.
745
+ * 'page' - Which page of results was retrieved.
746
+ * 'max_pages' - The total number of results pages, calculated using the above 'per_page' value.
747
+ * 'links' - An array of retrieved links (blcLink objects).
748
+ * 'search_params' - An associative array of the current search parameters as extracted either from the current URL or the filter itself.
749
+ * 'is_broken_filter' - TRUE if the filter was set to retrieve only broken links, FALSE otherwise.
750
+ *
751
+ * @param string $filter_id Filter ID.
752
+ * @param int $page Optional. Which page of results to retrieve. Defaults to returning the first page of results.
753
+ * @param int $per_page Optional. The number of results per page. Defaults to 30.
754
+ * @param string $fallback Optional. Which filter to use if none match the specified $filter_id. Defaults to the native broken link filter.
755
+ * @param string $orderby Optional. Sort results by this column.
756
+ * @param string $order Optional. Sort direction ('asc' or 'desc').
757
+ * @return array Associative array of filter data and the results of its execution.
758
+ */
759
+ function exec_filter($filter_id, $page = 1, $per_page = 30, $fallback = 'broken', $orderby = '', $order = 'asc'){
760
+ //The only valid sort directions are 'asc' and 'desc'.
761
+ if ( !in_array($order, array('asc', 'desc')) ) {
762
+ $order = 'asc';
763
+ }
764
+
765
+ //Get the selected filter (defaults to displaying broken links)
766
+ $current_filter = $this->get_filter($filter_id);
767
+ if ( empty($current_filter) ){
768
+ $current_filter = $this->get_filter($fallback);
769
+ $filter_id = $fallback;
770
+ }
771
+
772
+ //Page number must be > 0
773
+ if ($page < 1) $page = 1;
774
+
775
+ //Links per page [1 - 500]
776
+ if ($per_page < 1){
777
+ $per_page = 30;
778
+ } else if ($per_page > 500){
779
+ $per_page = 500;
780
+ }
781
+
782
+ //Calculate the maximum number of pages.
783
+ $max_pages = ceil($current_filter['count'] / $per_page);
784
+
785
+ //Select the required links
786
+ $extra_params = array(
787
+ 'offset' => ( ($page-1) * $per_page ),
788
+ 'max_results' => $per_page,
789
+ 'purpose' => BLC_FOR_DISPLAY,
790
+ 'orderby' => $orderby,
791
+ 'order' => $order,
792
+ );
793
+ $links = $this->get_filter_links($current_filter, $extra_params);
794
+
795
+ //If the current request is a user-initiated search query (either directly or
796
+ //via a custom filter), save the search params. They can later be used to pre-fill
797
+ //the search form or build a new/modified custom filter.
798
+ $search_params = array();
799
+ if ( !empty($current_filter['custom']) || ($filter_id == 'search') ){
800
+ $search_params = $this->get_search_params($current_filter);
801
+ }
802
+
803
+ $base_filter = '';
804
+ if ( array_key_exists($filter_id, $this->native_filters) ) {
805
+ $base_filter = $filter_id;
806
+ } else if ( isset($current_filter['params']['s_filter']) && !empty($current_filter['params']['s_filter']) ) {
807
+ $base_filter = $current_filter['params']['s_filter'];
808
+ } else if ( isset($_GET['s_filter']) && !empty($_GET['s_filter']) ) {
809
+ if ( array_key_exists( $_GET['s_filter'], $this->native_filters ) ) {
810
+ $base_filter = esc_html( $_GET['s_filter'] );
811
+ } else {
812
+ $base_filter = 'all';
813
+ }
814
+ }
815
+
816
+ $is_broken_filter = ($base_filter == 'broken');
817
+
818
+ //Save the effective filter data in the filter array.
819
+ //It can be used later to print the link table.
820
+ $current_filter = array_merge(array(
821
+ 'filter_id' => $filter_id,
822
+ 'page' => $page,
823
+ 'per_page' => $per_page,
824
+ 'max_pages' => $max_pages,
825
+ 'links' => $links,
826
+ 'search_params' => $search_params,
827
+ 'is_broken_filter' => $is_broken_filter,
828
+ 'base_filter' => $base_filter,
829
+ ), $current_filter);
830
+
831
+ return $current_filter;
832
+ }
833
+ }
834
+
835
+ /**
836
+ * Retrieve a list of links matching some criteria.
837
+ *
838
+ * The function argument should be an associative array describing the criteria.
839
+ * The supported keys are :
840
+ * 'offset' - Skip the first X results. Default is 0.
841
+ * 'max_results' - The maximum number of links to return. Defaults to returning all results.
842
+ * 'link_ids' - Retrieve only links with these IDs. This should either be a comma-separated list or an array.
843
+ * 's_link_text' - Link text must match this keyphrase (performs a fulltext search).
844
+ * 's_link_url' - Link URL must contain this string. You can use "*" as a wildcard.
845
+ * 's_parser_type' - Filter links by the type of link parser that was used to find them.
846
+ * 's_container_type' - Filter links by where they were found, e.g. 'post'.
847
+ * 's_container_id' - Find links that belong to a container with this ID (should be used together with s_container_type).
848
+ * 's_link_type' - Either parser type or container type must match this.
849
+ * 's_http_code' - Filter by HTTP code. Example : 201,400-410,500
850
+ * 's_filter' - Use a built-in filter. Available filters : 'broken', 'redirects', 'all'
851
+ * 'where_expr' - Advanced. Lets you directly specify a part of the WHERE clause.
852
+ * 'load_instances' - Pre-load all link instance data for each link. Default is false.
853
+ * 'load_containers' - Pre-load container data for each instance. Default is false.
854
+ * 'load_wrapped_objects' - Pre-load wrapped object data (e.g. posts, comments, etc) for each container. Default is false.
855
+ * 'count_only' - Only return the number of results (int), not the whole result set. 'offset' and 'max_results' will be ignored if this is set. Default is false.
856
+ * 'purpose' - An optional code indicating how the links will be used.
857
+ * 'include_invalid' - Include links that have no instances and links that only have instances that reference not-loaded containers or parsers. Defaults to false.
858
+ *
859
+ * All keys are optional.
860
+ *
861
+ * @uses blcLinkQuery::get_links();
862
+ *
863
+ * @param array $params
864
+ * @return int|blcLink[] Either an array of blcLink objects, or the number of results for the query.
865
+ */
866
+ function blc_get_links($params = null){
867
+ $instance = blcLinkQuery::getInstance();
868
+ return $instance->get_links($params);
869
+ }
870
+
includes/links.php CHANGED
File without changes
includes/logger.php CHANGED
@@ -1,188 +1,188 @@
1
- <?php
2
-
3
- if ( !class_exists('blcLogger') ):
4
-
5
- define('BLC_LEVEL_DEBUG', 0);
6
- define('BLC_LEVEL_INFO', 1);
7
- define('BLC_LEVEL_WARNING', 2);
8
- define('BLC_LEVEL_ERROR', 3);
9
-
10
- /**
11
- * Base class for loggers. Doesn't actually log anything anywhere.
12
- *
13
- * @package Broken Link Checker
14
- * @author Janis Elsts
15
- */
16
- class blcLogger {
17
- protected $log_level = BLC_LEVEL_DEBUG;
18
-
19
- function __construct($param = ''){
20
-
21
- }
22
-
23
- function blcLogger($param = ''){
24
- $this->__construct($param);
25
- }
26
-
27
- function log($message, $object = null, $level = BLC_LEVEL_INFO){
28
-
29
- }
30
-
31
- function debug($message, $object = null){
32
- $this->log($message, $object, BLC_LEVEL_DEBUG);
33
- }
34
-
35
- function info($message, $object = null){
36
- $this->log($message, $object, BLC_LEVEL_INFO);
37
- }
38
-
39
- function warn($message, $object = null){
40
- $this->log($message, $object, BLC_LEVEL_WARNING);
41
- }
42
-
43
- function error($message, $object = null){
44
- $this->log($message, $object, BLC_LEVEL_ERROR);
45
- }
46
-
47
- function get_messages($min_level = BLC_LEVEL_DEBUG){
48
- return array();
49
- }
50
-
51
- function get_log($min_level = BLC_LEVEL_DEBUG){
52
- return array();
53
- }
54
-
55
- function clear(){
56
-
57
- }
58
-
59
- public function set_log_level($level) {
60
- $this->log_level = $level;
61
- }
62
- }
63
-
64
- /**
65
- * A basic logger that uses WP options for permanent storage.
66
- *
67
- * Log entries are initially stored in memory and need to explicitly
68
- * flushed to the database by calling blcCachedOptionLogger::save().
69
- *
70
- * @package Broken Link Checker
71
- * @author Janis Elsts
72
- */
73
- class blcCachedOptionLogger extends blcLogger {
74
- var $option_name = '';
75
- var $log;
76
- var $filter_level = BLC_LEVEL_DEBUG;
77
-
78
- function __construct($option_name = ''){
79
- $this->option_name = $option_name;
80
- $oldLog = get_option($this->option_name);
81
- if ( is_array($oldLog) && !empty($oldLog) ){
82
- $this->log = $oldLog;
83
- } else {
84
- $this->log = array();
85
- }
86
- }
87
-
88
- function log($message, $object = null, $level = BLC_LEVEL_DEBUG){
89
- $new_entry = array($level, $message, $object);
90
- array_push($this->log, $new_entry);
91
- }
92
-
93
- function get_log($min_level = BLC_LEVEL_DEBUG){
94
- $this->filter_level = $min_level;
95
- return array_filter($this->log, array($this, '_filter_log'));
96
- }
97
-
98
- function _filter_log($entry){
99
- return ( $entry[0] >= $this->filter_level );
100
- }
101
-
102
- function get_messages($min_level = BLC_LEVEL_DEBUG){
103
- $messages = $this->get_log($min_level);
104
- return array_map( array($this, '_get_log_message'), $messages );
105
- }
106
-
107
- function _get_log_message($entry){
108
- return $entry[1];
109
- }
110
-
111
- function clear(){
112
- $this->log = array();
113
- delete_option($this->option_name);
114
- }
115
-
116
- function save(){
117
- update_option($this->option_name, $this->log);
118
- }
119
- }
120
-
121
- /**
122
- * A dummy logger that doesn't log anything.
123
- */
124
- class blcDummyLogger extends blcLogger { }
125
-
126
- /**
127
- * A basic logger that logs messages to a file.
128
- */
129
- class blcFileLogger extends blcLogger {
130
- protected $fileName;
131
-
132
- public function __construct($fileName = ''){
133
- $this->fileName = $fileName;
134
- }
135
-
136
- function log($message, $object = null, $level = BLC_LEVEL_INFO){
137
- if ( $level < $this->log_level ) {
138
- return;
139
- }
140
-
141
- $line = sprintf(
142
- '[%1$s] %2$s %3$s',
143
- date('Y-m-d H:i:s P'),
144
- $this->get_level_string($level),
145
- $message
146
- );
147
-
148
- if ( isset($object) ) {
149
- $line .= ' ' . var_export($object, true);
150
- }
151
-
152
- $line .= "\n";
153
-
154
- error_log($line, 3, $this->fileName);
155
- }
156
-
157
- function get_messages($min_level = BLC_LEVEL_DEBUG){
158
- return array(__CLASS__ . ':get_messages() is not implemented');
159
- }
160
-
161
- function get_log($min_level = BLC_LEVEL_DEBUG){
162
- return array(__CLASS__ . ':get_log() is not implemented');
163
- }
164
-
165
- public function clear(){
166
- if ( is_file($this->fileName) && is_writable($this->fileName) ) {
167
- $handle = fopen($this->fileName, 'w');
168
- fclose($handle);
169
- }
170
- }
171
-
172
- protected function get_level_string($level) {
173
- switch ($level) {
174
- case BLC_LEVEL_DEBUG:
175
- return 'DEBUG:';
176
- case BLC_LEVEL_ERROR:
177
- return 'ERROR:';
178
- case BLC_LEVEL_WARNING:
179
- return 'WARN:';
180
- case BLC_LEVEL_INFO:
181
- return 'INFO:';
182
- }
183
- return 'LOG:';
184
- }
185
- }
186
-
187
- endif;
188
-
1
+ <?php
2
+
3
+ if ( !class_exists('blcLogger') ):
4
+
5
+ define('BLC_LEVEL_DEBUG', 0);
6
+ define('BLC_LEVEL_INFO', 1);
7
+ define('BLC_LEVEL_WARNING', 2);
8
+ define('BLC_LEVEL_ERROR', 3);
9
+
10
+ /**
11
+ * Base class for loggers. Doesn't actually log anything anywhere.
12
+ *
13
+ * @package Broken Link Checker
14
+ * @author Janis Elsts
15
+ */
16
+ class blcLogger {
17
+ protected $log_level = BLC_LEVEL_DEBUG;
18
+
19
+ function __construct($param = ''){
20
+
21
+ }
22
+
23
+ function blcLogger($param = ''){
24
+ $this->__construct($param);
25
+ }
26
+
27
+ function log($message, $object = null, $level = BLC_LEVEL_INFO){
28
+
29
+ }
30
+
31
+ function debug($message, $object = null){
32
+ $this->log($message, $object, BLC_LEVEL_DEBUG);
33
+ }
34
+
35
+ function info($message, $object = null){
36
+ $this->log($message, $object, BLC_LEVEL_INFO);
37
+ }
38
+
39
+ function warn($message, $object = null){
40
+ $this->log($message, $object, BLC_LEVEL_WARNING);
41
+ }
42
+
43
+ function error($message, $object = null){
44
+ $this->log($message, $object, BLC_LEVEL_ERROR);
45
+ }
46
+
47
+ function get_messages($min_level = BLC_LEVEL_DEBUG){
48
+ return array();
49
+ }
50
+
51
+ function get_log($min_level = BLC_LEVEL_DEBUG){
52
+ return array();
53
+ }
54
+
55
+ function clear(){
56
+
57
+ }
58
+
59
+ public function set_log_level($level) {
60
+ $this->log_level = $level;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * A basic logger that uses WP options for permanent storage.
66
+ *
67
+ * Log entries are initially stored in memory and need to explicitly
68
+ * flushed to the database by calling blcCachedOptionLogger::save().
69
+ *
70
+ * @package Broken Link Checker
71
+ * @author Janis Elsts
72
+ */
73
+ class blcCachedOptionLogger extends blcLogger {
74
+ var $option_name = '';
75
+ var $log;
76
+ var $filter_level = BLC_LEVEL_DEBUG;
77
+
78
+ function __construct($option_name = ''){
79
+ $this->option_name = $option_name;
80
+ $oldLog = get_option($this->option_name);
81
+ if ( is_array($oldLog) && !empty($oldLog) ){
82
+ $this->log = $oldLog;
83
+ } else {
84
+ $this->log = array();
85
+ }
86
+ }
87
+
88
+ function log($message, $object = null, $level = BLC_LEVEL_DEBUG){
89
+ $new_entry = array($level, $message, $object);
90
+ array_push($this->log, $new_entry);
91
+ }
92
+
93
+ function get_log($min_level = BLC_LEVEL_DEBUG){
94
+ $this->filter_level = $min_level;
95
+ return array_filter($this->log, array($this, '_filter_log'));
96
+ }
97
+
98
+ function _filter_log($entry){
99
+ return ( $entry[0] >= $this->filter_level );
100
+ }
101
+
102
+ function get_messages($min_level = BLC_LEVEL_DEBUG){
103
+ $messages = $this->get_log($min_level);
104
+ return array_map( array($this, '_get_log_message'), $messages );
105
+ }
106
+
107
+ function _get_log_message($entry){
108
+ return $entry[1];
109
+ }
110
+
111
+ function clear(){
112
+ $this->log = array();
113
+ delete_option($this->option_name);
114
+ }
115
+
116
+ function save(){
117
+ update_option($this->option_name, $this->log);
118
+ }
119
+ }
120
+
121
+ /**
122
+ * A dummy logger that doesn't log anything.
123
+ */
124
+ class blcDummyLogger extends blcLogger { }
125
+
126
+ /**
127
+ * A basic logger that logs messages to a file.
128
+ */
129
+ class blcFileLogger extends blcLogger {
130
+ protected $fileName;
131
+
132
+ public function __construct($fileName = ''){
133
+ $this->fileName = $fileName;
134
+ }
135
+
136
+ function log($message, $object = null, $level = BLC_LEVEL_INFO){
137
+ if ( $level < $this->log_level ) {
138
+ return;
139
+ }
140
+
141
+ $line = sprintf(
142
+ '[%1$s] %2$s %3$s',
143
+ date('Y-m-d H:i:s P'),
144
+ $this->get_level_string($level),
145
+ $message
146
+ );
147
+
148
+ if ( isset($object) ) {
149
+ $line .= ' ' . var_export($object, true);
150
+ }
151
+
152
+ $line .= "\n";
153
+
154
+ error_log($line, 3, $this->fileName);
155
+ }
156
+
157
+ function get_messages($min_level = BLC_LEVEL_DEBUG){
158
+ return array(__CLASS__ . ':get_messages() is not implemented');
159
+ }
160
+
161
+ function get_log($min_level = BLC_LEVEL_DEBUG){
162
+ return array(__CLASS__ . ':get_log() is not implemented');
163
+ }
164
+
165
+ public function clear(){
166
+ if ( is_file($this->fileName) && is_writable($this->fileName) ) {
167
+ $handle = fopen($this->fileName, 'w');
168
+ fclose($handle);
169
+ }
170
+ }
171
+
172
+ protected function get_level_string($level) {
173
+ switch ($level) {
174
+ case BLC_LEVEL_DEBUG:
175
+ return 'DEBUG:';
176
+ case BLC_LEVEL_ERROR:
177
+ return 'ERROR:';
178
+ case BLC_LEVEL_WARNING:
179
+ return 'WARN:';
180
+ case BLC_LEVEL_INFO:
181
+ return 'INFO:';
182
+ }
183
+ return 'LOG:';
184
+ }
185
+ }
186
+
187
+ endif;
188
+
includes/module-base.php CHANGED
@@ -1,80 +1,80 @@
1
- <?php
2
-
3
- /**
4
- * @author Janis Elsts
5
- * @copyright 2010
6
- */
7
-
8
- /**
9
- * Base class for BLC modules.
10
- *
11
- * @package Broken Link Checker
12
- * @author Janis Elsts
13
- * @access public
14
- */
15
- class blcModule {
16
-
17
- var $module_id; //The ID of this module. Usually a lowercase string.
18
- var $cached_header; //An associative array containing the header data of the module file.
19
- /** @var blcConfigurationManager $plugin__conf */
20
- var $plugin_conf; //A reference to the plugin's global configuration object.
21
- var $module_manager; //A reference to the module manager.
22
-
23
- /**
24
- * Class constructor
25
- *
26
- * @param string $module_id
27
- * @param array $cached_header
28
- * @param blcConfigurationManager $plugin_conf
29
- * @param blcModuleManager $module_manager
30
- * @return void
31
- */
32
- function __construct($module_id, $cached_header, &$plugin_conf, &$module_manager){
33
- $this->module_id = $module_id;
34
- $this->cached_header = $cached_header;
35
- $this->plugin_conf = &$plugin_conf;
36
- $this->module_manager = &$module_manager;
37
-
38
- $this->init();
39
- }
40
-
41
- /**
42
- * Module initializer. Called when the module is first instantiated.
43
- * The default implementation does nothing. Override it in a subclass to
44
- * specify some sort of start-up behaviour.
45
- *
46
- * @return void
47
- */
48
- function init(){
49
- //Should be overridden in a sub-class.
50
- }
51
-
52
- /**
53
- * Called when the module is activated.
54
- * Should be overridden in a sub-class.
55
- *
56
- * @return void
57
- */
58
- function activated(){
59
- //Should be overridden in a sub-class.
60
- }
61
-
62
- /**
63
- * Called when the module is deactivated.
64
- * Should be overridden in a sub-class.
65
- *
66
- * @return void
67
- */
68
- function deactivated(){
69
- //Should be overridden in a sub-class.
70
- }
71
-
72
- /**
73
- * Called when BLC itself is activated.
74
- * Usually this method just calls activated(), but subclasses could override it for special handling.
75
- */
76
- function plugin_activated() {
77
- $this->activated();
78
- }
79
- }
80
-
1
+ <?php
2
+
3
+ /**
4
+ * @author Janis Elsts
5
+ * @copyright 2010
6
+ */
7
+
8
+ /**
9
+ * Base class for BLC modules.
10
+ *
11
+ * @package Broken Link Checker
12
+ * @author Janis Elsts
13
+ * @access public
14
+ */
15
+ class blcModule {
16
+
17
+ var $module_id; //The ID of this module. Usually a lowercase string.
18
+ var $cached_header; //An associative array containing the header data of the module file.
19
+ /** @var blcConfigurationManager $plugin__conf */
20
+ var $plugin_conf; //A reference to the plugin's global configuration object.
21
+ var $module_manager; //A reference to the module manager.
22
+
23
+ /**
24
+ * Class constructor
25
+ *
26
+ * @param string $module_id
27
+ * @param array $cached_header
28
+ * @param blcConfigurationManager $plugin_conf
29
+ * @param blcModuleManager $module_manager
30
+ * @return void
31
+ */
32
+ function __construct($module_id, $cached_header, &$plugin_conf, &$module_manager){
33
+ $this->module_id = $module_id;
34
+ $this->cached_header = $cached_header;
35
+ $this->plugin_conf = &$plugin_conf;
36
+ $this->module_manager = &$module_manager;
37
+
38
+ $this->init();
39
+ }
40
+
41
+ /**
42
+ * Module initializer. Called when the module is first instantiated.
43
+ * The default implementation does nothing. Override it in a subclass to
44
+ * specify some sort of start-up behaviour.
45
+ *
46
+ * @return void
47
+ */
48
+ function init(){
49
+ //Should be overridden in a sub-class.
50
+ }
51
+
52
+ /**
53
+ * Called when the module is activated.
54
+ * Should be overridden in a sub-class.
55
+ *
56
+ * @return void
57
+ */
58
+ function activated(){
59
+ //Should be overridden in a sub-class.
60
+ }
61
+
62
+ /**
63
+ * Called when the module is deactivated.
64
+ * Should be overridden in a sub-class.
65
+ *
66
+ * @return void
67
+ */
68
+ function deactivated(){
69
+ //Should be overridden in a sub-class.
70
+ }
71
+
72
+ /**
73
+ * Called when BLC itself is activated.
74
+ * Usually this method just calls activated(), but subclasses could override it for special handling.
75
+ */
76
+ function plugin_activated() {
77
+ $this->activated();
78
+ }
79
+ }
80
+
includes/module-manager.php CHANGED
@@ -1,860 +1,860 @@
1
- <?php
2
-
3
- class blcModuleManager {
4
-
5
- /* @var blcConfigurationManager */
6
- var $plugin_conf;
7
- var $module_dir = '';
8
-
9
- var $_module_cache;
10
- var $_category_cache;
11
- var $_category_cache_active;
12
- var $_virtual_modules = array();
13
-
14
- var $loaded;
15
- var $instances;
16
- var $default_active_modules;
17
-
18
-
19
- /**
20
- * Class "constructor".
21
- *
22
- * @param array $default_active_modules An array of module ids specifying which modules are active by default.
23
- * @return void
24
- */
25
- function init($default_active_modules = null){
26
- $this->module_dir = realpath(dirname(__FILE__) . '/../modules');
27
-
28
- $this->plugin_conf = blc_get_configuration();
29
- $this->default_active_modules = $default_active_modules;
30
-
31
- $this->loaded = array();
32
- $this->instances = array();
33
-
34
- add_filter('extra_plugin_headers', array(&$this, 'inject_module_headers'));
35
- }
36
-
37
- /**
38
- * Get an instance of the module manager.
39
- *
40
- * @param array|null $default_active_modules
41
- * @return blcModuleManager
42
- */
43
- static function getInstance($default_active_modules = null){
44
- static $instance = null;
45
- if ( is_null($instance) ){
46
- $instance = new blcModuleManager();
47
- $instance->init($default_active_modules);
48
- }
49
- return $instance;
50
- }
51
-
52
- /**
53
- * Retrieve a list of all installed BLC modules.
54
- *
55
- * This is essentially a slightly modified copy of get_plugins().
56
- *
57
- * @return array An associative array of module headers indexed by module ID.
58
- */
59
- function get_modules(){
60
- if ( !isset($this->_module_cache) ){
61
- //Refresh the module cache.
62
-
63
- $relative_path = '/' . plugin_basename($this->module_dir);
64
- if ( !function_exists('get_plugins') ){
65
- //BUG: Potentional security flaw/bug. plugin.php is not meant to be loaded outside admin panel.
66
- require_once(ABSPATH . 'wp-admin/includes/plugin.php');
67
- }
68
- $modules = get_plugins( $relative_path );
69
-
70
- $this->_module_cache = array();
71
-
72
- foreach($modules as $module_filename => $module_header){
73
- //Figure out the module ID. If not specified, it is equal to module's filename (sans the .php)
74
- if ( !empty($module_header['ModuleID']) ){
75
- $module_id = strtolower(trim($module_header['ModuleID']));
76
- } else {
77
- $module_id = strtolower(basename($module_filename, '.php'));
78
- }
79
-
80
- $module_header = $this->normalize_module_header($module_header, $module_id, $module_filename);
81
- $this->_module_cache[$module_id] = $module_header;
82
- }
83
-
84
- $this->_category_cache = null;
85
- }
86
-
87
- return array_merge($this->_module_cache, $this->_virtual_modules);
88
- }
89
-
90
- /**
91
- * Retrieve modules that match a specific category, or all modules sorted by categories.
92
- *
93
- * If a category ID is specified, this method returns the modules that have the "ModuleCategory:"
94
- * file header set to that value, or an empty array if no modules match that category. The
95
- * return array is indexed by module id :
96
- * [module_id1 => module1_data, module_id1 => module2_data, ...]
97
- *
98
- * If category is omitted, this method returns a list of all categories plus the modules
99
- * they contain. Only categories that have at least one module will be included. The return
100
- * value is an array of arrays, indexed by category ID :
101
- * [category1 => [module1_id => module1_data, module2_id => module2_data, ...], ...]
102
- *
103
- *
104
- * @param string $category Category id, e.g. "parser" or "container". Optional.
105
- * @param bool $markup Apply markup to module headers. Not implemented.
106
- * @param bool $translate Translate module headers. Defaults to false.
107
- * @return array An array of categories or module data.
108
- */
109
- function get_modules_by_category($category = '', $markup = false, $translate = false){
110
- if ( !isset($this->_category_cache) ){
111
- $this->_category_cache = $this->sort_into_categories($this->get_modules());
112
- }
113
-
114
- if ( empty($category) ){
115
- if ( $markup || $translate ){
116
-
117
- //Translate/apply markup to module headers
118
- $processed = array();
119
- foreach($this->_category_cache as $category_id => $modules){
120
- $processed[$category_id] = array();
121
- foreach($modules as $module_id => $module_data){
122
- if ( $translate ){
123
- $module_data['Name'] = _x($module_data['Name'], 'module name', 'broken-link-checker');
124
- }
125
- $processed[$category_id][$module_id] = $module_data;
126
- }
127
- }
128
-
129
- return $processed;
130
- } else {
131
- return $this->_category_cache;
132
- }
133
- } else {
134
- if ( isset($this->_category_cache[$category]) ){
135
- if ( $markup || $translate ){
136
- //Translate/apply markup to module headers
137
- $processed = array();
138
- foreach($this->_category_cache[$category] as $module_id => $module_data){
139
- if ( $translate ){
140
- $module_data['Name'] = _x($module_data['Name'], 'module name', 'broken-link-checker');
141
- }
142
- $processed[$module_id] = $module_data;
143
- }
144
- return $processed;
145
- } else {
146
- return $this->_category_cache[$category];
147
- }
148
- } else {
149
- return array();
150
- }
151
- }
152
- }
153
-
154
- /**
155
- * Retrieve active modules that match a specific category, or all active modules sorted by categories.
156
- *
157
- * @see blcModuleManager::get_modules_by_category()
158
- *
159
- * @param string $category Category id. Optional.
160
- * @return array An associative array of categories or module data.
161
- */
162
- function get_active_by_category($category = ''){
163
- if ( !isset($this->_category_cache_active) ){
164
- $this->_category_cache_active = $this->sort_into_categories($this->get_active_modules());
165
- }
166
-
167
- if ( empty($category) ){
168
- return $this->_category_cache_active;
169
- } else {
170
- if ( isset($this->_category_cache_active[$category]) ){
171
- return $this->_category_cache_active[$category];
172
- } else {
173
- return array();
174
- }
175
- }
176
- }
177
-
178
- /**
179
- * Get the module ids of all active modules that belong to a specific category,
180
- * quoted and ready for use in SQL.
181
- *
182
- * @param string $category Category ID. If not specified, a list of all active modules will be returned.
183
- * @return string A comma separated list of single-quoted module ids, e.g. 'module-foo','module-bar','modbaz'
184
- */
185
- function get_escaped_ids($category = ''){
186
- global $wpdb;
187
-
188
- if ( empty($category) ){
189
- $modules = $this->get_active_modules();
190
- } else {
191
- $modules = $this->get_active_by_category($category);
192
- }
193
-
194
- $modules = array_map('esc_sql', array_keys($modules));
195
- $modules = "'" . implode("', '", $modules) . "'";
196
-
197
- return $modules;
198
- }
199
-
200
- /**
201
- * Sort a list of modules into categories. Inside each category, modules are sorted by priority (descending).
202
- *
203
- * @access private
204
- *
205
- * @param array $modules
206
- * @return array
207
- */
208
- function sort_into_categories($modules){
209
- $categories = array();
210
-
211
- foreach($modules as $module_id => $module_data){
212
- $cat = $module_data['ModuleCategory'];
213
- if ( isset($categories[$cat]) ){
214
- $categories[$cat][$module_id] = $module_data;
215
- } else {
216
- $categories[$cat] = array($module_id => $module_data);
217
- }
218
- }
219
-
220
- foreach($categories as $cat => $cat_modules){
221
- uasort($categories[$cat], array(&$this, 'compare_priorities'));
222
- }
223
-
224
- return $categories;
225
- }
226
-
227
- /**
228
- * Callback for sorting modules by priority.
229
- *
230
- * @access private
231
- *
232
- * @param array $a First module header.
233
- * @param array $b Second module header.
234
- * @return int
235
- */
236
- function compare_priorities($a, $b){
237
- return $b['ModulePriority'] - $a['ModulePriority'];
238
- }
239
-
240
- /**
241
- * Retrieve a reference to an active module.
242
- *
243
- * Each module is instantiated only once, so if the module was already loaded you'll get back
244
- * a reference to the existing module object. If the module isn't loaded or instantiated yet,
245
- * the function will do it automatically (but only for active modules).
246
- *
247
- * @param string $module_id Module ID.
248
- * @param bool $autoload Optional. Whether to load the module file if it's not loaded yet. Defaults to TRUE.
249
- * @param string $category Optional. Return the module only if it's in a specific category. Categories are ignored by default.
250
- * @return blcModule A reference to a module object, or NULL on error.
251
- */
252
- function get_module($module_id, $autoload = true, $category=''){
253
- $no_result = null;
254
- if ( !is_string($module_id) ){
255
- //$backtrace = debug_backtrace();
256
- //FB::error($backtrace, "get_module called with a non-string argument");
257
- return $no_result;
258
- }
259
-
260
- if ( empty($this->loaded[$module_id]) ){
261
- if ( $autoload && $this->is_active($module_id) ){
262
- if ( !$this->load_module($module_id) ){
263
- return $no_result;
264
- }
265
- } else {
266
- return $no_result;
267
- }
268
- }
269
-
270
- if ( !empty($category) ){
271
- $data = $this->get_module_data($module_id);
272
- if ( $data['ModuleCategory'] != $category ){
273
- return $no_result;
274
- }
275
- }
276
-
277
- $module = $this->init_module($module_id);
278
- return $module;
279
- }
280
-
281
- /**
282
- * Retrieve the header data of a specific module.
283
- * Uses cached module info if available.
284
- *
285
- * @param string $module_id
286
- * @param bool $use_active_cache Check the active module cache before the general one. Defaults to true.
287
- * @return array Associative array of module data, or FALSE if the specified module was not found.
288
- */
289
- function get_module_data($module_id, $use_active_cache = true){
290
- //Check virtual modules
291
- if ( isset($this->_virtual_modules[$module_id]) ){
292
- return $this->_virtual_modules[$module_id];
293
- }
294
-
295
- //Check active modules
296
- if ( $use_active_cache && isset($this->plugin_conf->options['active_modules'][$module_id]) ){
297
- return $this->plugin_conf->options['active_modules'][$module_id];
298
- }
299
-
300
- //Otherwise, use the general module cache
301
- if ( !isset($this->_module_cache) ){
302
- $this->get_modules(); //Populates the cache
303
- }
304
-
305
- if ( isset($this->_module_cache[$module_id]) ){
306
- return $this->_module_cache[$module_id];
307
- } else {
308
- return false;
309
- }
310
- }
311
-
312
- /**
313
- * Retrieve a list of active modules.
314
- *
315
- * The list of active modules is stored in the 'active_modules' key of the
316
- * plugin configuration object. If this key is not set, this function will
317
- * create it and populate it using the list of default active modules passed
318
- * to the module manager's constructor.
319
- *
320
- * @return array Associative array of module data indexed by module ID.
321
- */
322
- function get_active_modules(){
323
- if ( isset($this->plugin_conf->options['active_modules']) ){
324
- return $this->plugin_conf->options['active_modules'];
325
- }
326
-
327
- $active = array();
328
- $modules = $this->get_modules();
329
-
330
- if ( is_array($this->default_active_modules) ){
331
- foreach($this->default_active_modules as $module_id){
332
- if ( array_key_exists($module_id, $modules) ){
333
- $active[$module_id] = $modules[$module_id];
334
- }
335
- }
336
- }
337
-
338
- $this->plugin_conf->options['active_modules'] = $active;
339
- $this->plugin_conf->save_options();
340
-
341
- return $this->plugin_conf->options['active_modules'];
342
- }
343
-
344
- /**
345
- * Determine if module is active.
346
- *
347
- * @param string $module_id
348
- * @return bool
349
- */
350
- function is_active($module_id){
351
- return array_key_exists($module_id, $this->get_active_modules());
352
- }
353
-
354
- /**
355
- * Activate a module.
356
- * Does nothing if the module is already active.
357
- *
358
- * @param string $module_id
359
- * @return bool True if module was activated successfully, false otherwise.
360
- */
361
- function activate($module_id){
362
- if ( $this->is_active($module_id) ){
363
- return true;
364
- }
365
-
366
- //Retrieve the module header
367
- $module_data = $this->get_module_data($module_id, false);
368
- if ( !$module_data ){
369
- return false;
370
- }
371
-
372
- //Attempt to load the module
373
- if ( $this->load_module($module_id, $module_data) ){
374
- //Okay, if it loads, we can assume it works.
375
- $this->plugin_conf->options['active_modules'][$module_id] = $module_data;
376
- $this->plugin_conf->save_options();
377
- //Invalidate the per-category active module cache
378
- $this->_category_cache_active = null;
379
-
380
- //Notify the module that it's been activated
381
- $module = $this->get_module($module_id);
382
- if ( $module ){
383
- $module->activated();
384
- }
385
- return true;
386
- } else {
387
- return false;
388
- }
389
- }
390
-
391
- /**
392
- * Deactivate a module.
393
- * Does nothing if the module is already inactive.
394
- *
395
- * @param string $module_id
396
- * @return bool
397
- */
398
- function deactivate($module_id){
399
- if ( !$this->is_active($module_id) ){
400
- return true;
401
- }
402
-
403
- //Some modules are supposed to be always active and thus can't be deactivated
404
- $module_data = $this->get_module_data($module_id, false);
405
- if ( isset($module_data['ModuleAlwaysActive']) && $module_data['ModuleAlwaysActive'] ){
406
- return false;
407
- }
408
-
409
- //Notify the module that it's being deactivated
410
- $module = $this->get_module($module_id);
411
- if ( $module ){
412
- $module->deactivated();
413
- }
414
-
415
- unset($this->plugin_conf->options['active_modules'][$module_id]);
416
-
417
- //Keep track of when each module was last deactivated. Used for parser resynchronization.
418
- if ( isset($this->plugin_conf->options['module_deactivated_when']) ){
419
- $this->plugin_conf->options['module_deactivated_when'][$module_id] = current_time('timestamp');
420
- } else {
421
- $this->plugin_conf->options['module_deactivated_when'] = array(
422
- $module_id => current_time('timestamp'),
423
- );
424
- }
425
- $this->plugin_conf->save_options();
426
-
427
- $this->_category_cache_active = null; //Invalidate the by-category cache since we just changed something
428
- return true;
429
- }
430
-
431
- /**
432
- * Determine when a module was last deactivated.
433
- *
434
- * @param string $module_id Module ID.
435
- * @return int Timestamp of last deactivation, or 0 if the module has never been deactivated.
436
- */
437
- function get_last_deactivation_time($module_id){
438
- if ( isset($this->plugin_conf->options['module_deactivated_when'][$module_id]) ){
439
- return $this->plugin_conf->options['module_deactivated_when'][$module_id];
440
- } else {
441
- return 0;
442
- }
443
- }
444
-
445
- /**
446
- * Set the current list of active modules. If any of the modules are not currently active,
447
- * they will be activated. Any currently active modules that are not on the new list will
448
- * be deactivated.
449
- *
450
- * @param array $ids An array of module IDs.
451
- * @return void
452
- */
453
- function set_active_modules($ids){
454
- $current_active = array_keys($this->get_active_modules());
455
-
456
- $activate = array_diff($ids, $current_active);
457
- $deactivate = array_diff($current_active, $ids);
458
-
459
- //Deactivate any modules not present in the new list
460
- foreach($deactivate as $module_id){
461
- $this->deactivate($module_id);
462
- }
463
-
464
- //Activate modules present in the new list but not in the old list
465
- foreach($activate as $module_id){
466
- $this->activate($module_id);
467
- }
468
-
469
- //Ensure all active modules have the latest headers
470
- $this->refresh_active_module_cache();
471
-
472
- //Invalidate the per-category active module cache
473
- $this->_category_cache_active = null;
474
- }
475
-
476
- /**
477
- * Send the activation message to all currently active plugins when the plugin is activated.
478
- *
479
- * @return void
480
- */
481
- function plugin_activated(){
482
- global $blclog;
483
-
484
- //Ensure all active modules have the latest headers
485
- $blclog->log('... Updating module cache');
486
- $start = microtime(true);
487
- $this->refresh_active_module_cache();
488
- $blclog->info(sprintf('... Cache refresh took %.3f seconds', microtime(true) - $start));
489
-
490
- //Notify them that we've been activated
491
- $blclog->log('... Loading modules');
492
- $start = microtime(true);
493
- $this->load_modules();
494
- $blclog->info(sprintf('... %d modules loaded in %.3f seconds', count($this->loaded), microtime(true) - $start));
495
-
496
- $active = $this->get_active_modules();
497
- foreach($active as $module_id => $module_data){
498
- $blclog->log( sprintf('... Notifying module "%s"', $module_id) );
499
- $module = $this->get_module($module_id);
500
- if ( $module ){
501
- $module->plugin_activated();
502
- } else {
503
- $blclog->warn(sprintf('... Module "%s" failed to load!', $module_id));
504
- }
505
- }
506
- }
507
-
508
- /**
509
- * Refresh the cached data of all active modules.
510
- *
511
- * @return array An updated list of active modules.
512
- */
513
- function refresh_active_module_cache(){
514
- $modules = $this->get_modules();
515
- foreach($this->plugin_conf->options['active_modules'] as $module_id => $module_header){
516
- if ( array_key_exists($module_id, $modules) ){
517
- $this->plugin_conf->options['active_modules'][$module_id] = $modules[$module_id];
518
- }
519
- }
520
- $this->plugin_conf->save_options();
521
- $this->_category_cache_active = null; //Invalidate the by-category active module cache
522
- return $this->plugin_conf->options['active_modules'];
523
- }
524
-
525
- /**
526
- * Load active modules.
527
- *
528
- * @param string $context Optional. If specified, only the modules that match this context (or the "all" context) will be loaded.
529
- * @return void
530
- */
531
- function load_modules($context = ''){
532
- $active = $this->get_active_modules();
533
- //Avoid trying to load a virtual module before the module that registered it has been loaded.
534
- $active = $this->put_virtual_last($active);
535
-
536
- foreach($active as $module_id => $module_data){
537
- //Load the module
538
- $should_load = ($module_data['ModuleContext'] == 'all') || (!empty($context) && $module_data['ModuleContext'] == $context);
539
- if ( $should_load ){
540
- $this->load_module($module_id, $module_data);
541
- }
542
- }
543
- }
544
-
545
- /**
546
- * Load and possibly instantiate a specific module.
547
- *
548
- * @access private
549
- *
550
- * @param string $module_id
551
- * @param array $module_data
552
- * @return bool True if the module was successfully loaded, false otherwise.
553
- */
554
- function load_module($module_id, $module_data = null){
555
-
556
- //Only load each module once.
557
- if ( !empty($this->loaded[$module_id]) ){
558
- return true;
559
- }
560
-
561
- if ( !isset($module_data) ){
562
- $module_data = $this->get_module_data($module_id);
563
- if ( empty($module_data) ){
564
- return false;
565
- }
566
- }
567
-
568
- //Load a normal module
569
- if ( empty($module_data['virtual']) ){
570
-
571
- //Skip invalid and missing modules
572
- if ( empty($module_data['file']) ){
573
- return false;
574
- }
575
-
576
- //Get the full path to the module file
577
- $filename = $this->module_dir . '/' . $module_data['file'];
578
- if ( !file_exists($filename) ){
579
- return false;
580
- }
581
-
582
- //Load it
583
- include $filename;
584
- $this->loaded[$module_id] = true;
585
-
586
- } else {
587
-
588
- //Virtual modules don't need to be explicitly loaded, but they must
589
- //be registered.
590
- if ( !array_key_exists($module_id, $this->_virtual_modules) ) {
591
- return false;
592
- }
593
- $this->loaded[$module_id] = true;
594
-
595
- }
596
-
597
- //Instantiate the main module class unless lazy init is on (default is off)
598
- if ( !array_key_exists($module_id, $this->instances) ){ //Only try to instantiate once
599
- if ( !$module_data['ModuleLazyInit'] ){
600
- $this->init_module($module_id, $module_data);
601
- }
602
- }
603
-
604
- return true;
605
- }
606
-
607
- /**
608
- * Instantiate a certain module.
609
- *
610
- * @param string $module_id
611
- * @param array $module_data Optional. The header data of the module that needs to be instantiated. If not specified, it will be retrieved automatically.
612
- * @return object The newly instantiated module object (extends blcModule), or NULL on error.
613
- */
614
- function init_module($module_id, $module_data = null){
615
- //Each module is only instantiated once.
616
- if ( isset($this->instances[$module_id]) ){
617
- return $this->instances[$module_id];
618
- }
619
-
620
- if ( !isset($module_data) ){
621
- $module_data = $this->get_module_data($module_id);
622
- if ( empty($module_data) ){
623
- return null;
624
- }
625
- }
626
-
627
- if ( !empty($module_data['ModuleClassName']) && class_exists($module_data['ModuleClassName']) ){
628
- $className = $module_data['ModuleClassName'];
629
- $this->instances[$module_id] = new $className(
630
- $module_id,
631
- $module_data,
632
- $this->plugin_conf,
633
- $this
634
- );
635
- return $this->instances[$module_id];
636
- };
637
-
638
- return null;
639
- }
640
-
641
- function is_instantiated($module_id){
642
- return !empty($this->instances[$module_id]);
643
- }
644
-
645
- /**
646
- * Register a virtual module.
647
- *
648
- * Virtual modules are the same as normal modules, except that they can be added
649
- * on the fly, e.g. by other modules.
650
- *
651
- * @param string $module_id Module Id.
652
- * @param string $module_data Associative array of module data. All module header fields are allowed, except ModuleID.
653
- * @return void
654
- */
655
- function register_virtual_module($module_id, $module_data){
656
- $module_data = $this->normalize_module_header($module_data, $module_id);
657
- $module_data['virtual'] = true;
658
- $this->_virtual_modules[$module_id] = $module_data;
659
- }
660
-
661
- /**
662
- * Sort an array of modules so that all virtual modules are placed at its end.
663
- *
664
- * @param array $modules Input array, [module_id => module_data, ...].
665
- * @return array Sorted array.
666
- */
667
- function put_virtual_last($modules){
668
- uasort($modules, array(&$this, 'compare_virtual_flags'));
669
- return $modules;
670
- }
671
-
672
- /**
673
- * Callback function for sorting modules by the state of their 'virtual' flag.
674
- *
675
- * @param array $a Associative array of module A data
676
- * @param array $b Associative array of module B data
677
- * @return int
678
- */
679
- function compare_virtual_flags($a, $b){
680
- if ( empty($a['virtual']) ){
681
- return empty($b['virtual'])?0:-1;
682
- } else {
683
- return empty($b['virtual'])?1:0;
684
- }
685
- }
686
-
687
- /**
688
- * Validate active modules.
689
- *
690
- * Validates all active modules, deactivates invalid ones and returns
691
- * an array of deactivated modules.
692
- *
693
- * @return array
694
- */
695
- function validate_active_modules(){
696
- $active = $this->get_active_modules();
697
- if ( empty($active) ){
698
- return array();
699
- }
700
-
701
- $invalid = array();
702
- foreach($active as $module_id => $module_data){
703
- $rez = $this->validate_module($module_data);
704
- if ( is_wp_error($rez) ){
705
- $invalid[$module_id] = $rez;
706
- $this->deactivate($module_id);
707
- }
708
- }
709
-
710
- return $invalid;
711
- }
712
-
713
- /**
714
- * Validate module data.
715
- *
716
- * Checks that the module file exists or that the module
717
- * is a currently registered virtual module.
718
- *
719
- * @param array $module_data Associative array of module data.
720
- * @return bool|WP_Error True on success, an error object if the module fails validation
721
- */
722
- function validate_module($module_data){
723
- if ( empty($module_data['ModuleID']) ){
724
- return new WP_Error('invalid_cached_header', 'The cached module header is invalid');
725
- }
726
-
727
- if ( empty($module_data['virtual']) ){
728
- //Normal modules must have a valid filename
729
- if ( empty($module_data['file']) ){
730
- return new WP_Error('module_not_found', 'Invalid module file');
731
- }
732
-
733
- $filename = $this->module_dir . '/' . $module_data['file'];
734
- if ( !file_exists($filename) ){
735
- return new WP_Error('module_not_found', 'Module file not found');
736
- }
737
-
738
- //The module file header must be in the proper format. While $module_data comes
739
- //from cache and can be assumed to be correct, get_modules() will attempt to load
740
- //the current headers and only return modules with semi-valid headers.
741
- $installed = $this->get_modules();
742
- if ( !array_key_exists($module_data['ModuleID'], $installed) ){
743
- return new WP_Error('invalid_module_header', 'Invalid module header');
744
- }
745
- } else {
746
- //Virtual modules need to be currently registered
747
- if ( !array_key_exists($module_data['ModuleID'], $this->_virtual_modules) ){
748
- return new WP_Error('module_not_registered', 'The virtual module is not registered');
749
- }
750
- }
751
-
752
- return true;
753
- }
754
-
755
- /**
756
- * Add BLC-module specific headers to the list of allowed plugin headers. This
757
- * lets us use get_plugins() to retrieve the list of BLC modules.
758
- *
759
- * @param array $headers Currently known plugin headers.
760
- * @return array New plugin headers.
761
- */
762
- function inject_module_headers($headers){
763
- $module_headers = array(
764
- 'ModuleID',
765
- 'ModuleCategory',
766
- 'ModuleContext',
767
- 'ModuleLazyInit',
768
- 'ModuleClassName',
769
- 'ModulePriority',
770
- 'ModuleCheckerUrlPattern',
771
- 'ModuleHidden', //Don't show the module in the Settings page
772
- 'ModuleAlwaysActive', //Module can't be deactivated.
773
- 'ModuleRequiresPro', //Can only be activated in the Pro version
774
- );
775
-
776
- return array_merge($headers, $module_headers);
777
- }
778
-
779
- /**
780
- * Normalize a module header, using defaults where necessary.
781
- *
782
- * @param array $module_header Module header, as read from the module's .php file.
783
- * @param string $module_id Module ID.
784
- * @param string $module_filename Module filename. Optional.
785
- * @return array Normalized module header.
786
- */
787
- function normalize_module_header($module_header, $module_id, $module_filename = ''){
788
- //Default values for optional module header fields
789
- $defaults = array(
790
- 'ModuleContext' => 'all',
791
- 'ModuleCategory' => 'other',
792
- 'ModuleLazyInit' => 'false',
793
- 'ModulePriority' => '0',
794
- 'ModuleHidden' => 'false',
795
- 'ModuleAlwaysActive' => 'false',
796
- 'ModuleRequiresPro' => 'false',
797
- 'TextDomain' => 'broken-link-checker', //For translating module headers
798
- );
799
-
800
- $module_header['ModuleID'] = $module_id; //Just for consistency
801
- $module_header['file'] = $module_filename; //Used later to load the module
802
-
803
- //Apply defaults
804
- foreach($defaults as $field => $default_value){
805
- if ( empty($module_header[$field]) ){
806
- $module_header[$field] = $default_value;
807
- }
808
- }
809
-
810
- //Convert bool/int fields from strings to native datatypes
811
- $module_header['ModuleLazyInit'] = $this->str_to_bool($module_header['ModuleLazyInit']);
812
- $module_header['ModuleHidden'] = $this->str_to_bool($module_header['ModuleHidden']);
813
- $module_header['ModuleAlwaysActive'] = $this->str_to_bool($module_header['ModuleAlwaysActive']);
814
- $module_header['ModuleRequiresPro'] = $this->str_to_bool($module_header['ModuleRequiresPro']);
815
- $module_header['ModulePriority'] = intval($module_header['ModulePriority']);
816
-
817
- return $module_header;
818
- }
819
-
820
- /**
821
- * Converts the strings "true" and "false" to boolean TRUE and FALSE, respectively.
822
- * Any other string will yield FALSE.
823
- *
824
- * @param string $value "true" or "false", case-insensitive.
825
- * @return bool
826
- */
827
- function str_to_bool($value){
828
- $value = trim(strtolower($value));
829
- return $value == 'true';
830
- }
831
-
832
- /**
833
- * Generates a PHP script that calls the __() i18n function with
834
- * the name and description of each available module. The generated
835
- * script is used to make module headers show up in the .POT file.
836
- *
837
- * @access private
838
- *
839
- * @return string
840
- */
841
- function _build_header_translation_code(){
842
- $this->_module_cache = null; //Clear the cache
843
- $modules = $this->get_modules();
844
-
845
- $strings = array();
846
- foreach($modules as $module_id => $module_header){
847
- if ( $module_header['ModuleHidden'] || ($module_id == 'write-module-placeholders')) {
848
- continue;
849
- }
850
- if ( !empty($module_header['Name']) ){
851
- $strings[] = sprintf(
852
- '_x("%s", "module name", "broken-link-checker");',
853
- str_replace('"', '\"', $module_header['Name'])
854
- );
855
- }
856
- }
857
-
858
- return "<?php\n" . implode("\n", $strings) . "\n";
859
- }
860
- }
1
+ <?php
2
+
3
+ class blcModuleManager {
4
+
5
+ /* @var blcConfigurationManager */
6
+ var $plugin_conf;
7
+ var $module_dir = '';
8
+
9
+ var $_module_cache;
10
+ var $_category_cache;
11
+ var $_category_cache_active;
12
+ var $_virtual_modules = array();
13
+
14
+ var $loaded;
15
+ var $instances;
16
+ var $default_active_modules;
17
+
18
+
19
+ /**
20
+ * Class "constructor".
21
+ *
22
+ * @param array $default_active_modules An array of module ids specifying which modules are active by default.
23
+ * @return void
24
+ */
25
+ function init($default_active_modules = null){
26
+ $this->module_dir = realpath(dirname(__FILE__) . '/../modules');
27
+
28
+ $this->plugin_conf = blc_get_configuration();
29
+ $this->default_active_modules = $default_active_modules;
30
+
31
+ $this->loaded = array();
32
+ $this->instances = array();
33
+
34
+ add_filter('extra_plugin_headers', array(&$this, 'inject_module_headers'));
35
+ }
36
+
37
+ /**
38
+ * Get an instance of the module manager.
39
+ *
40
+ * @param array|null $default_active_modules
41
+ * @return blcModuleManager
42
+ */
43
+ static function getInstance($default_active_modules = null){
44
+ static $instance = null;
45
+ if ( is_null($instance) ){
46
+ $instance = new blcModuleManager();
47
+ $instance->init($default_active_modules);
48
+ }
49
+ return $instance;
50
+ }
51
+
52
+ /**
53
+ * Retrieve a list of all installed BLC modules.
54
+ *
55
+ * This is essentially a slightly modified copy of get_plugins().
56
+ *
57
+ * @return array An associative array of module headers indexed by module ID.
58
+ */
59
+ function get_modules(){
60
+ if ( !isset($this->_module_cache) ){
61
+ //Refresh the module cache.
62
+
63
+ $relative_path = '/' . plugin_basename($this->module_dir);
64
+ if ( !function_exists('get_plugins') ){
65
+ //BUG: Potentional security flaw/bug. plugin.php is not meant to be loaded outside admin panel.
66
+ require_once(ABSPATH . 'wp-admin/includes/plugin.php');
67
+ }
68
+ $modules = get_plugins( $relative_path );
69
+
70
+ $this->_module_cache = array();
71
+
72
+ foreach($modules as $module_filename => $module_header){
73
+ //Figure out the module ID. If not specified, it is equal to module's filename (sans the .php)
74
+ if ( !empty($module_header['ModuleID']) ){
75
+ $module_id = strtolower(trim($module_header['ModuleID']));
76
+ } else {
77
+ $module_id = strtolower(basename($module_filename, '.php'));
78
+ }
79
+
80
+ $module_header = $this->normalize_module_header($module_header, $module_id, $module_filename);
81
+ $this->_module_cache[$module_id] = $module_header;
82
+ }
83
+
84
+ $this->_category_cache = null;
85
+ }
86
+
87
+ return array_merge($this->_module_cache, $this->_virtual_modules);
88
+ }
89
+
90
+ /**
91
+ * Retrieve modules that match a specific category, or all modules sorted by categories.
92
+ *
93
+ * If a category ID is specified, this method returns the modules that have the "ModuleCategory:"
94
+ * file header set to that value, or an empty array if no modules match that category. The
95
+ * return array is indexed by module id :
96
+ * [module_id1 => module1_data, module_id1 => module2_data, ...]
97
+ *
98
+ * If category is omitted, this method returns a list of all categories plus the modules
99
+ * they contain. Only categories that have at least one module will be included. The return
100
+ * value is an array of arrays, indexed by category ID :
101
+ * [category1 => [module1_id => module1_data, module2_id => module2_data, ...], ...]
102
+ *
103
+ *
104
+ * @param string $category Category id, e.g. "parser" or "container". Optional.
105
+ * @param bool $markup Apply markup to module headers. Not implemented.
106
+ * @param bool $translate Translate module headers. Defaults to false.
107
+ * @return array An array of categories or module data.
108
+ */
109
+ function get_modules_by_category($category = '', $markup = false, $translate = false){
110
+ if ( !isset($this->_category_cache) ){
111
+ $this->_category_cache = $this->sort_into_categories($this->get_modules());
112
+ }
113
+
114
+ if ( empty($category) ){
115
+ if ( $markup || $translate ){
116
+
117
+ //Translate/apply markup to module headers
118
+ $processed = array();
119
+ foreach($this->_category_cache as $category_id => $modules){
120
+ $processed[$category_id] = array();
121
+ foreach($modules as $module_id => $module_data){
122
+ if ( $translate ){
123
+ $module_data['Name'] = _x($module_data['Name'], 'module name', 'broken-link-checker');
124
+ }
125
+ $processed[$category_id][$module_id] = $module_data;
126
+ }
127
+ }
128
+
129
+ return $processed;
130
+ } else {
131
+ return $this->_category_cache;
132
+ }
133
+ } else {
134
+ if ( isset($this->_category_cache[$category]) ){
135
+ if ( $markup || $translate ){
136
+ //Translate/apply markup to module headers
137
+ $processed = array();
138
+ foreach($this->_category_cache[$category] as $module_id => $module_data){
139
+ if ( $translate ){
140
+ $module_data['Name'] = _x($module_data['Name'], 'module name', 'broken-link-checker');
141
+ }
142
+ $processed[$module_id] = $module_data;
143
+ }
144
+ return $processed;
145
+ } else {
146
+ return $this->_category_cache[$category];
147
+ }
148
+ } else {
149
+ return array();
150
+ }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Retrieve active modules that match a specific category, or all active modules sorted by categories.
156
+ *
157
+ * @see blcModuleManager::get_modules_by_category()
158
+ *
159
+ * @param string $category Category id. Optional.
160
+ * @return array An associative array of categories or module data.
161
+ */
162
+ function get_active_by_category($category = ''){
163
+ if ( !isset($this->_category_cache_active) ){
164
+ $this->_category_cache_active = $this->sort_into_categories($this->get_active_modules());
165
+ }
166
+
167
+ if ( empty($category) ){
168
+ return $this->_category_cache_active;
169
+ } else {
170
+ if ( isset($this->_category_cache_active[$category]) ){
171
+ return $this->_category_cache_active[$category];
172
+ } else {
173
+ return array();
174
+ }
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Get the module ids of all active modules that belong to a specific category,
180
+ * quoted and ready for use in SQL.
181
+ *
182
+ * @param string $category Category ID. If not specified, a list of all active modules will be returned.
183
+ * @return string A comma separated list of single-quoted module ids, e.g. 'module-foo','module-bar','modbaz'
184
+ */
185
+ function get_escaped_ids($category = ''){
186
+ global $wpdb;
187
+
188
+ if ( empty($category) ){
189
+ $modules = $this->get_active_modules();
190
+ } else {
191
+ $modules = $this->get_active_by_category($category);
192
+ }
193
+
194
+ $modules = array_map('esc_sql', array_keys($modules));
195
+ $modules = "'" . implode("', '", $modules) . "'";
196
+
197
+ return $modules;
198
+ }
199
+
200
+ /**
201
+ * Sort a list of modules into categories. Inside each category, modules are sorted by priority (descending).
202
+ *
203
+ * @access private
204
+ *
205
+ * @param array $modules
206
+ * @return array
207
+ */
208
+ function sort_into_categories($modules){
209
+ $categories = array();
210
+
211
+ foreach($modules as $module_id => $module_data){
212
+ $cat = $module_data['ModuleCategory'];
213
+ if ( isset($categories[$cat]) ){
214
+ $categories[$cat][$module_id] = $module_data;
215
+ } else {
216
+ $categories[$cat] = array($module_id => $module_data);
217
+ }
218
+ }
219
+
220
+ foreach($categories as $cat => $cat_modules){
221
+ uasort($categories[$cat], array(&$this, 'compare_priorities'));
222
+ }
223
+
224
+ return $categories;
225
+ }
226
+
227
+ /**
228
+ * Callback for sorting modules by priority.
229
+ *
230
+ * @access private
231
+ *
232
+ * @param array $a First module header.
233
+ * @param array $b Second module header.
234
+ * @return int
235
+ */
236
+ function compare_priorities($a, $b){
237
+ return $b['ModulePriority'] - $a['ModulePriority'];
238
+ }
239
+
240
+ /**
241
+ * Retrieve a reference to an active module.
242
+ *
243
+ * Each module is instantiated only once, so if the module was already loaded you'll get back
244
+ * a reference to the existing module object. If the module isn't loaded or instantiated yet,
245
+ * the function will do it automatically (but only for active modules).
246
+ *
247
+ * @param string $module_id Module ID.
248
+ * @param bool $autoload Optional. Whether to load the module file if it's not loaded yet. Defaults to TRUE.
249
+ * @param string $category Optional. Return the module only if it's in a specific category. Categories are ignored by default.
250
+ * @return blcModule A reference to a module object, or NULL on error.
251
+ */
252
+ function get_module($module_id, $autoload = true, $category=''){
253
+ $no_result = null;
254
+ if ( !is_string($module_id) ){
255
+ //$backtrace = debug_backtrace();
256
+ //FB::error($backtrace, "get_module called with a non-string argument");
257
+ return $no_result;
258
+ }
259
+
260
+ if ( empty($this->loaded[$module_id]) ){
261
+ if ( $autoload && $this->is_active($module_id) ){
262
+ if ( !$this->load_module($module_id) ){
263
+ return $no_result;
264
+ }
265
+ } else {
266
+ return $no_result;
267
+ }
268
+ }
269
+
270
+ if ( !empty($category) ){
271
+ $data = $this->get_module_data($module_id);
272
+ if ( $data['ModuleCategory'] != $category ){
273
+ return $no_result;
274
+ }
275
+ }
276
+
277
+ $module = $this->init_module($module_id);
278
+ return $module;
279
+ }
280
+
281
+ /**
282
+ * Retrieve the header data of a specific module.
283
+ * Uses cached module info if available.
284
+ *
285
+ * @param string $module_id
286
+ * @param bool $use_active_cache Check the active module cache before the general one. Defaults to true.
287
+ * @return array Associative array of module data, or FALSE if the specified module was not found.
288
+ */
289
+ function get_module_data($module_id, $use_active_cache = true){
290
+ //Check virtual modules
291
+ if ( isset($this->_virtual_modules[$module_id]) ){
292
+ return $this->_virtual_modules[$module_id];
293
+ }
294
+
295
+ //Check active modules
296
+ if ( $use_active_cache && isset($this->plugin_conf->options['active_modules'][$module_id]) ){
297
+ return $this->plugin_conf->options['active_modules'][$module_id];
298
+ }
299
+
300
+ //Otherwise, use the general module cache
301
+ if ( !isset($this->_module_cache) ){
302
+ $this->get_modules(); //Populates the cache
303
+ }
304
+
305
+ if ( isset($this->_module_cache[$module_id]) ){
306
+ return $this->_module_cache[$module_id];
307
+ } else {
308
+ return false;
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Retrieve a list of active modules.
314
+ *
315
+ * The list of active modules is stored in the 'active_modules' key of the
316
+ * plugin configuration object. If this key is not set, this function will
317
+ * create it and populate it using the list of default active modules passed
318
+ * to the module manager's constructor.
319
+ *
320
+ * @return array Associative array of module data indexed by module ID.
321
+ */
322
+ function get_active_modules(){
323
+ if ( isset($this->plugin_conf->options['active_modules']) ){
324
+ return $this->plugin_conf->options['active_modules'];
325
+ }
326
+
327
+ $active = array();
328
+ $modules = $this->get_modules();
329
+
330
+ if ( is_array($this->default_active_modules) ){
331
+ foreach($this->default_active_modules as $module_id){
332
+ if ( array_key_exists($module_id, $modules) ){
333
+ $active[$module_id] = $modules[$module_id];
334
+ }
335
+ }
336
+ }
337
+
338
+ $this->plugin_conf->options['active_modules'] = $active;
339
+ $this->plugin_conf->save_options();
340
+
341
+ return $this->plugin_conf->options['active_modules'];
342
+ }
343
+
344
+ /**
345
+ * Determine if module is active.
346
+ *
347
+ * @param string $module_id
348
+ * @return bool
349
+ */
350
+ function is_active($module_id){
351
+ return array_key_exists($module_id, $this->get_active_modules());
352
+ }
353
+
354
+ /**
355
+ * Activate a module.
356
+ * Does nothing if the module is already active.
357
+ *
358
+ * @param string $module_id
359
+ * @return bool True if module was activated successfully, false otherwise.
360
+ */
361
+ function activate($module_id){
362
+ if ( $this->is_active($module_id) ){
363
+ return true;
364
+ }
365
+
366
+ //Retrieve the module header
367
+ $module_data = $this->get_module_data($module_id, false);
368
+ if ( !$module_data ){
369
+ return false;
370
+ }
371
+
372
+ //Attempt to load the module
373
+ if ( $this->load_module($module_id, $module_data) ){
374
+ //Okay, if it loads, we can assume it works.
375
+ $this->plugin_conf->options['active_modules'][$module_id] = $module_data;
376
+ $this->plugin_conf->save_options();
377
+ //Invalidate the per-category active module cache
378
+ $this->_category_cache_active = null;
379
+
380
+ //Notify the module that it's been activated
381
+ $module = $this->get_module($module_id);
382
+ if ( $module ){
383
+ $module->activated();
384
+ }
385
+ return true;
386
+ } else {
387
+ return false;
388
+ }
389
+ }
390
+
391
+ /**
392
+ * Deactivate a module.
393
+ * Does nothing if the module is already inactive.
394
+ *
395
+ * @param string $module_id
396
+ * @return bool
397
+ */
398
+ function deactivate($module_id){
399
+ if ( !$this->is_active($module_id) ){
400
+ return true;
401
+ }
402
+
403
+ //Some modules are supposed to be always active and thus can't be deactivated
404
+ $module_data = $this->get_module_data($module_id, false);
405
+ if ( isset($module_data['ModuleAlwaysActive']) && $module_data['ModuleAlwaysActive'] ){
406
+ return false;
407
+ }
408
+
409
+ //Notify the module that it's being deactivated
410
+ $module = $this->get_module($module_id);
411
+ if ( $module ){
412
+ $module->deactivated();
413
+ }
414
+
415
+ unset($this->plugin_conf->options['active_modules'][$module_id]);
416
+
417
+ //Keep track of when each module was last deactivated. Used for parser resynchronization.
418
+ if ( isset($this->plugin_conf->options['module_deactivated_when']) ){
419
+ $this->plugin_conf->options['module_deactivated_when'][$module_id] = current_time('timestamp');
420
+ } else {
421
+ $this->plugin_conf->options['module_deactivated_when'] = array(
422
+ $module_id => current_time('timestamp'),
423
+ );
424
+ }
425
+ $this->plugin_conf->save_options();
426
+
427
+ $this->_category_cache_active = null; //Invalidate the by-category cache since we just changed something
428
+ return true;
429
+ }
430
+
431
+ /**
432
+ * Determine when a module was last deactivated.
433
+ *
434
+ * @param string $module_id Module ID.
435
+ * @return int Timestamp of last deactivation, or 0 if the module has never been deactivated.
436
+ */
437
+ function get_last_deactivation_time($module_id){
438
+ if ( isset($this->plugin_conf->options['module_deactivated_when'][$module_id]) ){
439
+ return $this->plugin_conf->options['module_deactivated_when'][$module_id];
440
+ } else {
441
+ return 0;
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Set the current list of active modules. If any of the modules are not currently active,
447
+ * they will be activated. Any currently active modules that are not on the new list will
448
+ * be deactivated.
449
+ *
450
+ * @param array $ids An array of module IDs.
451
+ * @return void
452
+ */
453
+ function set_active_modules($ids){
454
+ $current_active = array_keys($this->get_active_modules());
455
+
456
+ $activate = array_diff($ids, $current_active);
457
+ $deactivate = array_diff($current_active, $ids);
458
+
459
+ //Deactivate any modules not present in the new list
460
+ foreach($deactivate as $module_id){
461
+ $this->deactivate($module_id);
462
+ }
463
+
464
+ //Activate modules present in the new list but not in the old list
465
+ foreach($activate as $module_id){
466
+ $this->activate($module_id);
467
+ }
468
+
469
+ //Ensure all active modules have the latest headers
470
+ $this->refresh_active_module_cache();
471
+
472
+ //Invalidate the per-category active module cache
473
+ $this->_category_cache_active = null;
474
+ }
475
+
476
+ /**
477
+ * Send the activation message to all currently active plugins when the plugin is activated.
478
+ *
479
+ * @return void
480
+ */
481
+ function plugin_activated(){
482
+ global $blclog;
483
+
484
+ //Ensure all active modules have the latest headers
485
+ $blclog->log('... Updating module cache');
486
+ $start = microtime(true);
487
+ $this->refresh_active_module_cache();
488
+ $blclog->info(sprintf('... Cache refresh took %.3f seconds', microtime(true) - $start));
489
+
490
+ //Notify them that we've been activated
491
+ $blclog->log('... Loading modules');
492
+ $start = microtime(true);
493
+ $this->load_modules();
494
+ $blclog->info(sprintf('... %d modules loaded in %.3f seconds', count($this->loaded), microtime(true) - $start));
495
+
496
+ $active = $this->get_active_modules();
497
+ foreach($active as $module_id => $module_data){
498
+ $blclog->log( sprintf('... Notifying module "%s"', $module_id) );
499
+ $module = $this->get_module($module_id);
500
+ if ( $module ){
501
+ $module->plugin_activated();
502
+ } else {
503
+ $blclog->warn(sprintf('... Module "%s" failed to load!', $module_id));
504
+ }
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Refresh the cached data of all active modules.
510
+ *
511
+ * @return array An updated list of active modules.
512
+ */
513
+ function refresh_active_module_cache(){
514
+ $modules = $this->get_modules();
515
+ foreach($this->plugin_conf->options['active_modules'] as $module_id => $module_header){
516
+ if ( array_key_exists($module_id, $modules) ){
517
+ $this->plugin_conf->options['active_modules'][$module_id] = $modules[$module_id];
518
+ }
519
+ }
520
+ $this->plugin_conf->save_options();
521
+ $this->_category_cache_active = null; //Invalidate the by-category active module cache
522
+ return $this->plugin_conf->options['active_modules'];
523
+ }
524
+
525
+ /**
526
+ * Load active modules.
527
+ *
528
+ * @param string $context Optional. If specified, only the modules that match this context (or the "all" context) will be loaded.
529
+ * @return void
530
+ */
531
+ function load_modules($context = ''){
532
+ $active = $this->get_active_modules();
533
+ //Avoid trying to load a virtual module before the module that registered it has been loaded.
534
+ $active = $this->put_virtual_last($active);
535
+
536
+ foreach($active as $module_id => $module_data){
537
+ //Load the module
538
+ $should_load = ($module_data['ModuleContext'] == 'all') || (!empty($context) && $module_data['ModuleContext'] == $context);
539
+ if ( $should_load ){
540
+ $this->load_module($module_id, $module_data);
541
+ }
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Load and possibly instantiate a specific module.
547
+ *
548
+ * @access private
549
+ *
550
+ * @param string $module_id
551
+ * @param array $module_data
552
+ * @return bool True if the module was successfully loaded, false otherwise.
553
+ */
554
+ function load_module($module_id, $module_data = null){
555
+
556
+ //Only load each module once.
557
+ if ( !empty($this->loaded[$module_id]) ){
558
+ return true;
559
+ }
560
+
561
+ if ( !isset($module_data) ){
562
+ $module_data = $this->get_module_data($module_id);
563
+ if ( empty($module_data) ){
564
+ return false;
565
+ }
566
+ }
567
+
568
+ //Load a normal module
569
+ if ( empty($module_data['virtual']) ){
570
+
571
+ //Skip invalid and missing modules
572
+ if ( empty($module_data['file']) ){
573
+ return false;
574
+ }
575
+
576
+ //Get the full path to the module file
577
+ $filename = $this->module_dir . '/' . $module_data['file'];
578
+ if ( !file_exists($filename) ){
579
+ return false;
580
+ }
581
+
582
+ //Load it
583
+ include $filename;
584
+ $this->loaded[$module_id] = true;
585
+
586
+ } else {
587
+
588
+ //Virtual modules don't need to be explicitly loaded, but they must
589
+ //be registered.
590
+ if ( !array_key_exists($module_id, $this->_virtual_modules) ) {
591
+ return false;
592
+ }
593
+ $this->loaded[$module_id] = true;
594
+
595
+ }
596
+
597
+ //Instantiate the main module class unless lazy init is on (default is off)
598
+ if ( !array_key_exists($module_id, $this->instances) ){ //Only try to instantiate once
599
+ if ( !$module_data['ModuleLazyInit'] ){
600
+ $this->init_module($module_id, $module_data);
601
+ }
602
+ }
603
+
604
+ return true;
605
+ }
606
+
607
+ /**
608
+ * Instantiate a certain module.
609
+ *
610
+ * @param string $module_id
611
+ * @param array $module_data Optional. The header data of the module that needs to be instantiated. If not specified, it will be retrieved automatically.
612
+ * @return object The newly instantiated module object (extends blcModule), or NULL on error.
613
+ */
614
+ function init_module($module_id, $module_data = null){
615
+ //Each module is only instantiated once.
616
+ if ( isset($this->instances[$module_id]) ){
617
+ return $this->instances[$module_id];
618
+ }
619
+
620
+ if ( !isset($module_data) ){
621
+ $module_data = $this->get_module_data($module_id);
622
+ if ( empty($module_data) ){
623
+ return null;
624
+ }
625
+ }
626
+
627
+ if ( !empty($module_data['ModuleClassName']) && class_exists($module_data['ModuleClassName']) ){
628
+ $className = $module_data['ModuleClassName'];
629
+ $this->instances[$module_id] = new $className(
630
+ $module_id,
631
+ $module_data,
632
+ $this->plugin_conf,
633
+ $this
634
+ );
635
+ return $this->instances[$module_id];
636
+ };
637
+
638
+ return null;
639
+ }
640
+
641
+ function is_instantiated($module_id){
642
+ return !empty($this->instances[$module_id]);
643
+ }
644
+
645
+ /**
646
+ * Register a virtual module.
647
+ *
648
+ * Virtual modules are the same as normal modules, except that they can be added
649
+ * on the fly, e.g. by other modules.
650
+ *
651
+ * @param string $module_id Module Id.
652
+ * @param string $module_data Associative array of module data. All module header fields are allowed, except ModuleID.
653
+ * @return void
654
+ */
655
+ function register_virtual_module($module_id, $module_data){
656
+ $module_data = $this->normalize_module_header($module_data, $module_id);
657
+ $module_data['virtual'] = true;
658
+ $this->_virtual_modules[$module_id] = $module_data;
659
+ }
660
+
661
+ /**
662
+ * Sort an array of modules so that all virtual modules are placed at its end.
663
+ *
664
+ * @param array $modules Input array, [module_id => module_data, ...].
665
+ * @return array Sorted array.
666
+ */
667
+ function put_virtual_last($modules){
668
+ uasort($modules, array(&$this, 'compare_virtual_flags'));
669
+ return $modules;
670
+ }
671
+
672
+ /**
673
+ * Callback function for sorting modules by the state of their 'virtual' flag.
674
+ *
675
+ * @param array $a Associative array of module A data
676
+ * @param array $b Associative array of module B data
677
+ * @return int
678
+ */
679
+ function compare_virtual_flags($a, $b){
680
+ if ( empty($a['virtual']) ){
681
+ return empty($b['virtual'])?0:-1;
682
+ } else {
683
+ return empty($b['virtual'])?1:0;
684
+ }
685
+ }
686
+
687
+ /**
688
+ * Validate active modules.
689
+ *
690
+ * Validates all active modules, deactivates invalid ones and returns
691
+ * an array of deactivated modules.
692
+ *
693
+ * @return array
694
+ */
695
+ function validate_active_modules(){
696
+ $active = $this->get_active_modules();
697
+ if ( empty($active) ){
698
+ return array();
699
+ }
700
+
701
+ $invalid = array();
702
+ foreach($active as $module_id => $module_data){
703
+ $rez = $this->validate_module($module_data);
704
+ if ( is_wp_error($rez) ){
705
+ $invalid[$module_id] = $rez;
706
+ $this->deactivate($module_id);
707
+ }
708
+ }
709
+
710
+ return $invalid;
711
+ }
712
+
713
+ /**
714
+ * Validate module data.
715
+ *
716
+ * Checks that the module file exists or that the module
717
+ * is a currently registered virtual module.
718
+ *
719
+ * @param array $module_data Associative array of module data.
720
+ * @return bool|WP_Error True on success, an error object if the module fails validation
721
+ */
722
+ function validate_module($module_data){
723
+ if ( empty($module_data['ModuleID']) ){
724
+ return new WP_Error('invalid_cached_header', 'The cached module header is invalid');
725
+ }
726
+
727
+ if ( empty($module_data['virtual']) ){
728
+ //Normal modules must have a valid filename
729
+ if ( empty($module_data['file']) ){
730
+ return new WP_Error('module_not_found', 'Invalid module file');
731
+ }
732
+
733
+ $filename = $this->module_dir . '/' . $module_data['file'];
734
+ if ( !file_exists($filename) ){
735
+ return new WP_Error('module_not_found', 'Module file not found');
736
+ }
737
+
738
+ //The module file header must be in the proper format. While $module_data comes
739
+ //from cache and can be assumed to be correct, get_modules() will attempt to load
740
+ //the current headers and only return modules with semi-valid headers.
741
+ $installed = $this->get_modules();
742
+ if ( !array_key_exists($module_data['ModuleID'], $installed) ){
743
+ return new WP_Error('invalid_module_header', 'Invalid module header');
744
+ }
745
+ } else {
746
+ //Virtual modules need to be currently registered
747
+ if ( !array_key_exists($module_data['ModuleID'], $this->_virtual_modules) ){
748
+ return new WP_Error('module_not_registered', 'The virtual module is not registered');
749
+ }
750
+ }
751
+
752
+ return true;
753
+ }
754
+
755
+ /**
756
+ * Add BLC-module specific headers to the list of allowed plugin headers. This
757
+ * lets us use get_plugins() to retrieve the list of BLC modules.
758
+ *
759
+ * @param array $headers Currently known plugin headers.
760
+ * @return array New plugin headers.
761
+ */
762
+ function inject_module_headers($headers){
763
+ $module_headers = array(
764
+ 'ModuleID',
765
+ 'ModuleCategory',
766
+ 'ModuleContext',
767
+ 'ModuleLazyInit',
768
+ 'ModuleClassName',
769
+ 'ModulePriority',
770
+ 'ModuleCheckerUrlPattern',
771
+ 'ModuleHidden', //Don't show the module in the Settings page
772
+ 'ModuleAlwaysActive', //Module can't be deactivated.
773
+ 'ModuleRequiresPro', //Can only be activated in the Pro version
774
+ );
775
+
776
+ return array_merge($headers, $module_headers);
777
+ }
778
+
779
+ /**
780
+ * Normalize a module header, using defaults where necessary.
781
+ *
782
+ * @param array $module_header Module header, as read from the module's .php file.
783
+ * @param string $module_id Module ID.
784
+ * @param string $module_filename Module filename. Optional.
785
+ * @return array Normalized module header.
786
+ */
787
+ function normalize_module_header($module_header, $module_id, $module_filename = ''){
788
+ //Default values for optional module header fields
789
+ $defaults = array(
790
+ 'ModuleContext' => 'all',
791
+ 'ModuleCategory' => 'other',
792
+ 'ModuleLazyInit' => 'false',
793
+ 'ModulePriority' => '0',
794
+ 'ModuleHidden' => 'false',
795
+ 'ModuleAlwaysActive' => 'false',
796
+ 'ModuleRequiresPro' => 'false',
797
+ 'TextDomain' => 'broken-link-checker', //For translating module headers
798
+ );
799
+
800
+ $module_header['ModuleID'] = $module_id; //Just for consistency
801
+ $module_header['file'] = $module_filename; //Used later to load the module
802
+
803
+ //Apply defaults
804
+ foreach($defaults as $field => $default_value){
805
+ if ( empty($module_header[$field]) ){
806
+ $module_header[$field] = $default_value;
807
+ }
808
+ }
809
+
810
+ //Convert bool/int fields from strings to native datatypes
811
+ $module_header['ModuleLazyInit'] = $this->str_to_bool($module_header['ModuleLazyInit']);
812
+ $module_header['ModuleHidden'] = $this->str_to_bool($module_header['ModuleHidden']);
813
+ $module_header['ModuleAlwaysActive'] = $this->str_to_bool($module_header['ModuleAlwaysActive']);
814
+ $module_header['ModuleRequiresPro'] = $this->str_to_bool($module_header['ModuleRequiresPro']);
815
+ $module_header['ModulePriority'] = intval($module_header['ModulePriority']);
816
+
817
+ return $module_header;
818
+ }
819
+
820
+ /**
821
+ * Converts the strings "true" and "false" to boolean TRUE and FALSE, respectively.
822
+ * Any other string will yield FALSE.
823
+ *
824
+ * @param string $value "true" or "false", case-insensitive.
825
+ * @return bool
826
+ */
827
+ function str_to_bool($value){
828
+ $value = trim(strtolower($value));
829
+ return $value == 'true';
830
+ }
831
+
832
+ /**
833
+ * Generates a PHP script that calls the __() i18n function with
834
+ * the name and description of each available module. The generated
835
+ * script is used to make module headers show up in the .POT file.
836
+ *
837
+ * @access private
838
+ *
839
+ * @return string
840
+ */
841
+ function _build_header_translation_code(){
842
+ $this->_module_cache = null; //Clear the cache
843
+ $modules = $this->get_modules();
844
+
845
+ $strings = array();
846
+ foreach($modules as $module_id => $module_header){
847
+ if ( $module_header['ModuleHidden'] || ($module_id == 'write-module-placeholders')) {
848
+ continue;
849
+ }
850
+ if ( !empty($module_header['Name']) ){
851
+ $strings[] = sprintf(
852
+ '_x("%s", "module name", "broken-link-checker");',
853
+ str_replace('"', '\"', $module_header['Name'])
854
+ );
855
+ }
856
+ }
857
+
858
+ return "<?php\n" . implode("\n", $strings) . "\n";
859
+ }
860
+ }
includes/modules.php CHANGED
@@ -1,35 +1,35 @@
1
- <?php
2
-
3
- /**
4
- * Load all files pertaining to BLC's module subsystem
5
- */
6
-
7
- require 'module-manager.php';
8
- require 'module-base.php';
9
-
10
- require 'containers.php';
11
- require 'checkers.php';
12
- require 'parsers.php';
13
-
14
- $blc_module_manager = blcModuleManager::getInstance(array(
15
- //List of modules active by default
16
- 'http', //Link checker for the HTTP(s) protocol
17
- 'link', //HTML link parser
18
- 'image', //HTML image parser
19
- 'metadata', //Metadata (custom field) parser
20
- 'url_field', //URL field parser
21
- 'comment', //Comment container
22
- 'custom_field', //Post metadata container (aka custom fields)
23
- 'acf_field', //Post acf container (aka advanced custom fields)
24
- 'acf', //acf parser
25
- 'post', //Post content container
26
- 'page', //Page content container
27
- 'youtube-checker', //Video checker using the YouTube API
28
- 'youtube-iframe', //Embedded YouTube video container
29
- 'dummy', //Dummy container used as a fallback
30
- ));
31
-
32
- require 'any-post.php';
33
-
34
- //Let other plugins register virtual modules.
35
  do_action('blc_register_modules', $blc_module_manager);
1
+ <?php
2
+
3
+ /**
4
+ * Load all files pertaining to BLC's module subsystem
5
+ */
6
+
7
+ require 'module-manager.php';
8
+ require 'module-base.php';
9
+
10
+ require 'containers.php';
11
+ require 'checkers.php';
12
+ require 'parsers.php';
13
+
14
+ $blc_module_manager = blcModuleManager::getInstance(array(
15
+ //List of modules active by default
16
+ 'http', //Link checker for the HTTP(s) protocol
17
+ 'link', //HTML link parser
18
+ 'image', //HTML image parser
19
+ 'metadata', //Metadata (custom field) parser
20
+ 'url_field', //URL field parser
21
+ 'comment', //Comment container
22
+ 'custom_field', //Post metadata container (aka custom fields)
23
+ 'acf_field', //Post acf container (aka advanced custom fields)
24
+ 'acf', //acf parser
25
+ 'post', //Post content container
26
+ 'page', //Page content container
27
+ 'youtube-checker', //Video checker using the YouTube API
28
+ 'youtube-iframe', //Embedded YouTube video container
29
+ 'dummy', //Dummy container used as a fallback
30
+ ));
31
+
32
+ require 'any-post.php';
33
+
34
+ //Let other plugins register virtual modules.
35
  do_action('blc_register_modules', $blc_module_manager);
includes/parsers.php CHANGED
@@ -1,365 +1,365 @@
1
- <?php
2
-
3
- /**
4
- * A base class for parsers.
5
- *
6
- * In the context of this plugin, a "parser" is a class that knows how to extract or modify
7
- * a specific type of links from a given piece of text. For example, there could be a "HTML Link"
8
- * parser that knows how to find and modify standard HTML links such as this one :
9
- * <a href="http://example.com/">Example</a>
10
- *
11
- * Other parsers could extract plaintext URLs or handle metadata fields.
12
- *
13
- * Each parser has a list of supported formats (e.g. "html", "plaintext", etc) and container types
14
- * (e.g. "post", "comment", "blogroll", etc). When something needs to be parsed, the involved
15
- * container class will look up the parsers that support the relevant format or the container's type,
16
- * and apply them to the to-be-parsed string.
17
- *
18
- * All sub-classes of blcParser should override at least the blcParser::parse() method.
19
- *
20
- * @see blcContainer::$fields
21
- *
22
- * @package Broken Link Checker
23
- * @access public
24
- */
25
- class blcParser extends blcModule {
26
-
27
- var $parser_type;
28
- var $supported_formats = array();
29
- var $supported_containers = array();
30
-
31
- /**
32
- * Initialize the parser. Nothing much here.
33
- *
34
- * @return void
35
- */
36
- function init(){
37
- parent::init();
38
- $this->parser_type = $this->module_id;
39
- }
40
-
41
- /**
42
- * Called when the parser is activated.
43
- *
44
- * @return void
45
- */
46
- function activated(){
47
- parent::activated();
48
- $this->resynch_relevant_containers();
49
- }
50
-
51
- /**
52
- * Called when BLC is activated.
53
- */
54
- function plugin_activated() {
55
- //Intentionally do nothing. BLC can not parse containers while it's inactive, so we can be
56
- //pretty sure that there are no already-parsed containers that need to be resynchronized.
57
- }
58
-
59
- /**
60
- * Mark containers that this parser might be interested in as unparsed.
61
- *
62
- * @uses blcContainerHelper::mark_as_unsynched_where()
63
- *
64
- * @param bool $only_return If true, just return the list of formats and container types without actually modifying any synch. records.
65
- * @return void|array Either nothing or an array in the form [ [format1=>timestamp1, ...], [container_type1=>timestamp1, ...] ]
66
- */
67
- function resynch_relevant_containers($only_return = false){
68
- global $blclog;
69
- $blclog->log(sprintf('...... Parser "%s" is marking relevant items as unsynched', $this->module_id));
70
-
71
- $last_deactivated = $this->module_manager->get_last_deactivation_time($this->module_id);
72
-
73
- $formats = array();
74
- foreach($this->supported_formats as $format){
75
- $formats[$format] = $last_deactivated;
76
- }
77
-
78
- $container_types = array();
79
- foreach($this->supported_containers as $container_type){
80
- $container_types[$container_type] = $last_deactivated;
81
- }
82
-
83
- if ( $only_return ){
84
- return array($formats, $container_types);
85
- } else {
86
- blcContainerHelper::mark_as_unsynched_where($formats, $container_types);
87
- }
88
- }
89
-
90
- /**
91
- * Parse a string for links.
92
- *
93
- * @param string $content The text to parse.
94
- * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
95
- * @param string $default_link_text
96
- * @return array An array of new blcLinkInstance objects. The objects will include info about the links found, but not about the corresponding container entity.
97
- */
98
- function parse($content, $base_url = '', $default_link_text = ''){
99
- return array();
100
- }
101
-
102
- /**
103
- * Change all links that have a certain URL to a new URL.
104
- *
105
- * @param string $content Look for links in this string.
106
- * @param string $new_url Change the links to this URL.
107
- * @param string $old_url The URL to look for.
108
- * @param string $old_raw_url The raw, not-normalized URL of the links to look for. Optional.
109
- *
110
- * @return array|WP_Error If successful, the return value will be an associative array with two
111
- * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
112
- * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
113
- */
114
- function edit($content, $new_url, $old_url, $old_raw_url){
115
- return new WP_Error(
116
- 'not_implemented',
117
- sprintf(__("Editing is not implemented in the '%s' parser", 'broken-link-checker'), $this->parser_type)
118
- );
119
- }
120
-
121
- /**
122
- * Remove all links that have a certain URL, leaving anchor text intact.
123
- *
124
- * @param string $content Look for links in this string.
125
- * @param string $url The URL to look for.
126
- * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
127
- * @return string Input string with all matching links removed.
128
- */
129
- function unlink($content, $url, $raw_url){
130
- return new WP_Error(
131
- 'not_implemented',
132
- sprintf(__("Unlinking is not implemented in the '%s' parser", 'broken-link-checker'), $this->parser_type)
133
- );
134
- }
135
-
136
- /**
137
- * Get the link text for printing in the "Broken Links" table.
138
- * Sub-classes should override this method and display the link text in a way appropriate for the link type.
139
- *
140
- * @param blcLinkInstance $instance
141
- * @param string $context
142
- * @return string HTML
143
- */
144
- function ui_get_link_text($instance, $context = 'display'){
145
- return $instance->link_text;
146
- }
147
-
148
- /**
149
- * Check if the parser supports editing the link text.
150
- *
151
- * @return bool
152
- */
153
- public function is_link_text_editable() {
154
- return false;
155
- }
156
-
157
- /**
158
- * Check if the parser supports editing the link URL.
159
- *
160
- * @return bool
161
- */
162
- public function is_url_editable() {
163
- return true;
164
- }
165
-
166
- /**
167
- * Turn a relative URL into an absolute one.
168
- *
169
- * WordPress 3.4 has WP_Http::make_absolute_url() which is well-tested but not as comprehensive
170
- * as this implementation. For example, WP_Http doesn't properly handle directory traversal with "..",
171
- * and it removes #anchors for no good reason. The BLC implementation deals with both pretty well.
172
- *
173
- * @param string $url Relative URL.
174
- * @param string $base_url Base URL. If omitted, the blog's root URL will be used.
175
- * @return string
176
- */
177
- function relative2absolute($url, $base_url = ''){
178
- if ( empty($base_url) ){
179
- $base_url = home_url();
180
- }
181
-
182
- $p = @parse_url($url);
183
- if(!$p) {
184
- //URL is a malformed
185
- return false;
186
- }
187
- if( isset($p["scheme"]) ) return $url;
188
-
189
- //If the relative URL is just a query string or anchor, simply attach it to the absolute URL and return
190
- $first_char = substr($url, 0, 1);
191
- if ( ($first_char == '?') || ($first_char == '#') ){
192
- return $base_url . $url;
193
- }
194
-
195
- $parts=(parse_url($base_url));
196
-
197
- //Protocol-relative URLs start with "//". We just need to prepend the right protocol.
198
- if ( substr($url, 0, 2) === '//' ) {
199
- $scheme = isset($parts['scheme']) ? $parts['scheme'] : 'http';
200
- return $scheme . ':'. $url;
201
- }
202
-
203
- if(substr($url,0,1)=='/') {
204
- //Relative URL starts with a slash => ignore the base path and jump straight to the root.
205
- $path_segments = explode("/", $url);
206
- array_shift($path_segments);
207
- } else {
208
- if(isset($parts['path'])){
209
- $aparts=explode('/',$parts['path']);
210
- array_pop($aparts);
211
- $aparts=array_filter($aparts);
212
- } else {
213
- $aparts=array();
214
- }
215
-
216
- //Merge together the base path & the relative path
217
- $aparts = array_merge($aparts, explode("/", $url));
218
-
219
- //Filter the merged path
220
- $path_segments = array();
221
- foreach($aparts as $part){
222
- if ( $part == '.' ){
223
- continue; //. = "this directory". It's basically a no-op, so we skip it.
224
- } elseif ( $part == '..' ) {
225
- array_pop($path_segments); //.. = one directory up. Remove the last seen path segment.
226
- } else {
227
- array_push($path_segments, $part); //Normal directory -> add it to the path.
228
- }
229
- }
230
- }
231
- $path = implode("/", $path_segments);
232
-
233
- //Build the absolute URL.
234
- $url = '';
235
- if($parts['scheme']) {
236
- $url = "$parts[scheme]://";
237
- }
238
- if(isset($parts['user'])) {
239
- $url .= $parts['user'];
240
- if(isset($parts['pass'])) {
241
- $url .= ":".$parts['pass'];
242
- }
243
- $url .= "@";
244
- }
245
- if(isset($parts['host'])) {
246
- $url .= $parts['host'];
247
- if(isset($parts['port'])) {
248
- $url .= ':' . $parts['port'];
249
- }
250
- $url .= '/';
251
- }
252
- $url .= $path;
253
-
254
- return $url;
255
- }
256
-
257
- /**
258
- * Apply a callback function to all links found in a string and return the results.
259
- *
260
- * The first argument passed to the callback function will be an associative array
261
- * of link data. If the optional $extra parameter is set, it will be passed as the
262
- * second argument to the callback function.
263
- *
264
- * The link data array will contain at least these keys :
265
- * 'href' - the URL of the link, as-is (i.e. without any sanitization or relative-to-absolute translation).
266
- * '#raw' - the raw link code, e.g. the entire '<a href="...">...</a>' tag of a HTML link.
267
- *
268
- * Sub-classes may also set additional keys.
269
- *
270
- * This method is currently used only internally, so sub-classes are not required
271
- * to implement it.
272
- *
273
- * @param string $content A text string to parse for links.
274
- * @param callback $callback Callback function to apply to all found links.
275
- * @param mixed $extra If the optional $extra param. is supplied, it will be passed as the second parameter to the function $callback.
276
- * @return array An array of all detected links after applying $callback to each of them.
277
- */
278
- function map($content, $callback, $extra = null){
279
- return array();
280
- }
281
-
282
- /**
283
- * Modify all links found in a string using a callback function.
284
- *
285
- * The first argument passed to the callback function will be an associative array
286
- * of link data. If the optional $extra parameter is set, it will be passed as the
287
- * second argument to the callback function. See the map() method of this class for
288
- * details on the first argument.
289
- *
290
- * The callback function should return either an associative array or a string. If
291
- * a string is returned, the parser will replace the current link with the contents
292
- * of that string. If an array is returned, the current link will be modified/rebuilt
293
- * by substituting the new values for the old ones (e.g. returning array with the key
294
- * 'href' set to 'http://example.com/' will replace the current link's URL with
295
- * http://example.com/).
296
- *
297
- * This method is currently only used internally, so sub-classes are not required
298
- * to implement it.
299
- *
300
- * @see blcParser::map()
301
- *
302
- * @param string $content A text string containing the links to edit.
303
- * @param callback $callback Callback function used to modify the links.
304
- * @param mixed $extra If supplied, $extra will be passed as the second parameter to the function $callback.
305
- * @return string The modified input string.
306
- */
307
- function multi_edit($content, $callback, $extra = null){
308
- return $content; //No-op
309
- }
310
- }
311
-
312
- /**
313
- * A helper class for working with parsers. All its methods should be called statically.
314
- *
315
- * @see blcParser
316
- *
317
- * @package Broken Link Checker
318
- * @access public
319
- */
320
- class blcParserHelper {
321
-
322
- /**
323
- * Get the parser matching a parser type ID.
324
- *
325
- * @uses blcModuleManager::get_module()
326
- *
327
- * @param string $parser_type
328
- * @return blcParser|null
329
- */
330
- static function get_parser( $parser_type ){
331
- $manager = blcModuleManager::getInstance();
332
- return $manager->get_module($parser_type, true, 'parser');
333
- }
334
-
335
- /**
336
- * Get all parsers that support either the specified format or the container type.
337
- * If a parser supports both, it will still be included only once.
338
- *
339
- * @param string $format
340
- * @param string $container_type
341
- * @return blcParser[]
342
- */
343
- static function get_parsers( $format, $container_type ){
344
- $found = array();
345
-
346
- //Retrieve a list of active parsers
347
- $manager = blcModuleManager::getInstance();
348
- $active_parsers = $manager->get_modules_by_category('parser');
349
-
350
- //Try each one
351
- foreach($active_parsers as $module_id => $module_data){
352
- $parser = $manager->get_module($module_id); //Will autoload if necessary
353
- if ( !$parser ){
354
- continue;
355
- }
356
-
357
- if ( in_array($format, $parser->supported_formats) || in_array($container_type, $parser->supported_containers) ){
358
- array_push($found, $parser);
359
- }
360
- }
361
-
362
- return $found;
363
- }
364
- }
365
-
1
+ <?php
2
+
3
+ /**
4
+ * A base class for parsers.
5
+ *
6
+ * In the context of this plugin, a "parser" is a class that knows how to extract or modify
7
+ * a specific type of links from a given piece of text. For example, there could be a "HTML Link"
8
+ * parser that knows how to find and modify standard HTML links such as this one :
9
+ * <a href="http://example.com/">Example</a>
10
+ *
11
+ * Other parsers could extract plaintext URLs or handle metadata fields.
12
+ *
13
+ * Each parser has a list of supported formats (e.g. "html", "plaintext", etc) and container types
14
+ * (e.g. "post", "comment", "blogroll", etc). When something needs to be parsed, the involved
15
+ * container class will look up the parsers that support the relevant format or the container's type,
16
+ * and apply them to the to-be-parsed string.
17
+ *
18
+ * All sub-classes of blcParser should override at least the blcParser::parse() method.
19
+ *
20
+ * @see blcContainer::$fields
21
+ *
22
+ * @package Broken Link Checker
23
+ * @access public
24
+ */
25
+ class blcParser extends blcModule {
26
+
27
+ var $parser_type;
28
+ var $supported_formats = array();
29
+ var $supported_containers = array();
30
+
31
+ /**
32
+ * Initialize the parser. Nothing much here.
33
+ *
34
+ * @return void
35
+ */
36
+ function init(){
37
+ parent::init();
38
+ $this->parser_type = $this->module_id;
39
+ }
40
+
41
+ /**
42
+ * Called when the parser is activated.
43
+ *
44
+ * @return void
45
+ */
46
+ function activated(){
47
+ parent::activated();
48
+ $this->resynch_relevant_containers();
49
+ }
50
+
51
+ /**
52
+ * Called when BLC is activated.
53
+ */
54
+ function plugin_activated() {
55
+ //Intentionally do nothing. BLC can not parse containers while it's inactive, so we can be
56
+ //pretty sure that there are no already-parsed containers that need to be resynchronized.
57
+ }
58
+
59
+ /**
60
+ * Mark containers that this parser might be interested in as unparsed.
61
+ *
62
+ * @uses blcContainerHelper::mark_as_unsynched_where()
63
+ *
64
+ * @param bool $only_return If true, just return the list of formats and container types without actually modifying any synch. records.
65
+ * @return void|array Either nothing or an array in the form [ [format1=>timestamp1, ...], [container_type1=>timestamp1, ...] ]
66
+ */
67
+ function resynch_relevant_containers($only_return = false){
68
+ global $blclog;
69
+ $blclog->log(sprintf('...... Parser "%s" is marking relevant items as unsynched', $this->module_id));
70
+
71
+ $last_deactivated = $this->module_manager->get_last_deactivation_time($this->module_id);
72
+
73
+ $formats = array();
74
+ foreach($this->supported_formats as $format){
75
+ $formats[$format] = $last_deactivated;
76
+ }
77
+
78
+ $container_types = array();
79
+ foreach($this->supported_containers as $container_type){
80
+ $container_types[$container_type] = $last_deactivated;
81
+ }
82
+
83
+ if ( $only_return ){
84
+ return array($formats, $container_types);
85
+ } else {
86
+ blcContainerHelper::mark_as_unsynched_where($formats, $container_types);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Parse a string for links.
92
+ *
93
+ * @param string $content The text to parse.
94
+ * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
95
+ * @param string $default_link_text
96
+ * @return array An array of new blcLinkInstance objects. The objects will include info about the links found, but not about the corresponding container entity.
97
+ */
98
+ function parse($content, $base_url = '', $default_link_text = ''){
99
+ return array();
100
+ }
101
+
102
+ /**
103
+ * Change all links that have a certain URL to a new URL.
104
+ *
105
+ * @param string $content Look for links in this string.
106
+ * @param string $new_url Change the links to this URL.
107
+ * @param string $old_url The URL to look for.
108
+ * @param string $old_raw_url The raw, not-normalized URL of the links to look for. Optional.
109
+ *
110
+ * @return array|WP_Error If successful, the return value will be an associative array with two
111
+ * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
112
+ * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
113
+ */
114
+ function edit($content, $new_url, $old_url, $old_raw_url){
115
+ return new WP_Error(
116
+ 'not_implemented',
117
+ sprintf(__("Editing is not implemented in the '%s' parser", 'broken-link-checker'), $this->parser_type)
118
+ );
119
+ }
120
+
121
+ /**
122
+ * Remove all links that have a certain URL, leaving anchor text intact.
123
+ *
124
+ * @param string $content Look for links in this string.
125
+ * @param string $url The URL to look for.
126
+ * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
127
+ * @return string Input string with all matching links removed.
128
+ */
129
+ function unlink($content, $url, $raw_url){
130
+ return new WP_Error(
131
+ 'not_implemented',
132
+ sprintf(__("Unlinking is not implemented in the '%s' parser", 'broken-link-checker'), $this->parser_type)
133
+ );
134
+ }
135
+
136
+ /**
137
+ * Get the link text for printing in the "Broken Links" table.
138
+ * Sub-classes should override this method and display the link text in a way appropriate for the link type.
139
+ *
140
+ * @param blcLinkInstance $instance
141
+ * @param string $context
142
+ * @return string HTML
143
+ */
144
+ function ui_get_link_text($instance, $context = 'display'){
145
+ return $instance->link_text;
146
+ }
147
+
148
+ /**
149
+ * Check if the parser supports editing the link text.
150
+ *
151
+ * @return bool
152
+ */
153
+ public function is_link_text_editable() {
154
+ return false;
155
+ }
156
+
157
+ /**
158
+ * Check if the parser supports editing the link URL.
159
+ *
160
+ * @return bool
161
+ */
162
+ public function is_url_editable() {
163
+ return true;
164
+ }
165
+
166
+ /**
167
+ * Turn a relative URL into an absolute one.
168
+ *
169
+ * WordPress 3.4 has WP_Http::make_absolute_url() which is well-tested but not as comprehensive
170
+ * as this implementation. For example, WP_Http doesn't properly handle directory traversal with "..",
171
+ * and it removes #anchors for no good reason. The BLC implementation deals with both pretty well.
172
+ *
173
+ * @param string $url Relative URL.
174
+ * @param string $base_url Base URL. If omitted, the blog's root URL will be used.
175
+ * @return string
176
+ */
177
+ function relative2absolute($url, $base_url = ''){
178
+ if ( empty($base_url) ){
179
+ $base_url = home_url();
180
+ }
181
+
182
+ $p = @parse_url($url);
183
+ if(!$p) {
184
+ //URL is a malformed
185
+ return false;
186
+ }
187
+ if( isset($p["scheme"]) ) return $url;
188
+
189
+ //If the relative URL is just a query string or anchor, simply attach it to the absolute URL and return
190
+ $first_char = substr($url, 0, 1);
191
+ if ( ($first_char == '?') || ($first_char == '#') ){
192
+ return $base_url . $url;
193
+ }
194
+
195
+ $parts=(parse_url($base_url));
196
+
197
+ //Protocol-relative URLs start with "//". We just need to prepend the right protocol.
198
+ if ( substr($url, 0, 2) === '//' ) {
199
+ $scheme = isset($parts['scheme']) ? $parts['scheme'] : 'http';
200
+ return $scheme . ':'. $url;
201
+ }
202
+
203
+ if(substr($url,0,1)=='/') {
204
+ //Relative URL starts with a slash => ignore the base path and jump straight to the root.
205
+ $path_segments = explode("/", $url);
206
+ array_shift($path_segments);
207
+ } else {
208
+ if(isset($parts['path'])){
209
+ $aparts=explode('/',$parts['path']);
210
+ array_pop($aparts);
211
+ $aparts=array_filter($aparts);
212
+ } else {
213
+ $aparts=array();
214
+ }
215
+
216
+ //Merge together the base path & the relative path
217
+ $aparts = array_merge($aparts, explode("/", $url));
218
+
219
+ //Filter the merged path
220
+ $path_segments = array();
221
+ foreach($aparts as $part){
222
+ if ( $part == '.' ){
223
+ continue; //. = "this directory". It's basically a no-op, so we skip it.
224
+ } elseif ( $part == '..' ) {
225
+ array_pop($path_segments); //.. = one directory up. Remove the last seen path segment.
226
+ } else {
227
+ array_push($path_segments, $part); //Normal directory -> add it to the path.
228
+ }
229
+ }
230
+ }
231
+ $path = implode("/", $path_segments);
232
+
233
+ //Build the absolute URL.
234
+ $url = '';
235
+ if($parts['scheme']) {
236
+ $url = "$parts[scheme]://";
237
+ }
238
+ if(isset($parts['user'])) {
239
+ $url .= $parts['user'];
240
+ if(isset($parts['pass'])) {
241
+ $url .= ":".$parts['pass'];
242
+ }
243
+ $url .= "@";
244
+ }
245
+ if(isset($parts['host'])) {
246
+ $url .= $parts['host'];
247
+ if(isset($parts['port'])) {
248
+ $url .= ':' . $parts['port'];
249
+ }
250
+ $url .= '/';
251
+ }
252
+ $url .= $path;
253
+
254
+ return $url;
255
+ }
256
+
257
+ /**
258
+ * Apply a callback function to all links found in a string and return the results.
259
+ *
260
+ * The first argument passed to the callback function will be an associative array
261
+ * of link data. If the optional $extra parameter is set, it will be passed as the
262
+ * second argument to the callback function.
263
+ *
264
+ * The link data array will contain at least these keys :
265
+ * 'href' - the URL of the link, as-is (i.e. without any sanitization or relative-to-absolute translation).
266
+ * '#raw' - the raw link code, e.g. the entire '<a href="...">...</a>' tag of a HTML link.
267
+ *
268
+ * Sub-classes may also set additional keys.
269
+ *
270
+ * This method is currently used only internally, so sub-classes are not required
271
+ * to implement it.
272
+ *
273
+ * @param string $content A text string to parse for links.
274
+ * @param callback $callback Callback function to apply to all found links.
275
+ * @param mixed $extra If the optional $extra param. is supplied, it will be passed as the second parameter to the function $callback.
276
+ * @return array An array of all detected links after applying $callback to each of them.
277
+ */
278
+ function map($content, $callback, $extra = null){
279
+ return array();
280
+ }
281
+
282
+ /**
283
+ * Modify all links found in a string using a callback function.
284
+ *
285
+ * The first argument passed to the callback function will be an associative array
286
+ * of link data. If the optional $extra parameter is set, it will be passed as the
287
+ * second argument to the callback function. See the map() method of this class for
288
+ * details on the first argument.
289
+ *
290
+ * The callback function should return either an associative array or a string. If
291
+ * a string is returned, the parser will replace the current link with the contents
292
+ * of that string. If an array is returned, the current link will be modified/rebuilt
293
+ * by substituting the new values for the old ones (e.g. returning array with the key
294
+ * 'href' set to 'http://example.com/' will replace the current link's URL with
295
+ * http://example.com/).
296
+ *
297
+ * This method is currently only used internally, so sub-classes are not required
298
+ * to implement it.
299
+ *
300
+ * @see blcParser::map()
301
+ *
302
+ * @param string $content A text string containing the links to edit.
303
+ * @param callback $callback Callback function used to modify the links.
304
+ * @param mixed $extra If supplied, $extra will be passed as the second parameter to the function $callback.
305
+ * @return string The modified input string.
306
+ */
307
+ function multi_edit($content, $callback, $extra = null){
308
+ return $content; //No-op
309
+ }
310
+ }
311
+
312
+ /**
313
+ * A helper class for working with parsers. All its methods should be called statically.
314
+ *
315
+ * @see blcParser
316
+ *
317
+ * @package Broken Link Checker
318
+ * @access public
319
+ */
320
+ class blcParserHelper {
321
+
322
+ /**
323
+ * Get the parser matching a parser type ID.
324
+ *
325
+ * @uses blcModuleManager::get_module()
326
+ *
327
+ * @param string $parser_type
328
+ * @return blcParser|null
329
+ */
330
+ static function get_parser( $parser_type ){
331
+ $manager = blcModuleManager::getInstance();
332
+ return $manager->get_module($parser_type, true, 'parser');
333
+ }
334
+
335
+ /**
336
+ * Get all parsers that support either the specified format or the container type.
337
+ * If a parser supports both, it will still be included only once.
338
+ *
339
+ * @param string $format
340
+ * @param string $container_type
341
+ * @return blcParser[]
342
+ */
343
+ static function get_parsers( $format, $container_type ){
344
+ $found = array();
345
+
346
+ //Retrieve a list of active parsers
347
+ $manager = blcModuleManager::getInstance();
348
+ $active_parsers = $manager->get_modules_by_category('parser');
349
+
350
+ //Try each one
351
+ foreach($active_parsers as $module_id => $module_data){
352
+ $parser = $manager->get_module($module_id); //Will autoload if necessary
353
+ if ( !$parser ){
354
+ continue;
355
+ }
356
+
357
+ if ( in_array($format, $parser->supported_formats) || in_array($container_type, $parser->supported_containers) ){
358
+ array_push($found, $parser);
359
+ }
360
+ }
361
+
362
+ return $found;
363
+ }
364
+ }
365
+
includes/screen-meta-links.php CHANGED
@@ -1,312 +1,312 @@
1
- <?php
2
-
3
- /**
4
- * @author Janis Elsts
5
- * @copyright 2011
6
- */
7
-
8
-
9
- if ( !class_exists('wsScreenMetaLinks11') ):
10
-
11
- //Load JSON functions for PHP < 5.2
12
- if ( !(function_exists('json_encode') && function_exists('json_decode')) && !(class_exists('Services_JSON') || class_exists('Moxiecode_JSON')) ){
13
- $class_json_path = ABSPATH.WPINC.'/class-json.php';
14
- $class_moxiecode_json_path = ABSPATH.WPINC.'/js/tinymce/plugins/spellchecker/classes/utils/JSON.php';
15
- if ( file_exists($class_json_path) ){
16
- require $class_json_path;
17
-
18
- } elseif ( file_exists($class_moxiecode_json_path) ) {
19
- require $class_moxiecode_json_path;
20
- }
21
- }
22
-
23
- class wsScreenMetaLinks11 {
24
- var $registered_links; //List of meta links registered for each page.
25
-
26
- /**
27
- * Class constructor.
28
- *
29
- * @return void
30
- */
31
- function __construct(){
32
- $this->registered_links = array();
33
-
34
- add_action('admin_notices', array(&$this, 'append_meta_links'));
35
- add_action('admin_print_styles', array(&$this, 'add_link_styles'));
36
- }
37
-
38
- /**
39
- * Add a new link to the screen meta area.
40
- *
41
- * Do not call this method directly. Instead, use the global add_screen_meta_link() function.
42
- *
43
- * @param string $id Link ID. Should be unique and a valid value for a HTML ID attribute.
44
- * @param string $text Link text.
45
- * @param string $href Link URL.
46
- * @param string|array $page The page(s) where you want to add the link.
47
- * @param array $attributes Optional. Additional attributes for the link tag.
48
- * @return void
49
- */
50
- function add_screen_meta_link($id, $text, $href, $page, $attributes = null){
51
- if ( !is_array($page) ){
52
- $page = array($page);
53
- }
54
- if ( is_null($attributes) ){
55
- $attributes = array();
56
- }
57
-
58
- //Basically a list of props for a jQuery() call
59
- $link = compact('id', 'text', 'href');
60
- $link = array_merge($link, $attributes);
61
-
62
- //Add the CSS classes that will make the look like a proper meta link
63
- if ( empty($link['class']) ){
64
- $link['class'] = '';
65
- }
66
- $link['class'] = 'show-settings custom-screen-meta-link ' . $link['class'];
67
-
68
- //Save the link in each relevant page's list
69
- foreach($page as $page_id){
70
- if ( !isset($this->registered_links[$page_id]) ){
71
- $this->registered_links[$page_id] = array();
72
- }
73
- $this->registered_links[$page_id][] = $link;
74
- }
75
- }
76
-
77
- /**
78
- * Output the JS that appends the custom meta links to the page.
79
- * Callback for the 'admin_notices' action.
80
- *
81
- * @access private
82
- * @return void
83
- */
84
- function append_meta_links(){
85
- global $hook_suffix;
86
-
87
- //Find links registered for this page
88
- $links = $this->get_links_for_page($hook_suffix);
89
- if ( empty($links) ){
90
- return;
91
- }
92
-
93
- ?>
94
- <script type="text/javascript">
95
- (function($, links){
96
- var container = $('#screen-meta-links');
97
- if ( container.length == 0 ) {
98
- container = $('<div />').attr('id', 'screen-meta-links').insertAfter('#screen-meta');
99
- }
100
- for(var i = 0; i < links.length; i++){
101
- container.append(
102
- $('<div/>')
103
- .attr({
104
- 'id' : links[i].id + '-wrap',
105
- 'class' : 'hide-if-no-js custom-screen-meta-link-wrap'
106
- })
107
- .append( $('<a/>', links[i]) )
108
- );
109
- }
110
- })(jQuery, <?php echo $this->json_encode($links); ?>);
111
- </script>
112
- <?php
113
- }
114
-
115
- /**
116
- * Get a list of custom screen meta links registered for a specific page.
117
- *
118
- * @param string $page
119
- * @return array
120
- */
121
- function get_links_for_page($page){
122
- $links = array();
123
-
124
- if ( isset($this->registered_links[$page]) ){
125
- $links = array_merge($links, $this->registered_links[$page]);
126
- }
127
- $page_as_screen = $this->page_to_screen_id($page);
128
- if ( ($page_as_screen != $page) && isset($this->registered_links[$page_as_screen]) ){
129
- $links = array_merge($links, $this->registered_links[$page_as_screen]);
130
- }
131
-
132
- return $links;
133
- }
134
-
135
- /**
136
- * Output the CSS code for custom screen meta links. Required because WP only
137
- * has styles for specific meta links (by #id), not meta links in general.
138
- *
139
- * Callback for 'admin_print_styles'.
140
- *
141
- * @access private
142
- * @return void
143
- */
144
- function add_link_styles(){
145
- global $hook_suffix;
146
- //Don't output the CSS if there are no custom meta links for this page.
147
- $links = $this->get_links_for_page($hook_suffix);
148
- if ( empty($links) ){
149
- return;
150
- }
151
-
152
- if ( !isset($GLOBALS['wp_version']) || version_compare($GLOBALS['wp_version'], '3.8-RC1', '<') ) {
153
- $this->print_old_link_styles();
154
- } else {
155
- $this->print_link_styles();
156
- }
157
- }
158
-
159
- /**
160
- * Print screen meta button styles (WP 3.8+).
161
- */
162
- private function print_link_styles() {
163
- ?>
164
- <style type="text/css">
165
- .custom-screen-meta-link-wrap {
166
- float: right;
167
- height: 28px;
168
- margin: 0 0 0 6px;
169
-
170
- border: 1px solid #ddd;
171
- border-top: none;
172
- background: #fff;
173
- -webkit-box-shadow: 0 1px 1px -1px rgba(0,0,0,0.1);
174
- box-shadow: 0 1px 1px -1px rgba(0,0,0,0.1);
175
- }
176
-
177
- #screen-meta .custom-screen-meta-link-wrap a.custom-screen-meta-link,
178
- #screen-meta-links .custom-screen-meta-link-wrap a.custom-screen-meta-link
179
- {
180
- padding: 3px 16px 3px 16px;
181
- }
182
-
183
- #screen-meta-links a.custom-screen-meta-link::after {
184
- display: none;
185
- }
186
- </style>
187
- <?php
188
- }
189
-
190
- /**
191
- * Print old screen meta button styles (WP 3.7.x and older).
192
- */
193
- private function print_old_link_styles() {
194
- ?>
195
- <style type="text/css">
196
- .custom-screen-meta-link-wrap {
197
- float: right;
198
- height: 22px;
199
- padding: 0;
200
- margin: 0 0 0 6px;
201
- font-family: sans-serif;
202
- -moz-border-radius-bottomleft: 3px;
203
- -moz-border-radius-bottomright: 3px;
204
- -webkit-border-bottom-left-radius: 3px;
205
- -webkit-border-bottom-right-radius: 3px;
206
- border-bottom-left-radius: 3px;
207
- border-bottom-right-radius: 3px;
208
-
209
- background: #e3e3e3;
210
-
211
- border-right: 1px solid transparent;
212
- border-left: 1px solid transparent;
213
- border-bottom: 1px solid transparent;
214
- background-image: -ms-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* IE10 */
215
- background-image: -moz-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* Firefox */
216
- background-image: -o-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* Opera */
217
- background-image: -webkit-gradient(linear, left bottom, left top, from(#dfdfdf), to(#f1f1f1)); /* old Webkit */
218
- background-image: -webkit-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* new Webkit */
219
- background-image: linear-gradient(bottom, #dfdfdf, #f1f1f1); /* proposed W3C Markup */
220
- }
221
-
222
- #screen-meta .custom-screen-meta-link-wrap a.custom-screen-meta-link,
223
- #screen-meta-links .custom-screen-meta-link-wrap a.custom-screen-meta-link
224
- {
225
- background-image: none;
226
- padding-right: 6px;
227
- color: #777;
228
- }
229
- </style>
230
- <?php
231
- }
232
-
233
- /**
234
- * Convert a page hook name to a screen ID.
235
- *
236
- * @uses convert_to_screen()
237
- * @access private
238
- *
239
- * @param string $page
240
- * @return string
241
- */
242
- function page_to_screen_id($page){
243
- if ( function_exists('convert_to_screen') ){
244
- $screen = convert_to_screen($page);
245
- if ( isset($screen->id) ){
246
- return $screen->id;
247
- } else {
248
- return '';
249
- }
250
- } else {
251
- return str_replace( array('.php', '-new', '-add' ), '', $page);
252
- }
253
- }
254
-
255
- /**
256
- * Back-wards compatible json_encode(). Used to encode link data before
257
- * passing it to the JavaScript that actually creates the links.
258
- *
259
- * @param mixed $data
260
- * @return string
261
- */
262
- function json_encode($data){
263
- if ( function_exists('json_encode') ){
264
- return json_encode($data);
265
- }
266
- if ( class_exists('Services_JSON') ){
267
- $json = new Services_JSON();
268
- return( $json->encodeUnsafe($data) );
269
- } elseif ( class_exists('Moxiecode_JSON') ){
270
- $json = new Moxiecode_JSON();
271
- return $json->encode($data);
272
- } else {
273
- trigger_error('No JSON parser available', E_USER_ERROR);
274
- return null;
275
- }
276
- }
277
-
278
- }
279
-
280
- global $ws_screen_meta_links_versions;
281
- if ( !isset($ws_screen_meta_links_versions) ){
282
- $ws_screen_meta_links_versions = array();
283
- }
284
- $ws_screen_meta_links_versions['1.1'] = 'wsScreenMetaLinks11';
285
-
286
- endif;
287
-
288
- /**
289
- * Add a new link to the screen meta area.
290
- *
291
- * @param string $id Link ID. Should be unique and a valid value for a HTML ID attribute.
292
- * @param string $text Link text.
293
- * @param string $href Link URL.
294
- * @param string|array $page The page(s) where you want to add the link.
295
- * @param array $attributes Optional. Additional attributes for the link tag.
296
- * @return void
297
- */
298
- function add_screen_meta_link($id, $text, $href, $page, $attributes = null){
299
- global $ws_screen_meta_links_versions;
300
-
301
- static $instance = null;
302
- if ( is_null($instance) ){
303
- //Instantiate the latest version of the wsScreenMetaLinks class
304
- uksort($ws_screen_meta_links_versions, 'version_compare');
305
- $className = end($ws_screen_meta_links_versions);
306
- $instance = new $className;
307
- }
308
-
309
- $instance->add_screen_meta_link($id, $text, $href, $page, $attributes);
310
- }
311
-
312
- ?>
1
+ <?php
2
+
3
+ /**
4
+ * @author Janis Elsts
5
+ * @copyright 2011
6
+ */
7
+
8
+
9
+ if ( !class_exists('wsScreenMetaLinks11') ):
10
+
11
+ //Load JSON functions for PHP < 5.2
12
+ if ( !(function_exists('json_encode') && function_exists('json_decode')) && !(class_exists('Services_JSON') || class_exists('Moxiecode_JSON')) ){
13
+ $class_json_path = ABSPATH.WPINC.'/class-json.php';
14
+ $class_moxiecode_json_path = ABSPATH.WPINC.'/js/tinymce/plugins/spellchecker/classes/utils/JSON.php';
15
+ if ( file_exists($class_json_path) ){
16
+ require $class_json_path;
17
+
18
+ } elseif ( file_exists($class_moxiecode_json_path) ) {
19
+ require $class_moxiecode_json_path;
20
+ }
21
+ }
22
+
23
+ class wsScreenMetaLinks11 {
24
+ var $registered_links; //List of meta links registered for each page.
25
+
26
+ /**
27
+ * Class constructor.
28
+ *
29
+ * @return void
30
+ */
31
+ function __construct(){
32
+ $this->registered_links = array();
33
+
34
+ add_action('admin_notices', array(&$this, 'append_meta_links'));
35
+ add_action('admin_print_styles', array(&$this, 'add_link_styles'));
36
+ }
37
+
38
+ /**
39
+ * Add a new link to the screen meta area.
40
+ *
41
+ * Do not call this method directly. Instead, use the global add_screen_meta_link() function.
42
+ *
43
+ * @param string $id Link ID. Should be unique and a valid value for a HTML ID attribute.
44
+ * @param string $text Link text.
45
+ * @param string $href Link URL.
46
+ * @param string|array $page The page(s) where you want to add the link.
47
+ * @param array $attributes Optional. Additional attributes for the link tag.
48
+ * @return void
49
+ */
50
+ function add_screen_meta_link($id, $text, $href, $page, $attributes = null){
51
+ if ( !is_array($page) ){
52
+ $page = array($page);
53
+ }
54
+ if ( is_null($attributes) ){
55
+ $attributes = array();
56
+ }
57
+
58
+ //Basically a list of props for a jQuery() call
59
+ $link = compact('id', 'text', 'href');
60
+ $link = array_merge($link, $attributes);
61
+
62
+ //Add the CSS classes that will make the look like a proper meta link
63
+ if ( empty($link['class']) ){
64
+ $link['class'] = '';
65
+ }
66
+ $link['class'] = 'show-settings custom-screen-meta-link ' . $link['class'];
67
+
68
+ //Save the link in each relevant page's list
69
+ foreach($page as $page_id){
70
+ if ( !isset($this->registered_links[$page_id]) ){
71
+ $this->registered_links[$page_id] = array();
72
+ }
73
+ $this->registered_links[$page_id][] = $link;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Output the JS that appends the custom meta links to the page.
79
+ * Callback for the 'admin_notices' action.
80
+ *
81
+ * @access private
82
+ * @return void
83
+ */
84
+ function append_meta_links(){
85
+ global $hook_suffix;
86
+
87
+ //Find links registered for this page
88
+ $links = $this->get_links_for_page($hook_suffix);
89
+ if ( empty($links) ){
90
+ return;
91
+ }
92
+
93
+ ?>
94
+ <script type="text/javascript">
95
+ (function($, links){
96
+ var container = $('#screen-meta-links');
97
+ if ( container.length == 0 ) {
98
+ container = $('<div />').attr('id', 'screen-meta-links').insertAfter('#screen-meta');
99
+ }
100
+ for(var i = 0; i < links.length; i++){
101
+ container.append(
102
+ $('<div/>')
103
+ .attr({
104
+ 'id' : links[i].id + '-wrap',
105
+ 'class' : 'hide-if-no-js custom-screen-meta-link-wrap'
106
+ })
107
+ .append( $('<a/>', links[i]) )
108
+ );
109
+ }
110
+ })(jQuery, <?php echo $this->json_encode($links); ?>);
111
+ </script>
112
+ <?php
113
+ }
114
+
115
+ /**
116
+ * Get a list of custom screen meta links registered for a specific page.
117
+ *
118
+ * @param string $page
119
+ * @return array
120
+ */
121
+ function get_links_for_page($page){
122
+ $links = array();
123
+
124
+ if ( isset($this->registered_links[$page]) ){
125
+ $links = array_merge($links, $this->registered_links[$page]);
126
+ }
127
+ $page_as_screen = $this->page_to_screen_id($page);
128
+ if ( ($page_as_screen != $page) && isset($this->registered_links[$page_as_screen]) ){
129
+ $links = array_merge($links, $this->registered_links[$page_as_screen]);
130
+ }
131
+
132
+ return $links;
133
+ }
134
+
135
+ /**
136
+ * Output the CSS code for custom screen meta links. Required because WP only
137
+ * has styles for specific meta links (by #id), not meta links in general.
138
+ *
139
+ * Callback for 'admin_print_styles'.
140
+ *
141
+ * @access private
142
+ * @return void
143
+ */
144
+ function add_link_styles(){
145
+ global $hook_suffix;
146
+ //Don't output the CSS if there are no custom meta links for this page.
147
+ $links = $this->get_links_for_page($hook_suffix);
148
+ if ( empty($links) ){
149
+ return;
150
+ }
151
+
152
+ if ( !isset($GLOBALS['wp_version']) || version_compare($GLOBALS['wp_version'], '3.8-RC1', '<') ) {
153
+ $this->print_old_link_styles();
154
+ } else {
155
+ $this->print_link_styles();
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Print screen meta button styles (WP 3.8+).
161
+ */
162
+ private function print_link_styles() {
163
+ ?>
164
+ <style type="text/css">
165
+ .custom-screen-meta-link-wrap {
166
+ float: right;
167
+ height: 28px;
168
+ margin: 0 0 0 6px;
169
+
170
+ border: 1px solid #ddd;
171
+ border-top: none;
172
+ background: #fff;
173
+ -webkit-box-shadow: 0 1px 1px -1px rgba(0,0,0,0.1);
174
+ box-shadow: 0 1px 1px -1px rgba(0,0,0,0.1);
175
+ }
176
+
177
+ #screen-meta .custom-screen-meta-link-wrap a.custom-screen-meta-link,
178
+ #screen-meta-links .custom-screen-meta-link-wrap a.custom-screen-meta-link
179
+ {
180
+ padding: 3px 16px 3px 16px;
181
+ }
182
+
183
+ #screen-meta-links a.custom-screen-meta-link::after {
184
+ display: none;
185
+ }
186
+ </style>
187
+ <?php
188
+ }
189
+
190
+ /**
191
+ * Print old screen meta button styles (WP 3.7.x and older).
192
+ */
193
+ private function print_old_link_styles() {
194
+ ?>
195
+ <style type="text/css">
196
+ .custom-screen-meta-link-wrap {
197
+ float: right;
198
+ height: 22px;
199
+ padding: 0;
200
+ margin: 0 0 0 6px;
201
+ font-family: sans-serif;
202
+ -moz-border-radius-bottomleft: 3px;
203
+ -moz-border-radius-bottomright: 3px;
204
+ -webkit-border-bottom-left-radius: 3px;
205
+ -webkit-border-bottom-right-radius: 3px;
206
+ border-bottom-left-radius: 3px;
207
+ border-bottom-right-radius: 3px;
208
+
209
+ background: #e3e3e3;
210
+
211
+ border-right: 1px solid transparent;
212
+ border-left: 1px solid transparent;
213
+ border-bottom: 1px solid transparent;
214
+ background-image: -ms-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* IE10 */
215
+ background-image: -moz-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* Firefox */
216
+ background-image: -o-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* Opera */
217
+ background-image: -webkit-gradient(linear, left bottom, left top, from(#dfdfdf), to(#f1f1f1)); /* old Webkit */
218
+ background-image: -webkit-linear-gradient(bottom, #dfdfdf, #f1f1f1); /* new Webkit */
219
+ background-image: linear-gradient(bottom, #dfdfdf, #f1f1f1); /* proposed W3C Markup */
220
+ }
221
+
222
+ #screen-meta .custom-screen-meta-link-wrap a.custom-screen-meta-link,
223
+ #screen-meta-links .custom-screen-meta-link-wrap a.custom-screen-meta-link
224
+ {
225
+ background-image: none;
226
+ padding-right: 6px;
227
+ color: #777;
228
+ }
229
+ </style>
230
+ <?php
231
+ }
232
+
233
+ /**
234
+ * Convert a page hook name to a screen ID.
235
+ *
236
+ * @uses convert_to_screen()
237
+ * @access private
238
+ *
239
+ * @param string $page
240
+ * @return string
241
+ */
242
+ function page_to_screen_id($page){
243
+ if ( function_exists('convert_to_screen') ){
244
+ $screen = convert_to_screen($page);
245
+ if ( isset($screen->id) ){
246
+ return $screen->id;
247
+ } else {
248
+ return '';
249
+ }
250
+ } else {
251
+ return str_replace( array('.php', '-new', '-add' ), '', $page);
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Back-wards compatible json_encode(). Used to encode link data before
257
+ * passing it to the JavaScript that actually creates the links.
258
+ *
259
+ * @param mixed $data
260
+ * @return string
261
+ */
262
+ function json_encode($data){
263
+ if ( function_exists('json_encode') ){
264
+ return json_encode($data);
265
+ }
266
+ if ( class_exists('Services_JSON') ){
267
+ $json = new Services_JSON();
268
+ return( $json->encodeUnsafe($data) );
269
+ } elseif ( class_exists('Moxiecode_JSON') ){
270
+ $json = new Moxiecode_JSON();
271
+ return $json->encode($data);
272
+ } else {
273
+ trigger_error('No JSON parser available', E_USER_ERROR);
274
+ return null;
275
+ }
276
+ }
277
+
278
+ }
279
+
280
+ global $ws_screen_meta_links_versions;
281
+ if ( !isset($ws_screen_meta_links_versions) ){
282
+ $ws_screen_meta_links_versions = array();
283
+ }
284
+ $ws_screen_meta_links_versions['1.1'] = 'wsScreenMetaLinks11';
285
+
286
+ endif;
287
+
288
+ /**
289
+ * Add a new link to the screen meta area.
290
+ *
291
+ * @param string $id Link ID. Should be unique and a valid value for a HTML ID attribute.
292
+ * @param string $text Link text.
293
+ * @param string $href Link URL.
294
+ * @param string|array $page The page(s) where you want to add the link.
295
+ * @param array $attributes Optional. Additional attributes for the link tag.
296
+ * @return void
297
+ */
298
+ function add_screen_meta_link($id, $text, $href, $page, $attributes = null){
299
+ global $ws_screen_meta_links_versions;
300
+
301
+ static $instance = null;
302
+ if ( is_null($instance) ){
303
+ //Instantiate the latest version of the wsScreenMetaLinks class
304
+ uksort($ws_screen_meta_links_versions, 'version_compare');
305
+ $className = end($ws_screen_meta_links_versions);
306
+ $instance = new $className;
307
+ }
308
+
309
+ $instance->add_screen_meta_link($id, $text, $href, $page, $attributes);
310
+ }
311
+
312
+ ?>
includes/screen-options/screen-options.js CHANGED
@@ -1,13 +1,13 @@
1
- jQuery(function($){
2
- function performAutosave(){
3
- var panel = $(this).parents('div.custom-options-panel');
4
- var params = panel.find('input, select, textarea').serialize();
5
- params = params + '&action=save_settings-' + panel.attr('id');
6
- $.post(
7
- 'admin-ajax.php',
8
- params
9
- );
10
- }
11
-
12
- $('#screen-options-wrap div.requires-autosave').find('input, select, textarea').change(performAutosave);
13
  });
1
+ jQuery(function($){
2
+ function performAutosave(){
3
+ var panel = $(this).parents('div.custom-options-panel');
4
+ var params = panel.find('input, select, textarea').serialize();
5
+ params = params + '&action=save_settings-' + panel.attr('id');
6
+ $.post(
7
+ 'admin-ajax.php',
8
+ params
9
+ );
10
+ }
11
+
12
+ $('#screen-options-wrap div.requires-autosave').find('input, select, textarea').change(performAutosave);
13
  });
includes/screen-options/screen-options.php CHANGED
@@ -1,297 +1,297 @@
1
- <?php
2
-
3
- if ( !class_exists('wsScreenOptions12') ):
4
-
5
- /**
6
- * Class for adding new panels to the "Screen Options" box.
7
- *
8
- * Do not access this class directly. Instead, use the add_screen_options_panel() function.
9
- *
10
- * @author Janis Elsts
11
- * @copyright 2014
12
- * @version 1.3
13
- * @access public
14
- */
15
- class wsScreenOptions13 {
16
- var $registered_panels; //List of custom "Screen Options" panels
17
- var $page_panels; //Index of panels registered for each page ($page => array of panel ids).
18
-
19
- /**
20
- * Class constructor
21
- *
22
- * @return void
23
- */
24
- function init(){
25
- $this->registered_panels = array();
26
- $this->page_panels = array();
27
-
28
- add_action('current_screen', array($this, 'populate_page_panels'));
29
- add_filter('screen_settings', array(&$this, 'append_screen_settings'), 10, 2);
30
- add_action('admin_print_scripts', array(&$this, 'add_autosave_script'));
31
- }
32
-
33
- /**
34
- * Add a new settings panel to the "Screen Options" box.
35
- *
36
- * @param string $id String to use in the 'id' attribute of the settings panel. Should be unique.
37
- * @param string $title Title of the settings panel. Set to an empty string to omit title.
38
- * @param callback $callback Function that fills the panel with the desired content. Should return its output.
39
- * @param string|array $page The page(s) on which to show the panel (similar to add_meta_box()).
40
- * @param callback $save_callback Optional. Function that saves the settings.
41
- * @param bool $autosave Optional. If set, settings will be automatically saved (via AJAX) when the value of any input element in the panel changes. Defaults to false.
42
- * @return void
43
- */
44
- function add_screen_options_panel($id, $title, $callback, $page, $save_callback = null, $autosave = false){
45
- if ( !is_array($page) ){
46
- $page = array($page);
47
- }
48
-
49
- $new_panel = array(
50
- 'title' => $title,
51
- 'callback' => $callback,
52
- 'page' => $page,
53
- 'save_callback' => $save_callback,
54
- 'autosave' => $autosave,
55
- );
56
- $this->registered_panels[$id] = $new_panel;
57
-
58
- if ( $save_callback ){
59
- add_action('wp_ajax_save_settings-' . $id, array($this, 'ajax_save_callback'));
60
- }
61
- }
62
-
63
- /**
64
- * Populate a lookup array for screen -> panels queries.
65
- *
66
- * This is a callback for the "current_screen" action. We have to do it in this hook or WordPress will
67
- * complain about "doing it wrong" and incorrectly suggest using the "add_meta_boxes" action.
68
- *
69
- * "add_meta_boxes" doesn't work here because it only gets called on CPT pages and we want the ability
70
- * to add screen options to any page.
71
- */
72
- function populate_page_panels() {
73
- foreach($this->registered_panels as $id => $panel) {
74
- $page = $panel['page'];
75
-
76
- //Convert page hooks/slugs to screen IDs
77
- $page = array_map(array($this, 'page_to_screen_id'), $page);
78
- $page = array_unique($page);
79
-
80
- //Store the panel ID in each relevant page's list
81
- foreach($page as $page_id){
82
- if ( !isset($this->page_panels[$page_id]) ){
83
- $this->page_panels[$page_id] = array();
84
- }
85
- $this->page_panels[$page_id][] = $id;
86
- }
87
- }
88
- }
89
-
90
- /**
91
- * Convert a page hook name to a screen ID.
92
- *
93
- * @uses convert_to_screen()
94
- * @access private
95
- *
96
- * @param string $page
97
- * @return string
98
- */
99
- function page_to_screen_id($page){
100
- if ( function_exists('convert_to_screen') ){
101
- $screen = convert_to_screen($page);
102
- if ( isset($screen->id) ){
103
- return $screen->id;
104
- } else {
105
- return '';
106
- }
107
- } else {
108
- return str_replace( array('.php', '-new', '-add' ), '', $page);
109
- }
110
- }
111
-
112
- /**
113
- * Append custom panel HTML to the "Screen Options" box of the current page.
114
- * Callback for the 'screen_settings' filter (available in WP 3.0 and up).
115
- *
116
- * @access private
117
- *
118
- * @param string $current
119
- * @param string $screen Screen object (undocumented).
120
- * @return string The HTML code to append to "Screen Options"
121
- */
122
- function append_screen_settings($current, $screen){
123
- global $hook_suffix;
124
-
125
- //Sanity check
126
- if ( !isset($screen->id) ) {
127
- return $current;
128
- }
129
-
130
- //Are there any panels that want to appear on this page?
131
- $panels = $this->get_panels_for_screen($screen->id, $hook_suffix);
132
- if ( empty($panels) ){
133
- return $current;
134
- }
135
-
136
- //Append all panels registered for this screen
137
- foreach($panels as $panel_id){
138
- $panel = $this->registered_panels[$panel_id];
139
-
140
- //Add panel title
141
- if ( !empty($panel['title']) ){
142
- $current .= "\n<h5>".$panel['title']."</h5>\n";
143
- }
144
- //Generate panel contents
145
- if ( is_callable($panel['callback']) ){
146
- $contents = call_user_func($panel['callback']);
147
- $classes = array(
148
- 'custom-options-panel',
149
- );
150
- if ( $panel['autosave'] ){
151
- $classes[] = 'requires-autosave';
152
- }
153
-
154
- $contents = sprintf(
155
- '<div id="%s" class="%s"><input type="hidden" name="_wpnonce-%s" value="%s" />%s</div>',
156
- esc_attr($panel_id),
157
- implode(' ',$classes),
158
- esc_attr($panel_id),
159
- wp_create_nonce('save_settings-'.$panel_id),
160
- $contents
161
- );
162
-
163
- $current .= $contents;
164
- }
165
- }
166
-
167
- return $current;
168
- }
169
-
170
- /**
171
- * AJAX callback for the "Screen Options" autosave.
172
- *
173
- * @access private
174
- * @return void
175
- */
176
- function ajax_save_callback(){
177
- if ( empty($_POST['action']) ){
178
- die('0');
179
- }
180
-
181
- //The 'action' argument is in the form "save_settings-panel_id"
182
- $id = end(explode('-', $_POST['action'], 2));
183
-
184
- //Basic security check.
185
- check_ajax_referer('save_settings-' . $id, '_wpnonce-' . $id);
186
-
187
- //Hand the request to the registered callback, if any
188
- if ( !isset($this->registered_panels[$id]) ){
189
- exit('0');
190
- }
191
- $panel = $this->registered_panels[$id];
192
- if ( is_callable($panel['save_callback']) ){
193
- call_user_func($panel['save_callback'], $_POST);
194
- die('1');
195
- } else {
196
- die('0');
197
- }
198
- }
199
-
200
- /**
201
- * Add/enqueue supporting JavaScript for the autosave function of custom "Screen Options" panels.
202
- *
203
- * Checks if the current page is supposed to contain any autosave-enabled
204
- * panels and adds the script only if that's the case.
205
- *
206
- * @return void
207
- */
208
- function add_autosave_script(){
209
- //Get the page id/hook/slug/whatever.
210
- global $hook_suffix;
211
-
212
- //Check if we have some panels with autosave registered for this page.
213
- $panels = $this->get_panels_for_screen('', $hook_suffix);
214
- if ( empty($panels) ){
215
- return;
216
- }
217
-
218
- $got_autosave = false;
219
- foreach($panels as $panel_id){
220
- if ( $this->registered_panels[$panel_id]['autosave'] ){
221
- $got_autosave = true;
222
- break;
223
- }
224
- }
225
-
226
- if ( $got_autosave ){
227
- //Enqueue the script itself
228
- $url = plugins_url('screen-options.js', __FILE__);
229
- wp_enqueue_script('screen-options-custom-autosave', $url, array('jquery'));
230
- }
231
- }
232
-
233
- /**
234
- * Get custom panels registered for a particular screen and/or page.
235
- *
236
- * @param string $screen_id Screen ID.
237
- * @param string $page Optional. Page filename or hook name.
238
- * @return array Array of custom panels.
239
- */
240
- function get_panels_for_screen($screen_id, $page = ''){
241
- if ( isset($this->page_panels[$screen_id]) && !empty($this->page_panels[$screen_id]) ){
242
- $panels = $this->page_panels[$screen_id];
243
- } else {
244
- $panels = array();
245
- }
246
- if ( !empty($page) ){
247
- $page_as_screen = $this->page_to_screen_id($page);
248
- if ( isset($this->page_panels[$page_as_screen]) && !empty($this->page_panels[$page_as_screen]) ){
249
- $panels = array_merge($panels, $this->page_panels[$page_as_screen]);
250
- }
251
- }
252
- return array_unique($panels);
253
- }
254
- }
255
-
256
- //All versions of the class are stored in a global array
257
- //and only the latest version is actually used.
258
- global $ws_screen_options_versions;
259
- if ( !isset($ws_screen_options_versions) ){
260
- $ws_screen_options_versions = array();
261
- }
262
- $ws_screen_options_versions['1.3'] = 'wsScreenOptions13';
263
-
264
- endif;
265
-
266
- if ( !function_exists('add_screen_options_panel') ){
267
-
268
- /**
269
- * Add a new settings panel to the "Screen Options" box.
270
- *
271
- * @see wsScreenOptions10::add_screen_options_panel()
272
- *
273
- * @param string $id String to use in the 'id' attribute of the settings panel. Should be unique.
274
- * @param string $title Title of the settings panel. Set to an empty string to omit title.
275
- * @param callback $callback Function that fills the panel with the desired content. Should return its output.
276
- * @param string|array $page The page(s) on which to show the panel (similar to add_meta_box()).
277
- * @param callback $save_callback Optional. Function that saves the settings contained in the panel.
278
- * @param bool $autosave Optional. If set, settings will be automatically saved (via AJAX) when the value of any input element in the panel changes. Defaults to false.
279
- * @return void
280
- */
281
- function add_screen_options_panel($id, $title, $callback, $page, $save_callback = null, $autosave = false){
282
- global $ws_screen_options_versions;
283
-
284
- static $instance = null; /** @var wsScreenOptions13 $instance */
285
- if ( is_null($instance) ){
286
- //Instantiate the latest version of the wsScreenOptions class
287
- uksort($ws_screen_options_versions, 'version_compare');
288
- $className = end($ws_screen_options_versions);
289
- $instance = new $className;
290
- $instance->init();
291
- }
292
-
293
- $instance->add_screen_options_panel($id, $title, $callback, $page, $save_callback, $autosave);
294
- }
295
-
296
- }
297
-
1
+ <?php
2
+
3
+ if ( !class_exists('wsScreenOptions12') ):
4
+
5
+ /**
6
+ * Class for adding new panels to the "Screen Options" box.
7
+ *
8
+ * Do not access this class directly. Instead, use the add_screen_options_panel() function.
9
+ *
10
+ * @author Janis Elsts
11
+ * @copyright 2014
12
+ * @version 1.3
13
+ * @access public
14
+ */
15
+ class wsScreenOptions13 {
16
+ var $registered_panels; //List of custom "Screen Options" panels
17
+ var $page_panels; //Index of panels registered for each page ($page => array of panel ids).
18
+
19
+ /**
20
+ * Class constructor
21
+ *
22
+ * @return void
23
+ */
24
+ function init(){
25
+ $this->registered_panels = array();
26
+ $this->page_panels = array();
27
+
28
+ add_action('current_screen', array($this, 'populate_page_panels'));
29
+ add_filter('screen_settings', array(&$this, 'append_screen_settings'), 10, 2);
30
+ add_action('admin_print_scripts', array(&$this, 'add_autosave_script'));
31
+ }
32
+
33
+ /**
34
+ * Add a new settings panel to the "Screen Options" box.
35
+ *
36
+ * @param string $id String to use in the 'id' attribute of the settings panel. Should be unique.
37
+ * @param string $title Title of the settings panel. Set to an empty string to omit title.
38
+ * @param callback $callback Function that fills the panel with the desired content. Should return its output.
39
+ * @param string|array $page The page(s) on which to show the panel (similar to add_meta_box()).
40
+ * @param callback $save_callback Optional. Function that saves the settings.
41
+ * @param bool $autosave Optional. If set, settings will be automatically saved (via AJAX) when the value of any input element in the panel changes. Defaults to false.
42
+ * @return void
43
+ */
44
+ function add_screen_options_panel($id, $title, $callback, $page, $save_callback = null, $autosave = false){
45
+ if ( !is_array($page) ){
46
+ $page = array($page);
47
+ }
48
+
49
+ $new_panel = array(
50
+ 'title' => $title,
51
+ 'callback' => $callback,
52
+ 'page' => $page,
53
+ 'save_callback' => $save_callback,
54
+ 'autosave' => $autosave,
55
+ );
56
+ $this->registered_panels[$id] = $new_panel;
57
+
58
+ if ( $save_callback ){
59
+ add_action('wp_ajax_save_settings-' . $id, array($this, 'ajax_save_callback'));
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Populate a lookup array for screen -> panels queries.
65
+ *
66
+ * This is a callback for the "current_screen" action. We have to do it in this hook or WordPress will
67
+ * complain about "doing it wrong" and incorrectly suggest using the "add_meta_boxes" action.
68
+ *
69
+ * "add_meta_boxes" doesn't work here because it only gets called on CPT pages and we want the ability
70
+ * to add screen options to any page.
71
+ */
72
+ function populate_page_panels() {
73
+ foreach($this->registered_panels as $id => $panel) {
74
+ $page = $panel['page'];
75
+
76
+ //Convert page hooks/slugs to screen IDs
77
+ $page = array_map(array($this, 'page_to_screen_id'), $page);
78
+ $page = array_unique($page);
79
+
80
+ //Store the panel ID in each relevant page's list
81
+ foreach($page as $page_id){
82
+ if ( !isset($this->page_panels[$page_id]) ){
83
+ $this->page_panels[$page_id] = array();
84
+ }
85
+ $this->page_panels[$page_id][] = $id;
86
+ }
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Convert a page hook name to a screen ID.
92
+ *
93
+ * @uses convert_to_screen()
94
+ * @access private
95
+ *
96
+ * @param string $page
97
+ * @return string
98
+ */
99
+ function page_to_screen_id($page){
100
+ if ( function_exists('convert_to_screen') ){
101
+ $screen = convert_to_screen($page);
102
+ if ( isset($screen->id) ){
103
+ return $screen->id;
104
+ } else {
105
+ return '';
106
+ }
107
+ } else {
108
+ return str_replace( array('.php', '-new', '-add' ), '', $page);
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Append custom panel HTML to the "Screen Options" box of the current page.
114
+ * Callback for the 'screen_settings' filter (available in WP 3.0 and up).
115
+ *
116
+ * @access private
117
+ *
118
+ * @param string $current
119
+ * @param string $screen Screen object (undocumented).
120
+ * @return string The HTML code to append to "Screen Options"
121
+ */
122
+ function append_screen_settings($current, $screen){
123
+ global $hook_suffix;
124
+
125
+ //Sanity check
126
+ if ( !isset($screen->id) ) {
127
+ return $current;
128
+ }
129
+
130
+ //Are there any panels that want to appear on this page?
131
+ $panels = $this->get_panels_for_screen($screen->id, $hook_suffix);
132
+ if ( empty($panels) ){
133
+ return $current;
134
+ }
135
+
136
+ //Append all panels registered for this screen
137
+ foreach($panels as $panel_id){
138
+ $panel = $this->registered_panels[$panel_id];
139
+
140
+ //Add panel title
141
+ if ( !empty($panel['title']) ){
142
+ $current .= "\n<h5>".$panel['title']."</h5>\n";
143
+ }
144
+ //Generate panel contents
145
+ if ( is_callable($panel['callback']) ){
146
+ $contents = call_user_func($panel['callback']);
147
+ $classes = array(
148
+ 'custom-options-panel',
149
+ );
150
+ if ( $panel['autosave'] ){
151
+ $classes[] = 'requires-autosave';
152
+ }
153
+
154
+ $contents = sprintf(
155
+ '<div id="%s" class="%s"><input type="hidden" name="_wpnonce-%s" value="%s" />%s</div>',
156
+ esc_attr($panel_id),
157
+ implode(' ',$classes),
158
+ esc_attr($panel_id),
159
+ wp_create_nonce('save_settings-'.$panel_id),
160
+ $contents
161
+ );
162
+
163
+ $current .= $contents;
164
+ }
165
+ }
166
+
167
+ return $current;
168
+ }
169
+
170
+ /**
171
+ * AJAX callback for the "Screen Options" autosave.
172
+ *
173
+ * @access private
174
+ * @return void
175
+ */
176
+ function ajax_save_callback(){
177
+ if ( empty($_POST['action']) ){
178
+ die('0');
179
+ }
180
+
181
+ //The 'action' argument is in the form "save_settings-panel_id"
182
+ $id = end(explode('-', $_POST['action'], 2));
183
+
184
+ //Basic security check.
185
+ check_ajax_referer('save_settings-' . $id, '_wpnonce-' . $id);
186
+
187
+ //Hand the request to the registered callback, if any
188
+ if ( !isset($this->registered_panels[$id]) ){
189
+ exit('0');
190
+ }
191
+ $panel = $this->registered_panels[$id];
192
+ if ( is_callable($panel['save_callback']) ){
193
+ call_user_func($panel['save_callback'], $_POST);
194
+ die('1');
195
+ } else {
196
+ die('0');
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Add/enqueue supporting JavaScript for the autosave function of custom "Screen Options" panels.
202
+ *
203
+ * Checks if the current page is supposed to contain any autosave-enabled
204
+ * panels and adds the script only if that's the case.
205
+ *
206
+ * @return void
207
+ */
208
+ function add_autosave_script(){
209
+ //Get the page id/hook/slug/whatever.
210
+ global $hook_suffix;
211
+
212
+ //Check if we have some panels with autosave registered for this page.
213
+ $panels = $this->get_panels_for_screen('', $hook_suffix);
214
+ if ( empty($panels) ){
215
+ return;
216
+ }
217
+
218
+ $got_autosave = false;
219
+ foreach($panels as $panel_id){
220
+ if ( $this->registered_panels[$panel_id]['autosave'] ){
221
+ $got_autosave = true;
222
+ break;
223
+ }
224
+ }
225
+
226
+ if ( $got_autosave ){
227
+ //Enqueue the script itself
228
+ $url = plugins_url('screen-options.js', __FILE__);
229
+ wp_enqueue_script('screen-options-custom-autosave', $url, array('jquery'));
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Get custom panels registered for a particular screen and/or page.
235
+ *
236
+ * @param string $screen_id Screen ID.
237
+ * @param string $page Optional. Page filename or hook name.
238
+ * @return array Array of custom panels.
239
+ */
240
+ function get_panels_for_screen($screen_id, $page = ''){
241
+ if ( isset($this->page_panels[$screen_id]) && !empty($this->page_panels[$screen_id]) ){
242
+ $panels = $this->page_panels[$screen_id];
243
+ } else {
244
+ $panels = array();
245
+ }
246
+ if ( !empty($page) ){
247
+ $page_as_screen = $this->page_to_screen_id($page);
248
+ if ( isset($this->page_panels[$page_as_screen]) && !empty($this->page_panels[$page_as_screen]) ){
249
+ $panels = array_merge($panels, $this->page_panels[$page_as_screen]);
250
+ }
251
+ }
252
+ return array_unique($panels);
253
+ }
254
+ }
255
+
256
+ //All versions of the class are stored in a global array
257
+ //and only the latest version is actually used.
258
+ global $ws_screen_options_versions;
259
+ if ( !isset($ws_screen_options_versions) ){
260
+ $ws_screen_options_versions = array();
261
+ }
262
+ $ws_screen_options_versions['1.3'] = 'wsScreenOptions13';
263
+
264
+ endif;
265
+
266
+ if ( !function_exists('add_screen_options_panel') ){
267
+
268
+ /**
269
+ * Add a new settings panel to the "Screen Options" box.
270
+ *
271
+ * @see wsScreenOptions10::add_screen_options_panel()
272
+ *
273
+ * @param string $id String to use in the 'id' attribute of the settings panel. Should be unique.
274
+ * @param string $title Title of the settings panel. Set to an empty string to omit title.
275
+ * @param callback $callback Function that fills the panel with the desired content. Should return its output.
276
+ * @param string|array $page The page(s) on which to show the panel (similar to add_meta_box()).
277
+ * @param callback $save_callback Optional. Function that saves the settings contained in the panel.
278
+ * @param bool $autosave Optional. If set, settings will be automatically saved (via AJAX) when the value of any input element in the panel changes. Defaults to false.
279
+ * @return void
280
+ */
281
+ function add_screen_options_panel($id, $title, $callback, $page, $save_callback = null, $autosave = false){
282
+ global $ws_screen_options_versions;
283
+
284
+ static $instance = null; /** @var wsScreenOptions13 $instance */
285
+ if ( is_null($instance) ){
286
+ //Instantiate the latest version of the wsScreenOptions class
287
+ uksort($ws_screen_options_versions, 'version_compare');
288
+ $className = end($ws_screen_options_versions);
289
+ $instance = new $className;
290
+ $instance->init();
291
+ }
292
+
293
+ $instance->add_screen_options_panel($id, $title, $callback, $page, $save_callback, $autosave);
294
+ }
295
+
296
+ }
297
+
includes/token-bucket.php CHANGED
@@ -1,121 +1,121 @@
1
- <?php
2
-
3
- /**
4
- * This class implements a variant of the popular token bucket algorithm.
5
- */
6
- class blcTokenBucketList {
7
- const MICROSECONDS_PER_SECOND = 1000000;
8
-
9
- /** @var float How many tokens each bucket can hold. */
10
- private $capacity;
11
-
12
- /** @var float How long it takes to completely fill a bucket (in seconds). */
13
- private $fillTime;
14
-
15
- /** @var float Minimum interval between taking tokens from a bucket (in seconds). */
16
- private $minTakeInterval;
17
-
18
- /** @var int How many buckets we can manage, in total. */
19
- private $maxBuckets = 200;
20
-
21
- private $buckets = array();
22
-
23
- public function __construct($capacity, $fillTime, $minInterval = 0) {
24
- $this->capacity = $capacity;
25
- $this->fillTime = $fillTime;
26
- $this->minTakeInterval = $minInterval;
27
- }
28
-
29
- /**
30
- * Take one token from a bucket.
31
- * This method will block until a token becomes available.
32
- *
33
- * @param string $bucketName
34
- */
35
- public function takeToken($bucketName) {
36
- $this->createIfNotExists($bucketName);
37
- $this->waitForToken($bucketName);
38
-
39
- $this->buckets[$bucketName]['tokens']--;
40
- $this->buckets[$bucketName]['lastTokenTakenAt'] = microtime(true);
41
- }
42
-
43
- /**
44
- * Wait until at a token is available.
45
- *
46
- * @param string $name Bucket name.
47
- */
48
- private function waitForToken($name) {
49
- $now = microtime(true);
50
-
51
- $timeSinceLastToken = $now - $this->buckets[$name]['lastTokenTakenAt'];
52
- $intervalWait = max($this->minTakeInterval - $timeSinceLastToken, 0);
53
-
54
- $requiredTokens = max(1 - $this->buckets[$name]['tokens'], 0);
55
- $refillWait = $requiredTokens / $this->getFillRate();
56
-
57
- $totalWait = max($intervalWait, $refillWait);
58
- if ($totalWait > 0) {
59
- usleep($totalWait * self::MICROSECONDS_PER_SECOND);
60
- }
61
-
62
- $this->refillBucket($name);
63
- return;
64
- }
65
-
66
- /**
67
- * Create a bucket if it doesn't exist yet.
68
- *
69
- * @param $name
70
- */
71
- private function createIfNotExists($name) {
72
- if ( !isset($this->buckets[$name]) ) {
73
- $this->buckets[$name] = array(
74
- 'tokens' => $this->capacity,
75
- 'lastRefill' => microtime(true),
76
- 'lastTokenTakenAt' => 0
77
- );
78
- }
79
- //Make sure we don't exceed $maxBuckets.
80
- $this->cleanup();
81
- }
82
-
83
- /**
84
- * Calculate how quickly each bucket should be refilled.
85
- *
86
- * @return float Fill rate in tokens per second.
87
- */
88
- private function getFillRate() {
89
- return $this->capacity / $this->fillTime;
90
- }
91
-
92
- /**
93
- * Refill a bucket with fresh tokens.
94
- *
95
- * @param $name
96
- */
97
- private function refillBucket($name) {
98
- $now = microtime(true);
99
-
100
- $timeSinceRefill = $now - $this->buckets[$name]['lastRefill'];
101
- $this->buckets[$name]['tokens'] += $timeSinceRefill * $this->getFillRate();
102
-
103
- if ($this->buckets[$name]['tokens'] > $this->capacity) {
104
- $this->buckets[$name]['tokens'] = $this->capacity;
105
- }
106
-
107
- $this->buckets[$name]['lastRefill'] = $now;
108
- }
109
-
110
- /**
111
- * Keep the number of active buckets within the $this->maxBuckets limit.
112
- */
113
- private function cleanup() {
114
- if ($this->maxBuckets > 0) {
115
- //Very simplistic implementation - just discard the oldest buckets.
116
- while(count($this->buckets) > $this->maxBuckets) {
117
- array_shift($this->buckets);
118
- }
119
- }
120
- }
121
  }
1
+ <?php
2
+
3
+ /**
4
+ * This class implements a variant of the popular token bucket algorithm.
5
+ */
6
+ class blcTokenBucketList {
7
+ const MICROSECONDS_PER_SECOND = 1000000;
8
+
9
+ /** @var float How many tokens each bucket can hold. */
10
+ private $capacity;
11
+
12
+ /** @var float How long it takes to completely fill a bucket (in seconds). */
13
+ private $fillTime;
14
+
15
+ /** @var float Minimum interval between taking tokens from a bucket (in seconds). */
16
+ private $minTakeInterval;
17
+
18
+ /** @var int How many buckets we can manage, in total. */
19
+ private $maxBuckets = 200;
20
+
21
+ private $buckets = array();
22
+
23
+ public function __construct($capacity, $fillTime, $minInterval = 0) {
24
+ $this->capacity = $capacity;
25
+ $this->fillTime = $fillTime;
26
+ $this->minTakeInterval = $minInterval;
27
+ }
28
+
29
+ /**
30
+ * Take one token from a bucket.
31
+ * This method will block until a token becomes available.
32
+ *
33
+ * @param string $bucketName
34
+ */
35
+ public function takeToken($bucketName) {
36
+ $this->createIfNotExists($bucketName);
37
+ $this->waitForToken($bucketName);
38
+
39
+ $this->buckets[$bucketName]['tokens']--;
40
+ $this->buckets[$bucketName]['lastTokenTakenAt'] = microtime(true);
41
+ }
42
+
43
+ /**
44
+ * Wait until at a token is available.
45
+ *
46
+ * @param string $name Bucket name.
47
+ */
48
+ private function waitForToken($name) {
49
+ $now = microtime(true);
50
+
51
+ $timeSinceLastToken = $now - $this->buckets[$name]['lastTokenTakenAt'];
52
+ $intervalWait = max($this->minTakeInterval - $timeSinceLastToken, 0);
53
+
54
+ $requiredTokens = max(1 - $this->buckets[$name]['tokens'], 0);
55
+ $refillWait = $requiredTokens / $this->getFillRate();
56
+
57
+ $totalWait = max($intervalWait, $refillWait);
58
+ if ($totalWait > 0) {
59
+ usleep($totalWait * self::MICROSECONDS_PER_SECOND);
60
+ }
61
+
62
+ $this->refillBucket($name);
63
+ return;
64
+ }
65
+
66
+ /**
67
+ * Create a bucket if it doesn't exist yet.
68
+ *
69
+ * @param $name
70
+ */
71
+ private function createIfNotExists($name) {
72
+ if ( !isset($this->buckets[$name]) ) {
73
+ $this->buckets[$name] = array(
74
+ 'tokens' => $this->capacity,
75
+ 'lastRefill' => microtime(true),
76
+ 'lastTokenTakenAt' => 0
77
+ );
78
+ }
79
+ //Make sure we don't exceed $maxBuckets.
80
+ $this->cleanup();
81
+ }
82
+
83
+ /**
84
+ * Calculate how quickly each bucket should be refilled.
85
+ *
86
+ * @return float Fill rate in tokens per second.
87
+ */
88
+ private function getFillRate() {
89
+ return $this->capacity / $this->fillTime;
90
+ }
91
+
92
+ /**
93
+ * Refill a bucket with fresh tokens.
94
+ *
95
+ * @param $name
96
+ */
97
+ private function refillBucket($name) {
98
+ $now = microtime(true);
99
+
100
+ $timeSinceRefill = $now - $this->buckets[$name]['lastRefill'];
101
+ $this->buckets[$name]['tokens'] += $timeSinceRefill * $this->getFillRate();
102
+
103
+ if ($this->buckets[$name]['tokens'] > $this->capacity) {
104
+ $this->buckets[$name]['tokens'] = $this->capacity;
105
+ }
106
+
107
+ $this->buckets[$name]['lastRefill'] = $now;
108
+ }
109
+
110
+ /**
111
+ * Keep the number of active buckets within the $this->maxBuckets limit.
112
+ */
113
+ private function cleanup() {
114
+ if ($this->maxBuckets > 0) {
115
+ //Very simplistic implementation - just discard the oldest buckets.
116
+ while(count($this->buckets) > $this->maxBuckets) {
117
+ array_shift($this->buckets);
118
+ }
119
+ }
120
+ }
121
  }
includes/transactions-manager.php CHANGED
File without changes
includes/utility-class.php CHANGED
@@ -1,417 +1,417 @@
1
- <?php
2
-
3
- /**
4
- * @author W-Shadow
5
- * @copyright 2010
6
- */
7
-
8
- if ( ! function_exists( 'sys_get_temp_dir' ) ) {
9
- function sys_get_temp_dir() {
10
- if ( ! empty( $_ENV['TMP'] ) ) { return realpath( $_ENV['TMP'] ); }
11
- if ( ! empty( $_ENV['TMPDIR'] ) ) { return realpath( $_ENV['TMPDIR'] ); }
12
- if ( ! empty( $_ENV['TEMP'] ) ) { return realpath( $_ENV['TEMP'] ); }
13
- $tempfile = tempnam( uniqid( rand(),TRUE ),'' );
14
- if ( @file_exists( $tempfile ) ) {
15
- unlink( $tempfile );
16
- return realpath( dirname( $tempfile ) );
17
- }
18
- return '';
19
- }
20
- }
21
-
22
- //Include the internationalized domain name converter (requires PHP 5)
23
- if ( version_compare( phpversion(), '5.0.0', '>=' ) && ! class_exists( 'idna_convert' ) ) {
24
- include BLC_DIRECTORY . '/idn/idna_convert.class.php';
25
- if ( ! function_exists( 'encode_utf8' ) ) {
26
- include BLC_DIRECTORY . '/idn/transcode_wrapper.php';
27
- }
28
- }
29
-
30
-
31
- if ( ! class_exists( 'blcUtility' ) ) {
32
- class blcUtility {
33
- /**
34
- * Checks if PHP is running in safe mode
35
- * blcUtility::is_safe_mode()
36
- *
37
- * @return bool
38
- */
39
- static function is_safe_mode() {
40
- // Check php.ini safe_mode only if PHP version is lower than 5.3.0, else set to false.
41
- if ( version_compare( phpversion(), '5.3.0', '<' ) ) {
42
- $safe_mode = ini_get( 'safe_mode' );
43
- } else {
44
- $safe_mode = false;
45
- }
46
-
47
- // Null, 0, '', '0' and so on count as false.
48
- if ( ! $safe_mode ) {
49
- return false;
50
- }
51
- // Test for some textual true/false variations.
52
- switch ( strtolower( $safe_mode ) ) {
53
- case 'on':
54
- case 'true':
55
- case 'yes':
56
- return true;
57
-
58
- case 'off':
59
- case 'false':
60
- case 'no':
61
- return false;
62
-
63
- default: // Let PHP handle anything else.
64
- return (bool) (int) $safe_mode;
65
- }
66
- }
67
-
68
- /**
69
- * blcUtility::is_open_basedir()
70
- * Checks if open_basedir is enabled
71
- *
72
- * @return bool
73
- */
74
- static function is_open_basedir(){
75
- $open_basedir = ini_get( 'open_basedir' );
76
- return $open_basedir && ( strtolower( $open_basedir ) != 'none' );
77
- }
78
-
79
- /**
80
- * Truncate a string on a specified boundary character.
81
- *
82
- * @param string $text The text to truncate.
83
- * @param integer $max_characters Return no more than $max_characters
84
- * @param string $break Break on this character. Defaults to space.
85
- * @param string $pad Pad the truncated string with this string. Defaults to an HTML ellipsis.
86
- * @return string
87
- */
88
- static function truncate( $text, $max_characters = 0, $break = ' ', $pad = '&hellip;' ) {
89
- if ( strlen( $text ) <= $max_characters ) {
90
- return $text;
91
- }
92
-
93
- $text = substr( $text, 0, $max_characters );
94
- $break_pos = strrpos( $text, $break );
95
- if ( false !== $break_pos ) {
96
- $text = substr( $text, 0, $break_pos );
97
- }
98
-
99
- return $text.$pad;
100
- }
101
-
102
- /**
103
- * extract_tags()
104
- * Extract specific HTML tags and their attributes from a string.
105
- *
106
- * You can either specify one tag, an array of tag names, or a regular expression that matches the tag name(s).
107
- * If multiple tags are specified you must also set the $selfclosing parameter and it must be the same for
108
- * all specified tags (so you can't extract both normal and self-closing tags in one go).
109
- *
110
- * The function returns a numerically indexed array of extracted tags. Each entry is an associative array
111
- * with these keys :
112
- * tag_name - the name of the extracted tag, e.g. "a" or "img".
113
- * offset - the numberic offset of the first character of the tag within the HTML source.
114
- * contents - the inner HTML of the tag. This is always empty for self-closing tags.
115
- * attributes - a name -> value array of the tag's attributes, or an empty array if the tag has none.
116
- * full_tag - the entire matched tag, e.g. '<a href="http://example.com">example.com</a>'. This key
117
- * will only be present if you set $return_the_entire_tag to true.
118
- *
119
- * @param string $html The HTML code to search for tags.
120
- * @param string|array $tag The tag(s) to extract.
121
- * @param bool $selfclosing Whether the tag is self-closing or not. Setting it to null will force the script to try and make an educated guess.
122
- * @param bool $return_the_entire_tag Return the entire matched tag in 'full_tag' key of the results array.
123
- * @param string $charset The character set of the HTML code. Defaults to ISO-8859-1.
124
- *
125
- * @return array An array of extracted tags, or an empty array if no matching tags were found.
126
- */
127
- static function extract_tags( $html, $tag, $selfclosing = null, $return_the_entire_tag = false, $charset = 'ISO-8859-1' ) {
128
-
129
- if ( is_array( $tag ) ) {
130
- $tag = implode( '|', $tag );
131
- }
132
-
133
- //If the user didn't specify if $tag is a self-closing tag we try to auto-detect it
134
- //by checking against a list of known self-closing tags.
135
- $selfclosing_tags = array( 'area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta', 'col', 'param' );
136
- if ( is_null( $selfclosing ) ) {
137
- $selfclosing = in_array( $tag, $selfclosing_tags );
138
- }
139
-
140
- //The regexp is different for normal and self-closing tags because I can't figure out
141
- //how to make a sufficiently robust unified one.
142
- if ( $selfclosing ) {
143
- $tag_pattern =
144
- '@<(?P<tag>' . $tag . ') # <tag
145
- (?P<attributes>\s[^>]+)? # attributes, if any
146
- \s*/?> # /> or just >, being lenient here
147
- @xsi';
148
- } else {
149
- $tag_pattern =
150
- '@<(?P<tag>' . $tag . ') # <tag
151
- (?P<attributes>\s[^>]+)? # attributes, if any
152
- \s*> # >
153
- (?P<contents>.*?) # tag contents
154
- </(?P=tag)> # the closing </tag>
155
- @xsi';
156
- }
157
-
158
- $attribute_pattern =
159
- '@
160
- (?P<name>\w+) # attribute name
161
- \s*=\s*
162
- (
163
- (?P<quote>[\"\'])(?P<value_quoted>.*?)(?P=quote) # a quoted value
164
- | # or
165
- (?P<value_unquoted>[^\s"\']+?)(?:\s+|$) # an unquoted value (terminated by whitespace or EOF)
166
- )
167
- @xsi';
168
-
169
- //Find all tags
170
- if ( ! preg_match_all( $tag_pattern, $html, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ) ) {
171
- //Return an empty array if we didn't find anything
172
- return array();
173
- }
174
-
175
- $tags = array();
176
- foreach ( $matches as $match ) {
177
-
178
- // Parse tag attributes, if any.
179
- $attributes = array();
180
- if ( ! empty( $match['attributes'][0] ) ) {
181
-
182
- if ( preg_match_all( $attribute_pattern, $match['attributes'][0], $attribute_data, PREG_SET_ORDER ) ) {
183
- //Turn the attribute data into a name->value array
184
- foreach ( $attribute_data as $attr ) {
185
- if( ! empty( $attr['value_quoted'] ) ) {
186
- $value = $attr['value_quoted'];
187
- } else if( ! empty( $attr['value_unquoted'] ) ) {
188
- $value = $attr['value_unquoted'];
189
- } else {
190
- $value = '';
191
- }
192
-
193
- // Passing the value through html_entity_decode is handy when you want
194
- // to extract link URLs or something like that. You might want to remove
195
- // or modify this call if it doesn't fit your situation.
196
- $value = html_entity_decode( $value, ENT_QUOTES, $charset );
197
-
198
- $attributes[ $attr['name'] ] = $value;
199
- }
200
- }
201
-
202
- }
203
-
204
- $tag = array(
205
- 'tag_name' => $match['tag'][0],
206
- 'offset' => $match[0][1],
207
- 'contents' => ! empty( $match['contents'] ) ? $match['contents'][0] : '', // Empty for self-closing tags.
208
- 'attributes' => $attributes,
209
- );
210
- if ( $return_the_entire_tag ) {
211
- $tag['full_tag'] = $match[0][0];
212
- }
213
-
214
- $tags[] = $tag;
215
- }
216
-
217
- return $tags;
218
- }
219
-
220
- /**
221
- * Get the value of a cookie.
222
- *
223
- * @param string $cookie_name The name of the cookie to return.
224
- * @param string $default_value Optional. If the cookie is not set, this value will be returned instead. Defaults to an empty string.
225
- * @return mixed Either the value of the requested cookie, or $default_value.
226
- */
227
- static function get_cookie( $cookie_name, $default_value = '' ) {
228
- if ( isset( $_COOKIE[$cookie_name] ) ) {
229
- return $_COOKIE[$cookie_name];
230
- } else {
231
- return $default_value;
232
- }
233
- }
234
-
235
- /**
236
- * Format a time delta using a fuzzy format, e.g. '2 minutes ago', '2 days', etc.
237
- *
238
- * @param int $delta Time period in seconds.
239
- * @param string $type Optional. The output template to use.
240
- * @return string
241
- */
242
- static function fuzzy_delta( $delta, $template = 'default' ) {
243
-
244
- $templates = array(
245
- 'seconds' => array(
246
- 'default' => _n_noop('%d second', '%d seconds'),
247
- 'ago' => _n_noop('%d second ago', '%d seconds ago'),
248
- ),
249
- 'minutes' => array(
250
- 'default' => _n_noop('%d minute', '%d minutes'),
251
- 'ago' => _n_noop('%d minute ago', '%d minutes ago'),
252
- ),
253
- 'hours' => array(
254
- 'default' => _n_noop('%d hour', '%d hours'),
255
- 'ago' => _n_noop('%d hour ago', '%d hours ago'),
256
- ),
257
- 'days' => array(
258
- 'default' => _n_noop('%d day', '%d days'),
259
- 'ago' => _n_noop('%d day ago', '%d days ago'),
260
- ),
261
- 'months' => array(
262
- 'default' => _n_noop('%d month', '%d months'),
263
- 'ago' => _n_noop('%d month ago', '%d months ago'),
264
- ),
265
- );
266
-
267
- if ( $delta < 1 ) {
268
- $delta = 1;
269
- }
270
-
271
- if ( $delta < MINUTE_IN_SECONDS ) {
272
- $units = 'seconds';
273
- } elseif ( $delta < HOUR_IN_SECONDS ) {
274
- $delta = intval( $delta / MINUTE_IN_SECONDS );
275
- $units = 'minutes';
276
- } elseif ( $delta < DAY_IN_SECONDS ) {
277
- $delta = intval( $delta / HOUR_IN_SECONDS );
278
- $units = 'hours';
279
- } elseif ( $delta < MONTH_IN_SECONDS ) {
280
- $delta = intval( $delta / DAY_IN_SECONDS );
281
- $units = 'days';
282
- } else {
283
- $delta = intval( $delta / MONTH_IN_SECONDS );
284
- $units = 'months';
285
- }
286
-
287
- return sprintf(
288
- _n(
289
- $templates[$units][$template][0],
290
- $templates[$units][$template][1],
291
- $delta,
292
- 'broken-link-checker'
293
- ),
294
- $delta
295
- );
296
- }
297
-
298
- /**
299
- * Optimize the plugin's tables
300
- *
301
- * @return void
302
- */
303
- static function optimize_database(){
304
- global $wpdb; /** @var wpdb $wpdb */
305
-
306
- $wpdb->query( "OPTIMIZE TABLE {$wpdb->prefix}blc_links, {$wpdb->prefix}blc_instances, {$wpdb->prefix}blc_synch" );
307
- }
308
-
309
- /**
310
- * Get the server's load averages.
311
- *
312
- * Returns an array with three samples - the 1 minute avg, the 5 minute avg, and the 15 minute avg.
313
- *
314
- * @param integer $cache How long the load averages may be cached, in seconds. Set to 0 to get maximally up-to-date data.
315
- * @return array|null Array, or NULL if retrieving load data is impossible (e.g. when running on a Windows box).
316
- */
317
- static function get_server_load( $cache = 5 ) {
318
- static $cached_load = null;
319
- static $cached_when = 0;
320
-
321
- if ( ! empty( $cache ) && ((time() - $cached_when) <= $cache) ) {
322
- return $cached_load;
323
- }
324
-
325
- $load = null;
326
-
327
- if ( function_exists( 'sys_getloadavg' ) ) {
328
- $load = sys_getloadavg();
329
- } else {
330
- $loadavg_file = '/proc/loadavg';
331
- if ( @is_readable( $loadavg_file ) ) {
332
- $load = explode( ' ', file_get_contents( $loadavg_file ) );
333
- $load = array_map( 'floatval', $load );
334
- }
335
- }
336
-
337
- $cached_load = $load;
338
- $cached_when = time();
339
- return $load;
340
- }
341
-
342
- /**
343
- * Convert an internationalized domain name or URL to ASCII-compatible encoding.
344
- *
345
- * @param string $url Either a domain name or a complete URL.
346
- * @param string $charset The character encoding of the $url parameter. Defaults to the encoding set in Settings -> Reading.
347
- * @return string
348
- */
349
- static function idn_to_ascii( $url, $charset = '' ) {
350
- $idn = blcUtility::get_idna_converter();
351
- if ( $idn != null ) {
352
- if ( empty( $charset ) ) {
353
- $charset = get_bloginfo( 'charset' );
354
- }
355
-
356
- // Encode only the host.
357
- if ( preg_match( '@(\w+:/*)?([^/:]+)(.*$)?@s', $url, $matches ) ) {
358
- $host = $matches[2];
359
- if ( ( strtoupper( $charset ) != 'UTF-8') && ( strtoupper( $charset ) != 'UTF8') ) {
360
- $host = encode_utf8( $host, $charset, true );
361
- }
362
- $host = $idn->encode( $host );
363
- $url = $matches[1] . $host . $matches[3];
364
- }
365
- }
366
-
367
- return $url;
368
- }
369
-
370
- /**
371
- * Convert an internationalized domain name (or URL) from ASCII-compatible encoding to UTF8.
372
- *
373
- * @param string $url
374
- * @return string
375
- */
376
- static function idn_to_utf8( $url ) {
377
- $idn = blcUtility::get_idna_converter();
378
- if ( null !== $idn ) {
379
- $url = $idn->decode( $url );
380
- }
381
-
382
- return $url;
383
- }
384
-
385
- /**
386
- * Get an instance of idna_converter
387
- *
388
- * @return idna_convert|null Either an instance of IDNA converter, or NULL if the converter class is not available
389
- */
390
- static function get_idna_converter() {
391
- static $idn = null;
392
- if ( ( null === $idn ) && class_exists( 'idna_convert' ) ) {
393
- $idn = new idna_convert();
394
- }
395
- return $idn;
396
- }
397
-
398
- /**
399
- * Generate a numeric hash from a string. The result will be constrained to the specified interval.
400
- *
401
- * @static
402
- * @param string $input
403
- * @param int $min
404
- * @param int $max
405
- * @return float
406
- */
407
- public static function constrained_hash( $input, $min = 0, $max = 1 ) {
408
- $bytes_to_use = 3;
409
- $md5_char_count = 32;
410
- $hash = substr( md5( $input ), $md5_char_count - $bytes_to_use * 2 );
411
- $hash = intval( hexdec( $hash ) );
412
- return $min + ( ( $max - $min ) * ( $hash / ( pow( 2, $bytes_to_use * 8 ) - 1) ) );
413
- }
414
-
415
- }//class
416
-
417
- }//class_exists
1
+ <?php
2
+
3
+ /**
4
+ * @author W-Shadow
5
+ * @copyright 2010
6
+ */
7
+
8
+ if ( ! function_exists( 'sys_get_temp_dir' ) ) {
9
+ function sys_get_temp_dir() {
10
+ if ( ! empty( $_ENV['TMP'] ) ) { return realpath( $_ENV['TMP'] ); }
11
+ if ( ! empty( $_ENV['TMPDIR'] ) ) { return realpath( $_ENV['TMPDIR'] ); }
12
+ if ( ! empty( $_ENV['TEMP'] ) ) { return realpath( $_ENV['TEMP'] ); }
13
+ $tempfile = tempnam( uniqid( rand(),TRUE ),'' );
14
+ if ( @file_exists( $tempfile ) ) {
15
+ unlink( $tempfile );
16
+ return realpath( dirname( $tempfile ) );
17
+ }
18
+ return '';
19
+ }
20
+ }
21
+
22
+ //Include the internationalized domain name converter (requires PHP 5)
23
+ if ( version_compare( phpversion(), '5.0.0', '>=' ) && ! class_exists( 'idna_convert' ) ) {
24
+ include BLC_DIRECTORY . '/idn/idna_convert.class.php';
25
+ if ( ! function_exists( 'encode_utf8' ) ) {
26
+ include BLC_DIRECTORY . '/idn/transcode_wrapper.php';
27
+ }
28
+ }
29
+
30
+
31
+ if ( ! class_exists( 'blcUtility' ) ) {
32
+ class blcUtility {
33
+ /**
34
+ * Checks if PHP is running in safe mode
35
+ * blcUtility::is_safe_mode()
36
+ *
37
+ * @return bool
38
+ */
39
+ static function is_safe_mode() {
40
+ // Check php.ini safe_mode only if PHP version is lower than 5.3.0, else set to false.
41
+ if ( version_compare( phpversion(), '5.3.0', '<' ) ) {
42
+ $safe_mode = ini_get( 'safe_mode' );
43
+ } else {
44
+ $safe_mode = false;
45
+ }
46
+
47
+ // Null, 0, '', '0' and so on count as false.
48
+ if ( ! $safe_mode ) {
49
+ return false;
50
+ }
51
+ // Test for some textual true/false variations.
52
+ switch ( strtolower( $safe_mode ) ) {
53
+ case 'on':
54
+ case 'true':
55
+ case 'yes':
56
+ return true;
57
+
58
+ case 'off':
59
+ case 'false':
60
+ case 'no':
61
+ return false;
62
+
63
+ default: // Let PHP handle anything else.
64
+ return (bool) (int) $safe_mode;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * blcUtility::is_open_basedir()
70
+ * Checks if open_basedir is enabled
71
+ *
72
+ * @return bool
73
+ */
74
+ static function is_open_basedir(){
75
+ $open_basedir = ini_get( 'open_basedir' );
76
+ return $open_basedir && ( strtolower( $open_basedir ) != 'none' );
77
+ }
78
+
79
+ /**
80
+ * Truncate a string on a specified boundary character.
81
+ *
82
+ * @param string $text The text to truncate.
83
+ * @param integer $max_characters Return no more than $max_characters
84
+ * @param string $break Break on this character. Defaults to space.
85
+ * @param string $pad Pad the truncated string with this string. Defaults to an HTML ellipsis.
86
+ * @return string
87
+ */
88
+ static function truncate( $text, $max_characters = 0, $break = ' ', $pad = '&hellip;' ) {
89
+ if ( strlen( $text ) <= $max_characters ) {
90
+ return $text;
91
+ }
92
+
93
+ $text = substr( $text, 0, $max_characters );
94
+ $break_pos = strrpos( $text, $break );
95
+ if ( false !== $break_pos ) {
96
+ $text = substr( $text, 0, $break_pos );
97
+ }
98
+
99
+ return $text.$pad;
100
+ }
101
+
102
+ /**
103
+ * extract_tags()
104
+ * Extract specific HTML tags and their attributes from a string.
105
+ *
106
+ * You can either specify one tag, an array of tag names, or a regular expression that matches the tag name(s).
107
+ * If multiple tags are specified you must also set the $selfclosing parameter and it must be the same for
108
+ * all specified tags (so you can't extract both normal and self-closing tags in one go).
109
+ *
110
+ * The function returns a numerically indexed array of extracted tags. Each entry is an associative array
111
+ * with these keys :
112
+ * tag_name - the name of the extracted tag, e.g. "a" or "img".
113
+ * offset - the numberic offset of the first character of the tag within the HTML source.
114
+ * contents - the inner HTML of the tag. This is always empty for self-closing tags.
115
+ * attributes - a name -> value array of the tag's attributes, or an empty array if the tag has none.
116
+ * full_tag - the entire matched tag, e.g. '<a href="http://example.com">example.com</a>'. This key
117
+ * will only be present if you set $return_the_entire_tag to true.
118
+ *
119
+ * @param string $html The HTML code to search for tags.
120
+ * @param string|array $tag The tag(s) to extract.
121
+ * @param bool $selfclosing Whether the tag is self-closing or not. Setting it to null will force the script to try and make an educated guess.
122
+ * @param bool $return_the_entire_tag Return the entire matched tag in 'full_tag' key of the results array.
123
+ * @param string $charset The character set of the HTML code. Defaults to ISO-8859-1.
124
+ *
125
+ * @return array An array of extracted tags, or an empty array if no matching tags were found.
126
+ */
127
+ static function extract_tags( $html, $tag, $selfclosing = null, $return_the_entire_tag = false, $charset = 'ISO-8859-1' ) {
128
+
129
+ if ( is_array( $tag ) ) {
130
+ $tag = implode( '|', $tag );
131
+ }
132
+
133
+ //If the user didn't specify if $tag is a self-closing tag we try to auto-detect it
134
+ //by checking against a list of known self-closing tags.
135
+ $selfclosing_tags = array( 'area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta', 'col', 'param' );
136
+ if ( is_null( $selfclosing ) ) {
137
+ $selfclosing = in_array( $tag, $selfclosing_tags );
138
+ }
139
+
140
+ //The regexp is different for normal and self-closing tags because I can't figure out
141
+ //how to make a sufficiently robust unified one.
142
+ if ( $selfclosing ) {
143
+ $tag_pattern =
144
+ '@<(?P<tag>' . $tag . ') # <tag
145
+ (?P<attributes>\s[^>]+)? # attributes, if any
146
+ \s*/?> # /> or just >, being lenient here
147
+ @xsi';
148
+ } else {
149
+ $tag_pattern =
150
+ '@<(?P<tag>' . $tag . ') # <tag
151
+ (?P<attributes>\s[^>]+)? # attributes, if any
152
+ \s*> # >
153
+ (?P<contents>.*?) # tag contents
154
+ </(?P=tag)> # the closing </tag>
155
+ @xsi';
156
+ }
157
+
158
+ $attribute_pattern =
159
+ '@
160
+ (?P<name>\w+) # attribute name
161
+ \s*=\s*
162
+ (
163
+ (?P<quote>[\"\'])(?P<value_quoted>.*?)(?P=quote) # a quoted value
164
+ | # or
165
+ (?P<value_unquoted>[^\s"\']+?)(?:\s+|$) # an unquoted value (terminated by whitespace or EOF)
166
+ )
167
+ @xsi';
168
+
169
+ //Find all tags
170
+ if ( ! preg_match_all( $tag_pattern, $html, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ) ) {
171
+ //Return an empty array if we didn't find anything
172
+ return array();
173
+ }
174
+
175
+ $tags = array();
176
+ foreach ( $matches as $match ) {
177
+
178
+ // Parse tag attributes, if any.
179
+ $attributes = array();
180
+ if ( ! empty( $match['attributes'][0] ) ) {
181
+
182
+ if ( preg_match_all( $attribute_pattern, $match['attributes'][0], $attribute_data, PREG_SET_ORDER ) ) {
183
+ //Turn the attribute data into a name->value array
184
+ foreach ( $attribute_data as $attr ) {
185
+ if( ! empty( $attr['value_quoted'] ) ) {
186
+ $value = $attr['value_quoted'];
187
+ } else if( ! empty( $attr['value_unquoted'] ) ) {
188
+ $value = $attr['value_unquoted'];
189
+ } else {
190
+ $value = '';
191
+ }
192
+
193
+ // Passing the value through html_entity_decode is handy when you want
194
+ // to extract link URLs or something like that. You might want to remove
195
+ // or modify this call if it doesn't fit your situation.
196
+ $value = html_entity_decode( $value, ENT_QUOTES, $charset );
197
+
198
+ $attributes[ $attr['name'] ] = $value;
199
+ }
200
+ }
201
+
202
+ }
203
+
204
+ $tag = array(
205
+ 'tag_name' => $match['tag'][0],
206
+ 'offset' => $match[0][1],
207
+ 'contents' => ! empty( $match['contents'] ) ? $match['contents'][0] : '', // Empty for self-closing tags.
208
+ 'attributes' => $attributes,
209
+ );
210
+ if ( $return_the_entire_tag ) {
211
+ $tag['full_tag'] = $match[0][0];
212
+ }
213
+
214
+ $tags[] = $tag;
215
+ }
216
+
217
+ return $tags;
218
+ }
219
+
220
+ /**
221
+ * Get the value of a cookie.
222
+ *
223
+ * @param string $cookie_name The name of the cookie to return.
224
+ * @param string $default_value Optional. If the cookie is not set, this value will be returned instead. Defaults to an empty string.
225
+ * @return mixed Either the value of the requested cookie, or $default_value.
226
+ */
227
+ static function get_cookie( $cookie_name, $default_value = '' ) {
228
+ if ( isset( $_COOKIE[$cookie_name] ) ) {
229
+ return $_COOKIE[$cookie_name];
230
+ } else {
231
+ return $default_value;
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Format a time delta using a fuzzy format, e.g. '2 minutes ago', '2 days', etc.
237
+ *
238
+ * @param int $delta Time period in seconds.
239
+ * @param string $type Optional. The output template to use.
240
+ * @return string
241
+ */
242
+ static function fuzzy_delta( $delta, $template = 'default' ) {
243
+
244
+ $templates = array(
245
+ 'seconds' => array(
246
+ 'default' => _n_noop('%d second', '%d seconds'),
247
+ 'ago' => _n_noop('%d second ago', '%d seconds ago'),
248
+ ),
249
+ 'minutes' => array(
250
+ 'default' => _n_noop('%d minute', '%d minutes'),
251
+ 'ago' => _n_noop('%d minute ago', '%d minutes ago'),
252
+ ),
253
+ 'hours' => array(
254
+ 'default' => _n_noop('%d hour', '%d hours'),
255
+ 'ago' => _n_noop('%d hour ago', '%d hours ago'),
256
+ ),
257
+ 'days' => array(
258
+ 'default' => _n_noop('%d day', '%d days'),
259
+ 'ago' => _n_noop('%d day ago', '%d days ago'),
260
+ ),
261
+ 'months' => array(
262
+ 'default' => _n_noop('%d month', '%d months'),
263
+ 'ago' => _n_noop('%d month ago', '%d months ago'),
264
+ ),
265
+ );
266
+
267
+ if ( $delta < 1 ) {
268
+ $delta = 1;
269
+ }
270
+
271
+ if ( $delta < MINUTE_IN_SECONDS ) {
272
+ $units = 'seconds';
273
+ } elseif ( $delta < HOUR_IN_SECONDS ) {
274
+ $delta = intval( $delta / MINUTE_IN_SECONDS );
275
+ $units = 'minutes';
276
+ } elseif ( $delta < DAY_IN_SECONDS ) {
277
+ $delta = intval( $delta / HOUR_IN_SECONDS );
278
+ $units = 'hours';
279
+ } elseif ( $delta < MONTH_IN_SECONDS ) {
280
+ $delta = intval( $delta / DAY_IN_SECONDS );
281
+ $units = 'days';
282
+ } else {
283
+ $delta = intval( $delta / MONTH_IN_SECONDS );
284
+ $units = 'months';
285
+ }
286
+
287
+ return sprintf(
288
+ _n(
289
+ $templates[$units][$template][0],
290
+ $templates[$units][$template][1],
291
+ $delta,
292
+ 'broken-link-checker'
293
+ ),
294
+ $delta
295
+ );
296
+ }
297
+
298
+ /**
299
+ * Optimize the plugin's tables
300
+ *
301
+ * @return void
302
+ */
303
+ static function optimize_database(){
304
+ global $wpdb; /** @var wpdb $wpdb */
305
+
306
+ $wpdb->query( "OPTIMIZE TABLE {$wpdb->prefix}blc_links, {$wpdb->prefix}blc_instances, {$wpdb->prefix}blc_synch" );
307
+ }
308
+
309
+ /**
310
+ * Get the server's load averages.
311
+ *
312
+ * Returns an array with three samples - the 1 minute avg, the 5 minute avg, and the 15 minute avg.
313
+ *
314
+ * @param integer $cache How long the load averages may be cached, in seconds. Set to 0 to get maximally up-to-date data.
315
+ * @return array|null Array, or NULL if retrieving load data is impossible (e.g. when running on a Windows box).
316
+ */
317
+ static function get_server_load( $cache = 5 ) {
318
+ static $cached_load = null;
319
+ static $cached_when = 0;
320
+
321
+ if ( ! empty( $cache ) && ((time() - $cached_when) <= $cache) ) {
322
+ return $cached_load;
323
+ }
324
+
325
+ $load = null;
326
+
327
+ if ( function_exists( 'sys_getloadavg' ) ) {
328
+ $load = sys_getloadavg();
329
+ } else {
330
+ $loadavg_file = '/proc/loadavg';
331
+ if ( @is_readable( $loadavg_file ) ) {
332
+ $load = explode( ' ', file_get_contents( $loadavg_file ) );
333
+ $load = array_map( 'floatval', $load );
334
+ }
335
+ }
336
+
337
+ $cached_load = $load;
338
+ $cached_when = time();
339
+ return $load;
340
+ }
341
+
342
+ /**
343
+ * Convert an internationalized domain name or URL to ASCII-compatible encoding.
344
+ *
345
+ * @param string $url Either a domain name or a complete URL.
346
+ * @param string $charset The character encoding of the $url parameter. Defaults to the encoding set in Settings -> Reading.
347
+ * @return string
348
+ */
349
+ static function idn_to_ascii( $url, $charset = '' ) {
350
+ $idn = blcUtility::get_idna_converter();
351
+ if ( $idn != null ) {
352
+ if ( empty( $charset ) ) {
353
+ $charset = get_bloginfo( 'charset' );
354
+ }
355
+
356
+ // Encode only the host.
357
+ if ( preg_match( '@(\w+:/*)?([^/:]+)(.*$)?@s', $url, $matches ) ) {
358
+ $host = $matches[2];
359
+ if ( ( strtoupper( $charset ) != 'UTF-8') && ( strtoupper( $charset ) != 'UTF8') ) {
360
+ $host = encode_utf8( $host, $charset, true );
361
+ }
362
+ $host = $idn->encode( $host );
363
+ $url = $matches[1] . $host . $matches[3];
364
+ }
365
+ }
366
+
367
+ return $url;
368
+ }
369
+
370
+ /**
371
+ * Convert an internationalized domain name (or URL) from ASCII-compatible encoding to UTF8.
372
+ *
373
+ * @param string $url
374
+ * @return string
375
+ */
376
+ static function idn_to_utf8( $url ) {
377
+ $idn = blcUtility::get_idna_converter();
378
+ if ( null !== $idn ) {
379
+ $url = $idn->decode( $url );
380
+ }
381
+
382
+ return $url;
383
+ }
384
+
385
+ /**
386
+ * Get an instance of idna_converter
387
+ *
388
+ * @return idna_convert|null Either an instance of IDNA converter, or NULL if the converter class is not available
389
+ */
390
+ static function get_idna_converter() {
391
+ static $idn = null;
392
+ if ( ( null === $idn ) && class_exists( 'idna_convert' ) ) {
393
+ $idn = new idna_convert();
394
+ }
395
+ return $idn;
396
+ }
397
+
398
+ /**
399
+ * Generate a numeric hash from a string. The result will be constrained to the specified interval.
400
+ *
401
+ * @static
402
+ * @param string $input
403
+ * @param int $min
404
+ * @param int $max
405
+ * @return float
406
+ */
407
+ public static function constrained_hash( $input, $min = 0, $max = 1 ) {
408
+ $bytes_to_use = 3;
409
+ $md5_char_count = 32;
410
+ $hash = substr( md5( $input ), $md5_char_count - $bytes_to_use * 2 );
411
+ $hash = intval( hexdec( $hash ) );
412
+ return $min + ( ( $max - $min ) * ( $hash / ( pow( 2, $bytes_to_use * 8 ) - 1) ) );
413
+ }
414
+
415
+ }//class
416
+
417
+ }//class_exists
includes/wp-mutex.php CHANGED
@@ -1,57 +1,57 @@
1
- <?php
2
-
3
- if ( !class_exists('WPMutex') ):
4
-
5
- class WPMutex {
6
- /**
7
- * Get an exclusive named lock.
8
- *
9
- * @param string $name
10
- * @param integer $timeout
11
- * @param bool $network_wide
12
- * @return bool
13
- */
14
- static function acquire($name, $timeout = 0, $network_wide = false){
15
- global $wpdb; /* @var wpdb $wpdb */
16
- if ( !$network_wide ){
17
- $name = WPMutex::_get_private_name($name);
18
- }
19
- $state = $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, %d)', $name, $timeout));
20
- return $state == 1;
21
- }
22
-
23
- /**
24
- * Release a named lock.
25
- *
26
- * @param string $name
27
- * @param bool $network_wide
28
- * @return bool
29
- */
30
- static function release($name, $network_wide = false){
31
- global $wpdb; /* @var wpdb $wpdb */
32
- if ( !$network_wide ){
33
- $name = WPMutex::_get_private_name($name);
34
- }
35
- $released = $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $name));
36
- return $released == 1;
37
- }
38
-
39
- /**
40
- * Given a generic lock name, create a new one that's unique to the current blog.
41
- *
42
- * @access private
43
- *
44
- * @param string $name
45
- * @return string
46
- */
47
- static function _get_private_name($name){
48
- global $current_blog;
49
- if ( function_exists('is_multisite') && is_multisite() && isset($current_blog->blog_id) ){
50
- $name .= '-blog-' . $current_blog->blog_id;
51
- }
52
- return $name;
53
- }
54
- }
55
-
56
- endif;
57
-
1
+ <?php
2
+
3
+ if ( !class_exists('WPMutex') ):
4
+
5
+ class WPMutex {
6
+ /**
7
+ * Get an exclusive named lock.
8
+ *
9
+ * @param string $name
10
+ * @param integer $timeout
11
+ * @param bool $network_wide
12
+ * @return bool
13
+ */
14
+ static function acquire($name, $timeout = 0, $network_wide = false){
15
+ global $wpdb; /* @var wpdb $wpdb */
16
+ if ( !$network_wide ){
17
+ $name = WPMutex::_get_private_name($name);
18
+ }
19
+ $state = $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, %d)', $name, $timeout));
20
+ return $state == 1;
21
+ }
22
+
23
+ /**
24
+ * Release a named lock.
25
+ *
26
+ * @param string $name
27
+ * @param bool $network_wide
28
+ * @return bool
29
+ */
30
+ static function release($name, $network_wide = false){
31
+ global $wpdb; /* @var wpdb $wpdb */
32
+ if ( !$network_wide ){
33
+ $name = WPMutex::_get_private_name($name);
34
+ }
35
+ $released = $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $name));
36
+ return $released == 1;
37
+ }
38
+
39
+ /**
40
+ * Given a generic lock name, create a new one that's unique to the current blog.
41
+ *
42
+ * @access private
43
+ *
44
+ * @param string $name
45
+ * @return string
46
+ */
47
+ static function _get_private_name($name){
48
+ global $current_blog;
49
+ if ( function_exists('is_multisite') && is_multisite() && isset($current_blog->blog_id) ){
50
+ $name .= '-blog-' . $current_blog->blog_id;
51
+ }
52
+ return $name;
53
+ }
54
+ }
55
+
56
+ endif;
57
+
js/jquery.cookie.js CHANGED
File without changes
js/sprintf.js CHANGED
@@ -1,55 +1,55 @@
1
- /**
2
- * sprintf() for JavaScript v.0.4
3
- *
4
- * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
5
- * Thanks to David Baird (unit test and patch).
6
- *
7
- * This program is free software; you can redistribute it and/or modify it under
8
- * the terms of the GNU General Public License as published by the Free Software
9
- * Foundation; either version 2 of the License, or (at your option) any later
10
- * version.
11
- *
12
- * This program is distributed in the hope that it will be useful, but WITHOUT
13
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14
- * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15
- * details.
16
- *
17
- * You should have received a copy of the GNU General Public License along with
18
- * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19
- * Place, Suite 330, Boston, MA 02111-1307 USA
20
- */
21
-
22
- function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }
23
-
24
- function sprintf () {
25
- var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
26
- while (f) {
27
- if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
28
- else if (m = /^\x25{2}/.exec(f)) o.push('%');
29
- else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
30
- if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
31
- if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
32
- throw("Expecting number but found " + typeof(a));
33
- switch (m[7]) {
34
- case 'b': a = a.toString(2); break;
35
- case 'c': a = String.fromCharCode(a); break;
36
- case 'd': a = parseInt(a); break;
37
- case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
38
- case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
39
- case 'o': a = a.toString(8); break;
40
- case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
41
- case 'u': a = Math.abs(a); break;
42
- case 'x': a = a.toString(16); break;
43
- case 'X': a = a.toString(16).toUpperCase(); break;
44
- }
45
- a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
46
- c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
47
- x = m[5] - String(a).length;
48
- p = m[5] ? str_repeat(c, x) : '';
49
- o.push(m[4] ? a + p : p + a);
50
- }
51
- else throw ("Huh ?!");
52
- f = f.substring(m[0].length);
53
- }
54
- return o.join('');
55
- }
1
+ /**
2
+ * sprintf() for JavaScript v.0.4
3
+ *
4
+ * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
5
+ * Thanks to David Baird (unit test and patch).
6
+ *
7
+ * This program is free software; you can redistribute it and/or modify it under
8
+ * the terms of the GNU General Public License as published by the Free Software
9
+ * Foundation; either version 2 of the License, or (at your option) any later
10
+ * version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful, but WITHOUT
13
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15
+ * details.
16
+ *
17
+ * You should have received a copy of the GNU General Public License along with
18
+ * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19
+ * Place, Suite 330, Boston, MA 02111-1307 USA
20
+ */
21
+
22
+ function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }
23
+
24
+ function sprintf () {
25
+ var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
26
+ while (f) {
27
+ if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
28
+ else if (m = /^\x25{2}/.exec(f)) o.push('%');
29
+ else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
30
+ if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
31
+ if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
32
+ throw("Expecting number but found " + typeof(a));
33
+ switch (m[7]) {
34
+ case 'b': a = a.toString(2); break;
35
+ case 'c': a = String.fromCharCode(a); break;
36
+ case 'd': a = parseInt(a); break;
37
+ case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
38
+ case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
39
+ case 'o': a = a.toString(8); break;
40
+ case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
41
+ case 'u': a = Math.abs(a); break;
42
+ case 'x': a = a.toString(16); break;
43
+ case 'X': a = a.toString(16).toUpperCase(); break;
44
+ }
45
+ a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
46
+ c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
47
+ x = m[5] - String(a).length;
48
+ p = m[5] ? str_repeat(c, x) : '';
49
+ o.push(m[4] ? a + p : p + a);
50
+ }
51
+ else throw ("Huh ?!");
52
+ f = f.substring(m[0].length);
53
+ }
54
+ return o.join('');
55
+ }
languages/broken-link-checker-zh_CN.mo ADDED
Binary file
modules/checkers/http.php CHANGED
File without changes
modules/containers/acf_field.php CHANGED
File without changes
modules/containers/blogroll.php CHANGED
@@ -1,307 +1,307 @@
1
- <?php
2
- /*
3
- Plugin Name: Blogroll items
4
- Description:
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleID: blogroll
9
- ModuleCategory: container
10
- ModuleClassName: blcBookmarkManager
11
- */
12
-
13
- class blcBookmark extends blcContainer{
14
-
15
- function ui_get_source($container_field = '', $context = 'display'){
16
- $bookmark = $this->get_wrapped_object();
17
-
18
- $image = sprintf(
19
- '<img src="%1$s" class="blc-small-image" title="%2$s" alt="%2$s">',
20
- esc_attr( plugins_url('/images/font-awesome/font-awesome-link.png', BLC_PLUGIN_FILE) ),
21
- __('Bookmark', 'broken-link-checker')
22
- );
23
-
24
- $link_name = sprintf(
25
- '<a class="row-title" href="%s" title="%s">%s</a>',
26
- $this->get_edit_url(),
27
- __('Edit this bookmark', 'broken-link-checker'),
28
- sanitize_bookmark_field('link_name', $bookmark->link_name, $this->container_id, 'display')
29
- );
30
-
31
- if ( $context != 'email' ){
32
- return "$image $link_name";
33
- } else {
34
- return $link_name;
35
- }
36
- }
37
-
38
- function ui_get_action_links($container_field){
39
- //Inline action links for bookmarks
40
- $bookmark = $this->get_wrapped_object();
41
-
42
- $delete_url = admin_url( wp_nonce_url("link.php?action=delete&link_id={$this->container_id}", 'delete-bookmark_' . $this->container_id) );
43
-
44
- $actions = array();
45
- if ( current_user_can('manage_links') ) {
46
- $actions['edit'] = '<span class="edit"><a href="' . $this->get_edit_url() . '" title="' . esc_attr(__('Edit this bookmark', 'broken-link-checker')) . '">' . __('Edit') . '</a>';
47
- $actions['delete'] = "<span class='delete'><a class='submitdelete' href='" . esc_url($delete_url) . "' onclick=\"if ( confirm('" . esc_js(sprintf( __("You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete."), $bookmark->link_name)) . "') ) { return true;}return false;\">" . __('Delete') . "</a>";
48
- }
49
-
50
- return $actions;
51
- }
52
-
53
- function get_edit_url(){
54
- return esc_url(admin_url("link.php?action=edit&link_id={$this->container_id}"));
55
- }
56
-
57
- /**
58
- * Retrieve the bookmark associated with this container.
59
- *
60
- * @access protected
61
- *
62
- * @param bool $ensure_consistency Set this to true to ignore the cached $wrapped_object value and retrieve an up-to-date copy of the wrapped object from the DB (or WP's internal cache).
63
- * @return object Bookmark data.
64
- */
65
- function get_wrapped_object($ensure_consistency = false){
66
- if( $ensure_consistency || is_null($this->wrapped_object) ){
67
- $this->wrapped_object = get_bookmark($this->container_id);
68
- }
69
- return $this->wrapped_object;
70
- }
71
-
72
- /**
73
- * Update the bookmark associated with this container.
74
- *
75
- * @access protected
76
- *
77
- * @return bool|WP_Error True on success, an error if something went wrong.
78
- */
79
- function update_wrapped_object(){
80
- if ( is_null($this->wrapped_object) ){
81
- return new WP_Error(
82
- 'no_wrapped_object',
83
- __('Nothing to update', 'broken-link-checker')
84
- );
85
- }
86
-
87
- //wp_update_link() expects it's argument to be an array.
88
- $data = (array)$this->wrapped_object;
89
- //Update the bookmark
90
- $rez = wp_update_link($data);
91
-
92
- if ( !empty($rez) ){
93
- return true;
94
- } else {
95
- return new WP_Error(
96
- 'update_failed',
97
- sprintf(__('Updating bookmark %d failed', 'broken-link-checker'), $this->container_id)
98
- );
99
- }
100
- }
101
-
102
- /**
103
- * Delete the bookmark corresponding to this container.
104
- * Also removes the synch. record of the container and removes all associated instances.
105
- *
106
- * @return bool|WP_error
107
- */
108
- function delete_wrapped_object(){
109
- if ( wp_delete_link($this->container_id) ){
110
- //Note that there is no need to explicitly delete the synch. record and instances
111
- //associated with this link - wp_delete_link() will execute the 'delete_link' action,
112
- //which will be noticed by blcBookmarkManager, which will then delete anything that needs
113
- //to be deleted.
114
-
115
- //But in case the (undocumented) behaviour of wp_delete_link() changes in a later WP version,
116
- //add a call to $this->delete() here.
117
- return true;
118
- } else {
119
- $bookmark = $this->get_wrapped_object();
120
-
121
- if ( is_null($bookmark) ){
122
- $link_name = "[nonexistent]";
123
- } else {
124
- $link_name = sanitize_bookmark_field('link_name', $bookmark->link_name, $this->container_id, 'display');
125
- }
126
-
127
- $msg = sprintf(
128
- __('Failed to delete blogroll link "%s" (%d)', 'broken-link-checker'),
129
- $link_name,
130
- $this->container_id
131
- );
132
-
133
- return new WP_Error( 'delete_failed', $msg );
134
- }
135
- }
136
-
137
- function current_user_can_delete(){
138
- return current_user_can('manage_links');
139
- }
140
-
141
- function can_be_trashed(){
142
- return false;
143
- }
144
-
145
- /**
146
- * Get the default link text. For bookmarks, this is the bookmark name.
147
- *
148
- * @param string $field
149
- * @return string
150
- */
151
- function default_link_text($field = ''){
152
- $bookmark = $this->get_wrapped_object();
153
- return sanitize_bookmark_field('link_name', $bookmark->link_name, $this->container_id, 'display');
154
- }
155
-
156
- /**
157
- * For bookmarks, calling unlink() simply removes the bookmark.
158
- *
159
- * @return bool|WP_Error True on success, or an error object if something went wrong.
160
- */
161
- function unlink($field_name, $parser, $url, $raw_url =''){
162
- return $this->delete_wrapped_object();
163
- }
164
-
165
- }
166
-
167
- class blcBookmarkManager extends blcContainerManager{
168
- var $container_class_name = 'blcBookmark';
169
- var $fields = array('link_url' => 'url_field');
170
-
171
- /**
172
- * Set up hooks that monitor added/modified/deleted bookmarks.
173
- *
174
- * @return void
175
- */
176
- function init(){
177
- parent::init();
178
-
179
- add_action('add_link', array($this,'hook_add_link'));
180
- add_action('edit_link', array($this,'hook_edit_link'));
181
- add_action('delete_link', array($this,'hook_delete_link'));
182
- }
183
-
184
- /**
185
- * Instantiate multiple containers of the container type managed by this class.
186
- *
187
- * @param array $containers Array of assoc. arrays containing container data.
188
- * @param string $purpose An optional code indicating how the retrieved containers will be used.
189
- * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
190
- *
191
- * @return array of blcBookmark indexed by "container_type|container_id"
192
- */
193
- function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
194
- $containers = $this->make_containers($containers);
195
-
196
- //Preload bookmark data if it is likely to be useful later
197
- $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_PARSING));
198
- if ( $preload ){
199
- $bookmark_ids = array();
200
- foreach($containers as $container){
201
- $bookmark_ids[] = $container->container_id;
202
- }
203
-
204
- $args = array('include' => implode(',', $bookmark_ids));
205
- $bookmarks = get_bookmarks($args);
206
-
207
- foreach($bookmarks as $bookmark){
208
- $key = $this->container_type . '|' . $bookmark->link_id;
209
- if ( isset($containers[$key]) ){
210
- $containers[$key]->wrapped_object = $bookmark;
211
- }
212
- }
213
- }
214
-
215
- return $containers;
216
- }
217
-
218
- /**
219
- * Create or update synchronization records for all posts.
220
- *
221
- * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
222
- * @return void
223
- */
224
- function resynch($forced = false){
225
- global $wpdb; /** @var wpdb $wpdb */
226
-
227
- if ( !$forced ){
228
- //Usually the number of bookmarks is rather small, so it's cheap enough to always
229
- //drop the entire list of bookmark-related synch records and recreate it from scratch.
230
- $q = $wpdb->prepare(
231
- "DELETE FROM {$wpdb->prefix}blc_synch WHERE container_type = %s",
232
- $this->container_type
233
- );
234
- $wpdb->query( $q );
235
- }
236
-
237
- //Create new synchronization records for all bookmarks (AKA the blogroll).
238
- $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
239
- SELECT link_id, %s, 0
240
- FROM {$wpdb->links}
241
- WHERE 1";
242
- $q = $wpdb->prepare($q, $this->container_type);
243
- $wpdb->query( $q );
244
- }
245
-
246
- /**
247
- * When a bookmark is added mark it as unsynched.
248
- *
249
- * @param int $link_id
250
- * @return void
251
- */
252
- function hook_add_link( $link_id ){
253
- $container = blcContainerHelper::get_container( array($this->container_type, $link_id) );
254
- $container->mark_as_unsynched();
255
- }
256
-
257
- /**
258
- * Ditto for modified bookmarks.
259
- *
260
- * @param int $link_id
261
- * @return void
262
- */
263
- function hook_edit_link( $link_id ){
264
- $this->hook_add_link( $link_id );
265
- }
266
-
267
- /**
268
- * When a bookmark is deleted, remove the related DB records.
269
- *
270
- * @param int $link_id
271
- * @return void
272
- */
273
- function hook_delete_link( $link_id ){
274
- //Get the container object.
275
- $container = blcContainerHelper::get_container( array($this->container_type, $link_id) );
276
- //Get the link(s) associated with it.
277
- $links = $container->get_links();
278
-
279
- //Remove synch. record & instance records.
280
- $container->delete();
281
-
282
- //Clean up links associated with this bookmark (there's probably only one)
283
- $link_ids = array();
284
- foreach($links as $link){
285
- $link_ids[] = $link->link_id;
286
- }
287
- blc_cleanup_links($link_ids);
288
- }
289
-
290
- /**
291
- * Get the message to display after $n bookmarks have been deleted.
292
- *
293
- * @param int $n Number of deleted bookmarks.
294
- * @return string The delete confirmation message.
295
- */
296
- function ui_bulk_delete_message($n){
297
- return sprintf(
298
- _n(
299
- "%d blogroll link deleted.",
300
- "%d blogroll links deleted.",
301
- $n,
302
- 'broken-link-checker'
303
- ),
304
- $n
305
- );
306
- }
307
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: Blogroll items
4
+ Description:
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleID: blogroll
9
+ ModuleCategory: container
10
+ ModuleClassName: blcBookmarkManager
11
+ */
12
+
13
+ class blcBookmark extends blcContainer{
14
+
15
+ function ui_get_source($container_field = '', $context = 'display'){
16
+ $bookmark = $this->get_wrapped_object();
17
+
18
+ $image = sprintf(
19
+ '<img src="%1$s" class="blc-small-image" title="%2$s" alt="%2$s">',
20
+ esc_attr( plugins_url('/images/font-awesome/font-awesome-link.png', BLC_PLUGIN_FILE) ),
21
+ __('Bookmark', 'broken-link-checker')
22
+ );
23
+
24
+ $link_name = sprintf(
25
+ '<a class="row-title" href="%s" title="%s">%s</a>',
26
+ $this->get_edit_url(),
27
+ __('Edit this bookmark', 'broken-link-checker'),
28
+ sanitize_bookmark_field('link_name', $bookmark->link_name, $this->container_id, 'display')
29
+ );
30
+
31
+ if ( $context != 'email' ){
32
+ return "$image $link_name";
33
+ } else {
34
+ return $link_name;
35
+ }
36
+ }
37
+
38
+ function ui_get_action_links($container_field){
39
+ //Inline action links for bookmarks
40
+ $bookmark = $this->get_wrapped_object();
41
+
42
+ $delete_url = admin_url( wp_nonce_url("link.php?action=delete&link_id={$this->container_id}", 'delete-bookmark_' . $this->container_id) );
43
+
44
+ $actions = array();
45
+ if ( current_user_can('manage_links') ) {
46
+ $actions['edit'] = '<span class="edit"><a href="' . $this->get_edit_url() . '" title="' . esc_attr(__('Edit this bookmark', 'broken-link-checker')) . '">' . __('Edit') . '</a>';
47
+ $actions['delete'] = "<span class='delete'><a class='submitdelete' href='" . esc_url($delete_url) . "' onclick=\"if ( confirm('" . esc_js(sprintf( __("You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete."), $bookmark->link_name)) . "') ) { return true;}return false;\">" . __('Delete') . "</a>";
48
+ }
49
+
50
+ return $actions;
51
+ }
52
+
53
+ function get_edit_url(){
54
+ return esc_url(admin_url("link.php?action=edit&link_id={$this->container_id}"));
55
+ }
56
+
57
+ /**
58
+ * Retrieve the bookmark associated with this container.
59
+ *
60
+ * @access protected
61
+ *
62
+ * @param bool $ensure_consistency Set this to true to ignore the cached $wrapped_object value and retrieve an up-to-date copy of the wrapped object from the DB (or WP's internal cache).
63
+ * @return object Bookmark data.
64
+ */
65
+ function get_wrapped_object($ensure_consistency = false){
66
+ if( $ensure_consistency || is_null($this->wrapped_object) ){
67
+ $this->wrapped_object = get_bookmark($this->container_id);
68
+ }
69
+ return $this->wrapped_object;
70
+ }
71
+
72
+ /**
73
+ * Update the bookmark associated with this container.
74
+ *
75
+ * @access protected
76
+ *
77
+ * @return bool|WP_Error True on success, an error if something went wrong.
78
+ */
79
+ function update_wrapped_object(){
80
+ if ( is_null($this->wrapped_object) ){
81
+ return new WP_Error(
82
+ 'no_wrapped_object',
83
+ __('Nothing to update', 'broken-link-checker')
84
+ );
85
+ }
86
+
87
+ //wp_update_link() expects it's argument to be an array.
88
+ $data = (array)$this->wrapped_object;
89
+ //Update the bookmark
90
+ $rez = wp_update_link($data);
91
+
92
+ if ( !empty($rez) ){
93
+ return true;
94
+ } else {
95
+ return new WP_Error(
96
+ 'update_failed',
97
+ sprintf(__('Updating bookmark %d failed', 'broken-link-checker'), $this->container_id)
98
+ );
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Delete the bookmark corresponding to this container.
104
+ * Also removes the synch. record of the container and removes all associated instances.
105
+ *
106
+ * @return bool|WP_error
107
+ */
108
+ function delete_wrapped_object(){
109
+ if ( wp_delete_link($this->container_id) ){
110
+ //Note that there is no need to explicitly delete the synch. record and instances
111
+ //associated with this link - wp_delete_link() will execute the 'delete_link' action,
112
+ //which will be noticed by blcBookmarkManager, which will then delete anything that needs
113
+ //to be deleted.
114
+
115
+ //But in case the (undocumented) behaviour of wp_delete_link() changes in a later WP version,
116
+ //add a call to $this->delete() here.
117
+ return true;
118
+ } else {
119
+ $bookmark = $this->get_wrapped_object();
120
+
121
+ if ( is_null($bookmark) ){
122
+ $link_name = "[nonexistent]";
123
+ } else {
124
+ $link_name = sanitize_bookmark_field('link_name', $bookmark->link_name, $this->container_id, 'display');
125
+ }
126
+
127
+ $msg = sprintf(
128
+ __('Failed to delete blogroll link "%s" (%d)', 'broken-link-checker'),
129
+ $link_name,
130
+ $this->container_id
131
+ );
132
+
133
+ return new WP_Error( 'delete_failed', $msg );
134
+ }
135
+ }
136
+
137
+ function current_user_can_delete(){
138
+ return current_user_can('manage_links');
139
+ }
140
+
141
+ function can_be_trashed(){
142
+ return false;
143
+ }
144
+
145
+ /**
146
+ * Get the default link text. For bookmarks, this is the bookmark name.
147
+ *
148
+ * @param string $field
149
+ * @return string
150
+ */
151
+ function default_link_text($field = ''){
152
+ $bookmark = $this->get_wrapped_object();
153
+ return sanitize_bookmark_field('link_name', $bookmark->link_name, $this->container_id, 'display');
154
+ }
155
+
156
+ /**
157
+ * For bookmarks, calling unlink() simply removes the bookmark.
158
+ *
159
+ * @return bool|WP_Error True on success, or an error object if something went wrong.
160
+ */
161
+ function unlink($field_name, $parser, $url, $raw_url =''){
162
+ return $this->delete_wrapped_object();
163
+ }
164
+
165
+ }
166
+
167
+ class blcBookmarkManager extends blcContainerManager{
168
+ var $container_class_name = 'blcBookmark';
169
+ var $fields = array('link_url' => 'url_field');
170
+
171
+ /**
172
+ * Set up hooks that monitor added/modified/deleted bookmarks.
173
+ *
174
+ * @return void
175
+ */
176
+ function init(){
177
+ parent::init();
178
+
179
+ add_action('add_link', array($this,'hook_add_link'));
180
+ add_action('edit_link', array($this,'hook_edit_link'));
181
+ add_action('delete_link', array($this,'hook_delete_link'));
182
+ }
183
+
184
+ /**
185
+ * Instantiate multiple containers of the container type managed by this class.
186
+ *
187
+ * @param array $containers Array of assoc. arrays containing container data.
188
+ * @param string $purpose An optional code indicating how the retrieved containers will be used.
189
+ * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
190
+ *
191
+ * @return array of blcBookmark indexed by "container_type|container_id"
192
+ */
193
+ function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
194
+ $containers = $this->make_containers($containers);
195
+
196
+ //Preload bookmark data if it is likely to be useful later
197
+ $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_PARSING));
198
+ if ( $preload ){
199
+ $bookmark_ids = array();
200
+ foreach($containers as $container){
201
+ $bookmark_ids[] = $container->container_id;
202
+ }
203
+
204
+ $args = array('include' => implode(',', $bookmark_ids));
205
+ $bookmarks = get_bookmarks($args);
206
+
207
+ foreach($bookmarks as $bookmark){
208
+ $key = $this->container_type . '|' . $bookmark->link_id;
209
+ if ( isset($containers[$key]) ){
210
+ $containers[$key]->wrapped_object = $bookmark;
211
+ }
212
+ }
213
+ }
214
+
215
+ return $containers;
216
+ }
217
+
218
+ /**
219
+ * Create or update synchronization records for all posts.
220
+ *
221
+ * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
222
+ * @return void
223
+ */
224
+ function resynch($forced = false){
225
+ global $wpdb; /** @var wpdb $wpdb */
226
+
227
+ if ( !$forced ){
228
+ //Usually the number of bookmarks is rather small, so it's cheap enough to always
229
+ //drop the entire list of bookmark-related synch records and recreate it from scratch.
230
+ $q = $wpdb->prepare(
231
+ "DELETE FROM {$wpdb->prefix}blc_synch WHERE container_type = %s",
232
+ $this->container_type
233
+ );
234
+ $wpdb->query( $q );
235
+ }
236
+
237
+ //Create new synchronization records for all bookmarks (AKA the blogroll).
238
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
239
+ SELECT link_id, %s, 0
240
+ FROM {$wpdb->links}
241
+ WHERE 1";
242
+ $q = $wpdb->prepare($q, $this->container_type);
243
+ $wpdb->query( $q );
244
+ }
245
+
246
+ /**
247
+ * When a bookmark is added mark it as unsynched.
248
+ *
249
+ * @param int $link_id
250
+ * @return void
251
+ */
252
+ function hook_add_link( $link_id ){
253
+ $container = blcContainerHelper::get_container( array($this->container_type, $link_id) );
254
+ $container->mark_as_unsynched();
255
+ }
256
+
257
+ /**
258
+ * Ditto for modified bookmarks.
259
+ *
260
+ * @param int $link_id
261
+ * @return void
262
+ */
263
+ function hook_edit_link( $link_id ){
264
+ $this->hook_add_link( $link_id );
265
+ }
266
+
267
+ /**
268
+ * When a bookmark is deleted, remove the related DB records.
269
+ *
270
+ * @param int $link_id
271
+ * @return void
272
+ */
273
+ function hook_delete_link( $link_id ){
274
+ //Get the container object.
275
+ $container = blcContainerHelper::get_container( array($this->container_type, $link_id) );
276
+ //Get the link(s) associated with it.
277
+ $links = $container->get_links();
278
+
279
+ //Remove synch. record & instance records.
280
+ $container->delete();
281
+
282
+ //Clean up links associated with this bookmark (there's probably only one)
283
+ $link_ids = array();
284
+ foreach($links as $link){
285
+ $link_ids[] = $link->link_id;
286
+ }
287
+ blc_cleanup_links($link_ids);
288
+ }
289
+
290
+ /**
291
+ * Get the message to display after $n bookmarks have been deleted.
292
+ *
293
+ * @param int $n Number of deleted bookmarks.
294
+ * @return string The delete confirmation message.
295
+ */
296
+ function ui_bulk_delete_message($n){
297
+ return sprintf(
298
+ _n(
299
+ "%d blogroll link deleted.",
300
+ "%d blogroll links deleted.",
301
+ $n,
302
+ 'broken-link-checker'
303
+ ),
304
+ $n
305
+ );
306
+ }
307
+ }
modules/containers/comment.php CHANGED
@@ -1,434 +1,434 @@
1
- <?php
2
-
3
- /*
4
- Plugin Name: Comments
5
- Description:
6
- Version: 1.0
7
- Author: Janis Elsts
8
-
9
- ModuleID: comment
10
- ModuleCategory: container
11
- ModuleClassName: blcCommentManager
12
- */
13
-
14
- class blcComment extends blcContainer{
15
-
16
- /**
17
- * Retrieve the comment wrapped by this container.
18
- * The fetched object will also be cached in the $wrapped_object variable.
19
- *
20
- * @access protected
21
- *
22
- * @param bool $ensure_consistency
23
- * @return object The comment.
24
- */
25
- function get_wrapped_object($ensure_consistency = false){
26
- if( $ensure_consistency || is_null($this->wrapped_object) ){
27
- $this->wrapped_object = get_comment($this->container_id);
28
- }
29
- return $this->wrapped_object;
30
- }
31
-
32
- /**
33
- * Update the comment wrapped by the container with values currently in the $wrapped_object.
34
- *
35
- * @access protected
36
- *
37
- * @return bool|WP_Error True on success, an error if something went wrong.
38
- */
39
- function update_wrapped_object(){
40
- if ( is_null($this->wrapped_object) ){
41
- return new WP_Error(
42
- 'no_wrapped_object',
43
- __('Nothing to update', 'broken-link-checker')
44
- );
45
- }
46
-
47
- $data = (array)$this->wrapped_object;
48
- if ( wp_update_comment($data) ){
49
- return true;
50
- } else {
51
- return new WP_Error(
52
- 'update_failed',
53
- sprintf(__('Updating comment %d failed', 'broken-link-checker'), $this->container_id)
54
- );
55
- }
56
- }
57
-
58
- /**
59
- * Delete the comment corresponding to this container.
60
- * This will actually move the comment to the trash in newer versions of WP.
61
- *
62
- * @return bool|WP_error
63
- */
64
- function delete_wrapped_object(){
65
- if ( EMPTY_TRASH_DAYS ){
66
- return $this->trash_wrapped_object();
67
- } else {
68
- if ( wp_delete_comment($this->container_id, true) ){
69
- return true;
70
- } else {
71
- return new WP_Error(
72
- 'delete_failed',
73
- sprintf(
74
- __('Failed to delete comment %d', 'broken-link-checker'),
75
- $this->container_id
76
- )
77
- );
78
- }
79
- }
80
- }
81
-
82
- /**
83
- * Delete the comment corresponding to this container.
84
- * This will actually move the comment to the trash in newer versions of WP.
85
- *
86
- * @return bool|WP_error
87
- */
88
- function trash_wrapped_object(){
89
- if ( wp_trash_comment($this->container_id) ){
90
- return true;
91
- } else {
92
- return new WP_Error(
93
- 'trash_failed',
94
- sprintf(
95
- __('Can\'t move comment %d to the trash', 'broken-link-checker'),
96
- $this->container_id
97
- )
98
- );
99
- }
100
- }
101
-
102
- /**
103
- * Check if the current user can delete/trash this comment.
104
- *
105
- * @return bool
106
- */
107
- function current_user_can_delete(){
108
- //TODO: Fix for custom post types? WP itself doesn't care, at least in 3.0.
109
- $comment = $this->get_wrapped_object();
110
- return current_user_can('edit_post', $comment->comment_post_ID);
111
- }
112
-
113
- function can_be_trashed(){
114
- return defined('EMPTY_TRASH_DAYS') && EMPTY_TRASH_DAYS;
115
- }
116
-
117
- /**
118
- * Get the default link text to use for links found in a specific container field.
119
- * For links in the comment body there is no default link text. For author links,
120
- * the link text will be equal to the author name + comment type (if any).
121
- *
122
- * @param string $field
123
- * @return string
124
- */
125
- function default_link_text($field = ''){
126
-
127
- if ( $field == 'comment_author_url' ){
128
- $w = $this->get_wrapped_object();
129
- if ( !is_null($w) ){
130
- $text = $w->comment_author;
131
-
132
- //This lets us identify pingbacks & trackbacks.
133
- if ( !empty($w->comment_type) ){
134
- $text .= sprintf(' [%s]', $w->comment_type);
135
- }
136
-
137
- return $text;
138
- }
139
- }
140
-
141
- return '';
142
- }
143
-
144
- function ui_get_action_links($container_field){
145
- $actions = array();
146
-
147
- $comment = $this->get_wrapped_object();
148
- $post = get_post($comment->comment_post_ID); /* @var StdClass $post */
149
-
150
- //If the post type no longer exists, we can't really do anything with this comment.
151
- //WordPress will just throw errors if we try.
152
- if ( !post_type_exists(get_post_type($post)) ) {
153
- return $actions;
154
- }
155
-
156
- //Display Edit & Delete/Trash links only if the user has the right caps.
157
- $user_can = current_user_can('edit_post', $comment->comment_post_ID);
158
- if ( $user_can ){
159
- $actions['edit'] = "<a href='". $this->get_edit_url() ."' title='" . esc_attr__('Edit comment') . "'>". __('Edit') . '</a>';
160
-
161
- $del_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "delete-comment_$comment->comment_ID" ) );
162
- $trash_url = esc_url( admin_url("comment.php?action=trashcomment&p=$post->ID&c=$comment->comment_ID&$del_nonce") );
163
- $delete_url = esc_url( admin_url("comment.php?action=deletecomment&p=$post->ID&c=$comment->comment_ID&$del_nonce") );
164
-
165
- if ( !constant('EMPTY_TRASH_DAYS') ) {
166
- $actions['delete'] = "<a href='$delete_url' class='delete:the-comment-list:comment-$comment->comment_ID::delete=1 delete vim-d vim-destructive submitdelete'>" . __('Delete Permanently') . '</a>';
167
- } else {
168
- $actions['trash'] = "<a href='$trash_url' class='delete:the-comment-list:comment-$comment->comment_ID::trash=1 delete vim-d vim-destructive submitdelete' title='" . esc_attr__( 'Move this comment to the trash' ) . "'>" . _x('Trash', 'verb') . '</a>';
169
- }
170
- }
171
-
172
- $actions['view'] = '<span class="view"><a href="' . get_comment_link($this->container_id) . '" title="' . esc_attr(__('View comment', 'broken-link-checker')) . '" rel="permalink">' . __('View') . '</a>';
173
-
174
- return $actions;
175
- }
176
-
177
- function ui_get_source($container_field = '', $context = 'display'){
178
- //Display a comment icon.
179
- if ( $container_field == 'comment_author_url' ){
180
- $image = 'font-awesome/font-awesome-user.png';
181
- } else {
182
- $image = 'font-awesome/font-awesome-comment-alt.png';
183
- }
184
-
185
- $image = sprintf(
186
- '<img src="%s/broken-link-checker/images/%s" class="blc-small-image" title="%3$s" alt="%3$s"> ',
187
- WP_PLUGIN_URL,
188
- $image,
189
- __('Comment', 'broken-link-checker')
190
- );
191
-
192
- $comment = $this->get_wrapped_object();
193
-
194
- //Display a small text sample from the comment
195
- $text_sample = strip_tags($comment->comment_content);
196
- $text_sample = blcUtility::truncate($text_sample, 65);
197
-
198
- $html = sprintf(
199
- '<a href="%s" title="%s"><b>%s</b> &mdash; %s</a>',
200
- $this->get_edit_url(),
201
- esc_attr__('Edit comment'),
202
- esc_attr($comment->comment_author),
203
- $text_sample
204
- );
205
-
206
- //Don't show the image in email notifications.
207
- if ( $context != 'email' ){
208
- $html = $image . $html;
209
- }
210
-
211
- return $html;
212
- }
213
-
214
- function get_edit_url(){
215
- return esc_url(admin_url("comment.php?action=editcomment&c={$this->container_id}"));
216
- }
217
-
218
- function base_url(){
219
- $comment_permalink = get_comment_link($this->container_id);
220
- return substr($comment_permalink, 0, strpos($comment_permalink, '#'));
221
- }
222
- }
223
-
224
- class blcCommentManager extends blcContainerManager {
225
- var $container_class_name = 'blcComment';
226
-
227
- var $fields = array(
228
- 'comment_author_url' => 'url_field',
229
- 'comment_content' => 'html',
230
- );
231
-
232
- function init(){
233
- parent::init();
234
-
235
- add_action('post_comment', array($this, 'hook_post_comment'), 10, 2);
236
- add_action('edit_comment', array($this, 'hook_edit_comment'));
237
- add_action('transition_comment_status', array($this, 'hook_comment_status'), 10, 3);
238
-
239
- add_action('trashed_post_comments', array($this, 'hook_trashed_post_comments'), 10, 2);
240
- add_action('untrash_post_comments', array($this, 'hook_untrash_post_comments'));
241
- }
242
-
243
- function hook_post_comment($comment_id, $comment_status){
244
- if ( $comment_status == '1' ) {
245
- $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
246
- $container->mark_as_unsynched();
247
- }
248
- }
249
-
250
- function hook_edit_comment($comment_id){
251
- if ( wp_get_comment_status($comment_id) == 'approved' ){
252
- $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
253
- $container->mark_as_unsynched();
254
- }
255
- }
256
-
257
- function hook_comment_status($new_status, $old_status, $comment){
258
- //We only care about approved comments.
259
- if ( ($new_status == 'approved') || ($old_status == 'approved') ){
260
- $container = blcContainerHelper::get_container(array($this->container_type, $comment->comment_ID));
261
- if ($new_status == 'approved') {
262
- $container->mark_as_unsynched();
263
- } else {
264
- $container->delete();
265
- blc_cleanup_links();
266
- }
267
- }
268
- }
269
-
270
- function hook_trashed_post_comments(/** @noinspection PhpUnusedParameterInspection */$post_id, $statuses){
271
- foreach($statuses as $comment_id => $comment_status){
272
- if ( $comment_status == '1' ){
273
- $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
274
- $container->delete();
275
- }
276
- }
277
- blc_cleanup_links();
278
- }
279
-
280
- function hook_untrash_post_comments($post_id){
281
- //Unlike with the 'trashed_post_comments' hook, WP doesn't pass the list of (un)trashed
282
- //comments to callbacks assigned to the 'untrash_post_comments' and 'untrashed_post_comments'
283
- //actions. Therefore, we must read it from the appropriate metadata entry.
284
- $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
285
- if ( empty($statuses) || !is_array($statuses) ) return;
286
-
287
- foreach ( $statuses as $comment_id => $comment_status ){
288
- if ( $comment_status == '1' ){ //if approved
289
- $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
290
- $container->mark_as_unsynched();
291
- }
292
- }
293
- }
294
-
295
- /**
296
- * Create or update synchronization records for all comments.
297
- *
298
- * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
299
- * @return void
300
- */
301
- function resynch($forced = false){
302
- global $wpdb; /* @var wpdb $wpdb */
303
- global $blclog;
304
-
305
- if ( $forced ){
306
- //Create new synchronization records for all comments.
307
- $blclog->log('...... Creating synch. records for comments');
308
- $start = microtime(true);
309
- $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
310
- SELECT comment_ID, '{$this->container_type}', 0
311
- FROM {$wpdb->comments}
312
- WHERE
313
- {$wpdb->comments}.comment_approved = '1'";
314
- $wpdb->query( $q );
315
- $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
316
- } else {
317
- //Delete synch records corresponding to comments that no longer exist
318
- //or have been trashed/spammed/unapproved.
319
- $blclog->log('...... Deleting synch. records for removed comments');
320
- $start = microtime(true);
321
- $q = "DELETE synch.*
322
- FROM
323
- {$wpdb->prefix}blc_synch AS synch LEFT JOIN {$wpdb->comments} AS comments
324
- ON comments.comment_ID = synch.container_id
325
- WHERE
326
- synch.container_type = '{$this->container_type}'
327
- AND (comments.comment_ID IS NULL OR comments.comment_approved <> '1')";
328
- $wpdb->query( $q );
329
- $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
330
-
331
- //Create synch. records for comments that don't have them.
332
- $blclog->log('...... Creating synch. records for new comments');
333
- $start = microtime(true);
334
- $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
335
- SELECT comment_ID, '{$this->container_type}', 0
336
- FROM
337
- {$wpdb->comments} AS comments LEFT JOIN {$wpdb->prefix}blc_synch AS synch
338
- ON (synch.container_id = comments.comment_ID and synch.container_type='{$this->container_type}')
339
- WHERE
340
- comments.comment_approved = '1'
341
- AND synch.container_id IS NULL";
342
- $wpdb->query($q);
343
- $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
344
-
345
- /*
346
- Note that there is no way to detect comments that were *edited* (not added - those
347
- will be caught by the above query) while the plugin was inactive. Unlike with posts,
348
- WP doesn't track comment modification times.
349
- */
350
- }
351
- }
352
-
353
- /**
354
- * Get the message to display after $n comments have been deleted.
355
- *
356
- * @param int $n Number of deleted comments.
357
- * @return string A delete confirmation message, e.g. "5 comments were deleted"
358
- */
359
- function ui_bulk_delete_message($n){
360
- if ( EMPTY_TRASH_DAYS ){
361
- return $this->ui_bulk_trash_message($n);
362
- } else {
363
- return sprintf(
364
- _n(
365
- "%d comment has been deleted.",
366
- "%d comments have been deleted.",
367
- $n,
368
- 'broken-link-checker'
369
- ),
370
- $n
371
- );
372
- }
373
- }
374
-
375
- /**
376
- * Get the message to display after $n comments have been moved to the trash.
377
- *
378
- * @param int $n Number of trashed comments.
379
- * @return string A delete confirmation message, e.g. "5 comments were moved to trash"
380
- */
381
- function ui_bulk_trash_message($n){
382
- return sprintf(
383
- _n(
384
- "%d comment moved to the Trash.",
385
- "%d comments moved to the Trash.",
386
- $n,
387
- 'broken-link-checker'
388
- ),
389
- $n
390
- );
391
- }
392
-
393
- /**
394
- * Instantiate multiple containers of the container type managed by this class.
395
- *
396
- * @param array $containers Array of assoc. arrays containing container data.
397
- * @param string $purpose An optional code indicating how the retrieved containers will be used.
398
- * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
399
- *
400
- * @return array of blcPostContainer indexed by "container_type|container_id"
401
- */
402
- function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
403
- global $wpdb; /* @var wpdb $wpdb */
404
-
405
- $containers = $this->make_containers($containers);
406
-
407
- //Preload comment data if it is likely to be useful later
408
- $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_PARSING));
409
- if ( $preload ){
410
- $comment_ids = array();
411
- foreach($containers as $container){ /* @var blcContainer $container */
412
- $comment_ids[] = $container->container_id;
413
- }
414
-
415
- //There's no WP function for retrieving multiple comments by their IDs,
416
- //so we query the DB directly.
417
- $q = "SELECT * FROM {$wpdb->comments} WHERE comment_ID IN (" . implode(', ', $comment_ids) . ")";
418
- $comments = $wpdb->get_results($q);
419
-
420
- foreach($comments as $comment){
421
- //Cache the comment in the internal WP object cache
422
- $comment = get_comment($comment); /* @var StdClass $comment */
423
-
424
- //Attach it to the container
425
- $key = $this->container_type . '|' . $comment->comment_ID;
426
- if ( isset($containers[$key]) ){
427
- $containers[$key]->wrapped_object = $comment;
428
- }
429
- }
430
- }
431
-
432
- return $containers;
433
- }
434
- }
1
+ <?php
2
+
3
+ /*
4
+ Plugin Name: Comments
5
+ Description:
6
+ Version: 1.0
7
+ Author: Janis Elsts
8
+
9
+ ModuleID: comment
10
+ ModuleCategory: container
11
+ ModuleClassName: blcCommentManager
12
+ */
13
+
14
+ class blcComment extends blcContainer{
15
+
16
+ /**
17
+ * Retrieve the comment wrapped by this container.
18
+ * The fetched object will also be cached in the $wrapped_object variable.
19
+ *
20
+ * @access protected
21
+ *
22
+ * @param bool $ensure_consistency
23
+ * @return object The comment.
24
+ */
25
+ function get_wrapped_object($ensure_consistency = false){
26
+ if( $ensure_consistency || is_null($this->wrapped_object) ){
27
+ $this->wrapped_object = get_comment($this->container_id);
28
+ }
29
+ return $this->wrapped_object;
30
+ }
31
+
32
+ /**
33
+ * Update the comment wrapped by the container with values currently in the $wrapped_object.
34
+ *
35
+ * @access protected
36
+ *
37
+ * @return bool|WP_Error True on success, an error if something went wrong.
38
+ */
39
+ function update_wrapped_object(){
40
+ if ( is_null($this->wrapped_object) ){
41
+ return new WP_Error(
42
+ 'no_wrapped_object',
43
+ __('Nothing to update', 'broken-link-checker')
44
+ );
45
+ }
46
+
47
+ $data = (array)$this->wrapped_object;
48
+ if ( wp_update_comment($data) ){
49
+ return true;
50
+ } else {
51
+ return new WP_Error(
52
+ 'update_failed',
53
+ sprintf(__('Updating comment %d failed', 'broken-link-checker'), $this->container_id)
54
+ );
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Delete the comment corresponding to this container.
60
+ * This will actually move the comment to the trash in newer versions of WP.
61
+ *
62
+ * @return bool|WP_error
63
+ */
64
+ function delete_wrapped_object(){
65
+ if ( EMPTY_TRASH_DAYS ){
66
+ return $this->trash_wrapped_object();
67
+ } else {
68
+ if ( wp_delete_comment($this->container_id, true) ){
69
+ return true;
70
+ } else {
71
+ return new WP_Error(
72
+ 'delete_failed',
73
+ sprintf(
74
+ __('Failed to delete comment %d', 'broken-link-checker'),
75
+ $this->container_id
76
+ )
77
+ );
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Delete the comment corresponding to this container.
84
+ * This will actually move the comment to the trash in newer versions of WP.
85
+ *
86
+ * @return bool|WP_error
87
+ */
88
+ function trash_wrapped_object(){
89
+ if ( wp_trash_comment($this->container_id) ){
90
+ return true;
91
+ } else {
92
+ return new WP_Error(
93
+ 'trash_failed',
94
+ sprintf(
95
+ __('Can\'t move comment %d to the trash', 'broken-link-checker'),
96
+ $this->container_id
97
+ )
98
+ );
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Check if the current user can delete/trash this comment.
104
+ *
105
+ * @return bool
106
+ */
107
+ function current_user_can_delete(){
108
+ //TODO: Fix for custom post types? WP itself doesn't care, at least in 3.0.
109
+ $comment = $this->get_wrapped_object();
110
+ return current_user_can('edit_post', $comment->comment_post_ID);
111
+ }
112
+
113
+ function can_be_trashed(){
114
+ return defined('EMPTY_TRASH_DAYS') && EMPTY_TRASH_DAYS;
115
+ }
116
+
117
+ /**
118
+ * Get the default link text to use for links found in a specific container field.
119
+ * For links in the comment body there is no default link text. For author links,
120
+ * the link text will be equal to the author name + comment type (if any).
121
+ *
122
+ * @param string $field
123
+ * @return string
124
+ */
125
+ function default_link_text($field = ''){
126
+
127
+ if ( $field == 'comment_author_url' ){
128
+ $w = $this->get_wrapped_object();
129
+ if ( !is_null($w) ){
130
+ $text = $w->comment_author;
131
+
132
+ //This lets us identify pingbacks & trackbacks.
133
+ if ( !empty($w->comment_type) ){
134
+ $text .= sprintf(' [%s]', $w->comment_type);
135
+ }
136
+
137
+ return $text;
138
+ }
139
+ }
140
+
141
+ return '';
142
+ }
143
+
144
+ function ui_get_action_links($container_field){
145
+ $actions = array();
146
+
147
+ $comment = $this->get_wrapped_object();
148
+ $post = get_post($comment->comment_post_ID); /* @var StdClass $post */
149
+
150
+ //If the post type no longer exists, we can't really do anything with this comment.
151
+ //WordPress will just throw errors if we try.
152
+ if ( !post_type_exists(get_post_type($post)) ) {
153
+ return $actions;
154
+ }
155
+
156
+ //Display Edit & Delete/Trash links only if the user has the right caps.
157
+ $user_can = current_user_can('edit_post', $comment->comment_post_ID);
158
+ if ( $user_can ){
159
+ $actions['edit'] = "<a href='". $this->get_edit_url() ."' title='" . esc_attr__('Edit comment') . "'>". __('Edit') . '</a>';
160
+
161
+ $del_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "delete-comment_$comment->comment_ID" ) );
162
+ $trash_url = esc_url( admin_url("comment.php?action=trashcomment&p=$post->ID&c=$comment->comment_ID&$del_nonce") );
163
+ $delete_url = esc_url( admin_url("comment.php?action=deletecomment&p=$post->ID&c=$comment->comment_ID&$del_nonce") );
164
+
165
+ if ( !constant('EMPTY_TRASH_DAYS') ) {
166
+ $actions['delete'] = "<a href='$delete_url' class='delete:the-comment-list:comment-$comment->comment_ID::delete=1 delete vim-d vim-destructive submitdelete'>" . __('Delete Permanently') . '</a>';
167
+ } else {
168
+ $actions['trash'] = "<a href='$trash_url' class='delete:the-comment-list:comment-$comment->comment_ID::trash=1 delete vim-d vim-destructive submitdelete' title='" . esc_attr__( 'Move this comment to the trash' ) . "'>" . _x('Trash', 'verb') . '</a>';
169
+ }
170
+ }
171
+
172
+ $actions['view'] = '<span class="view"><a href="' . get_comment_link($this->container_id) . '" title="' . esc_attr(__('View comment', 'broken-link-checker')) . '" rel="permalink">' . __('View') . '</a>';
173
+
174
+ return $actions;
175
+ }
176
+
177
+ function ui_get_source($container_field = '', $context = 'display'){
178
+ //Display a comment icon.
179
+ if ( $container_field == 'comment_author_url' ){
180
+ $image = 'font-awesome/font-awesome-user.png';
181
+ } else {
182
+ $image = 'font-awesome/font-awesome-comment-alt.png';
183
+ }
184
+
185
+ $image = sprintf(
186
+ '<img src="%s/broken-link-checker/images/%s" class="blc-small-image" title="%3$s" alt="%3$s"> ',
187
+ WP_PLUGIN_URL,
188
+ $image,
189
+ __('Comment', 'broken-link-checker')
190
+ );
191
+
192
+ $comment = $this->get_wrapped_object();
193
+
194
+ //Display a small text sample from the comment
195
+ $text_sample = strip_tags($comment->comment_content);
196
+ $text_sample = blcUtility::truncate($text_sample, 65);
197
+
198
+ $html = sprintf(
199
+ '<a href="%s" title="%s"><b>%s</b> &mdash; %s</a>',
200
+ $this->get_edit_url(),
201
+ esc_attr__('Edit comment'),
202
+ esc_attr($comment->comment_author),
203
+ $text_sample
204
+ );
205
+
206
+ //Don't show the image in email notifications.
207
+ if ( $context != 'email' ){
208
+ $html = $image . $html;
209
+ }
210
+
211
+ return $html;
212
+ }
213
+
214
+ function get_edit_url(){
215
+ return esc_url(admin_url("comment.php?action=editcomment&c={$this->container_id}"));
216
+ }
217
+
218
+ function base_url(){
219
+ $comment_permalink = get_comment_link($this->container_id);
220
+ return substr($comment_permalink, 0, strpos($comment_permalink, '#'));
221
+ }
222
+ }
223
+
224
+ class blcCommentManager extends blcContainerManager {
225
+ var $container_class_name = 'blcComment';
226
+
227
+ var $fields = array(
228
+ 'comment_author_url' => 'url_field',
229
+ 'comment_content' => 'html',
230
+ );
231
+
232
+ function init(){
233
+ parent::init();
234
+
235
+ add_action('post_comment', array($this, 'hook_post_comment'), 10, 2);
236
+ add_action('edit_comment', array($this, 'hook_edit_comment'));
237
+ add_action('transition_comment_status', array($this, 'hook_comment_status'), 10, 3);
238
+
239
+ add_action('trashed_post_comments', array($this, 'hook_trashed_post_comments'), 10, 2);
240
+ add_action('untrash_post_comments', array($this, 'hook_untrash_post_comments'));
241
+ }
242
+
243
+ function hook_post_comment($comment_id, $comment_status){
244
+ if ( $comment_status == '1' ) {
245
+ $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
246
+ $container->mark_as_unsynched();
247
+ }
248
+ }
249
+
250
+ function hook_edit_comment($comment_id){
251
+ if ( wp_get_comment_status($comment_id) == 'approved' ){
252
+ $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
253
+ $container->mark_as_unsynched();
254
+ }
255
+ }
256
+
257
+ function hook_comment_status($new_status, $old_status, $comment){
258
+ //We only care about approved comments.
259
+ if ( ($new_status == 'approved') || ($old_status == 'approved') ){
260
+ $container = blcContainerHelper::get_container(array($this->container_type, $comment->comment_ID));
261
+ if ($new_status == 'approved') {
262
+ $container->mark_as_unsynched();
263
+ } else {
264
+ $container->delete();
265
+ blc_cleanup_links();
266
+ }
267
+ }
268
+ }
269
+
270
+ function hook_trashed_post_comments(/** @noinspection PhpUnusedParameterInspection */$post_id, $statuses){
271
+ foreach($statuses as $comment_id => $comment_status){
272
+ if ( $comment_status == '1' ){
273
+ $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
274
+ $container->delete();
275
+ }
276
+ }
277
+ blc_cleanup_links();
278
+ }
279
+
280
+ function hook_untrash_post_comments($post_id){
281
+ //Unlike with the 'trashed_post_comments' hook, WP doesn't pass the list of (un)trashed
282
+ //comments to callbacks assigned to the 'untrash_post_comments' and 'untrashed_post_comments'
283
+ //actions. Therefore, we must read it from the appropriate metadata entry.
284
+ $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
285
+ if ( empty($statuses) || !is_array($statuses) ) return;
286
+
287
+ foreach ( $statuses as $comment_id => $comment_status ){
288
+ if ( $comment_status == '1' ){ //if approved
289
+ $container = blcContainerHelper::get_container(array($this->container_type, $comment_id));
290
+ $container->mark_as_unsynched();
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Create or update synchronization records for all comments.
297
+ *
298
+ * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
299
+ * @return void
300
+ */
301
+ function resynch($forced = false){
302
+ global $wpdb; /* @var wpdb $wpdb */
303
+ global $blclog;
304
+
305
+ if ( $forced ){
306
+ //Create new synchronization records for all comments.
307
+ $blclog->log('...... Creating synch. records for comments');
308
+ $start = microtime(true);
309
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
310
+ SELECT comment_ID, '{$this->container_type}', 0
311
+ FROM {$wpdb->comments}
312
+ WHERE
313
+ {$wpdb->comments}.comment_approved = '1'";
314
+ $wpdb->query( $q );
315
+ $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
316
+ } else {
317
+ //Delete synch records corresponding to comments that no longer exist
318
+ //or have been trashed/spammed/unapproved.
319
+ $blclog->log('...... Deleting synch. records for removed comments');
320
+ $start = microtime(true);
321
+ $q = "DELETE synch.*
322
+ FROM
323
+ {$wpdb->prefix}blc_synch AS synch LEFT JOIN {$wpdb->comments} AS comments
324
+ ON comments.comment_ID = synch.container_id
325
+ WHERE
326
+ synch.container_type = '{$this->container_type}'
327
+ AND (comments.comment_ID IS NULL OR comments.comment_approved <> '1')";
328
+ $wpdb->query( $q );
329
+ $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
330
+
331
+ //Create synch. records for comments that don't have them.
332
+ $blclog->log('...... Creating synch. records for new comments');
333
+ $start = microtime(true);
334
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
335
+ SELECT comment_ID, '{$this->container_type}', 0
336
+ FROM
337
+ {$wpdb->comments} AS comments LEFT JOIN {$wpdb->prefix}blc_synch AS synch
338
+ ON (synch.container_id = comments.comment_ID and synch.container_type='{$this->container_type}')
339
+ WHERE
340
+ comments.comment_approved = '1'
341
+ AND synch.container_id IS NULL";
342
+ $wpdb->query($q);
343
+ $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
344
+
345
+ /*
346
+ Note that there is no way to detect comments that were *edited* (not added - those
347
+ will be caught by the above query) while the plugin was inactive. Unlike with posts,
348
+ WP doesn't track comment modification times.
349
+ */
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Get the message to display after $n comments have been deleted.
355
+ *
356
+ * @param int $n Number of deleted comments.
357
+ * @return string A delete confirmation message, e.g. "5 comments were deleted"
358
+ */
359
+ function ui_bulk_delete_message($n){
360
+ if ( EMPTY_TRASH_DAYS ){
361
+ return $this->ui_bulk_trash_message($n);
362
+ } else {
363
+ return sprintf(
364
+ _n(
365
+ "%d comment has been deleted.",
366
+ "%d comments have been deleted.",
367
+ $n,
368
+ 'broken-link-checker'
369
+ ),
370
+ $n
371
+ );
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Get the message to display after $n comments have been moved to the trash.
377
+ *
378
+ * @param int $n Number of trashed comments.
379
+ * @return string A delete confirmation message, e.g. "5 comments were moved to trash"
380
+ */
381
+ function ui_bulk_trash_message($n){
382
+ return sprintf(
383
+ _n(
384
+ "%d comment moved to the Trash.",
385
+ "%d comments moved to the Trash.",
386
+ $n,
387
+ 'broken-link-checker'
388
+ ),
389
+ $n
390
+ );
391
+ }
392
+
393
+ /**
394
+ * Instantiate multiple containers of the container type managed by this class.
395
+ *
396
+ * @param array $containers Array of assoc. arrays containing container data.
397
+ * @param string $purpose An optional code indicating how the retrieved containers will be used.
398
+ * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
399
+ *
400
+ * @return array of blcPostContainer indexed by "container_type|container_id"
401
+ */
402
+ function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
403
+ global $wpdb; /* @var wpdb $wpdb */
404
+
405
+ $containers = $this->make_containers($containers);
406
+
407
+ //Preload comment data if it is likely to be useful later
408
+ $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY, BLC_FOR_PARSING));
409
+ if ( $preload ){
410
+ $comment_ids = array();
411
+ foreach($containers as $container){ /* @var blcContainer $container */
412
+ $comment_ids[] = $container->container_id;
413
+ }
414
+
415
+ //There's no WP function for retrieving multiple comments by their IDs,
416
+ //so we query the DB directly.
417
+ $q = "SELECT * FROM {$wpdb->comments} WHERE comment_ID IN (" . implode(', ', $comment_ids) . ")";
418
+ $comments = $wpdb->get_results($q);
419
+
420
+ foreach($comments as $comment){
421
+ //Cache the comment in the internal WP object cache
422
+ $comment = get_comment($comment); /* @var StdClass $comment */
423
+
424
+ //Attach it to the container
425
+ $key = $this->container_type . '|' . $comment->comment_ID;
426
+ if ( isset($containers[$key]) ){
427
+ $containers[$key]->wrapped_object = $comment;
428
+ }
429
+ }
430
+ }
431
+
432
+ return $containers;
433
+ }
434
+ }
modules/containers/custom_field.php CHANGED
@@ -1,637 +1,637 @@
1
- <?php
2
-
3
- /*
4
- Plugin Name: Custom fields
5
- Description: Container module for post metadata.
6
- Version: 1.0
7
- Author: Janis Elsts
8
-
9
- ModuleID: custom_field
10
- ModuleCategory: container
11
- ModuleClassName: blcPostMetaManager
12
- */
13
-
14
- //Note : If it ever becomes necessary to check metadata on objects other than posts, it will
15
- //be fairly easy to extract a more general metadata container class from blcPostMeta.
16
-
17
- /**
18
- * blcPostMeta - A link container class for post metadata (AKA custom fields).
19
- *
20
- * Due to the way metadata works, this container differs significantly from other containers :
21
- * - container_field is equal to meta name, and container_id holds the ID of the post.
22
- * - There is one synch. record per post that determines the synch. state of all metadata fields of that post.
23
- * - Unlinking simply deletes the meta entry in question without involving the parser.
24
- * - The list of parse-able $fields is not fixed. Instead, it's initialized based on the
25
- * custom field list defined in Settings -> Link Checker.
26
- * - The $wrapped_object is an array (and isn't really used for anything).
27
- * - update_wrapped_object() does nothing.
28
- *
29
- * @package Broken Link Checker
30
- * @access public
31
- */
32
- class blcPostMeta extends blcContainer {
33
-
34
- var $meta_type = 'post';
35
-
36
- /**
37
- * Retrieve all metadata fields of the post associated with this container.
38
- * The results are cached in the internal $wrapped_object variable.
39
- *
40
- * @param bool $ensure_consistency
41
- * @return object The wrapped object.
42
- */
43
- function get_wrapped_object($ensure_consistency = false){
44
- if ( is_null($this->wrapped_object) || $ensure_consistency ) {
45
- $this->wrapped_object = get_metadata($this->meta_type, $this->container_id);
46
- }
47
- return $this->wrapped_object;
48
- }
49
-
50
- function update_wrapped_object(){
51
- trigger_error('Function blcPostMeta::update_wrapped_object() does nothing and should not be used.', E_USER_WARNING);
52
- }
53
-
54
- /**
55
- * Get the value of the specified metadata field of the object wrapped by this container.
56
- *
57
- * @access protected
58
- *
59
- * @param string $field Field name. If omitted, the value of the default field will be returned.
60
- * @return array
61
- */
62
- function get_field($field = ''){
63
- $get_only_first_field = ($this->fields[$field] !== 'metadata');
64
- return get_metadata($this->meta_type, $this->container_id, $field, $get_only_first_field);
65
- }
66
-
67
- /**
68
- * Update the value of the specified metadata field of the object wrapped by this container.
69
- *
70
- * @access protected
71
- *
72
- * @param string $field Meta name.
73
- * @param string $new_value New meta value.
74
- * @param string $old_value old meta value.
75
- * @return bool|WP_Error True on success, an error object if something went wrong.
76
- */
77
- function update_field($field, $new_value, $old_value = ''){
78
- $rez = update_metadata($this->meta_type, $this->container_id, $field, $new_value, $old_value);
79
- if ( $rez ){
80
- return true;
81
- } else {
82
- return new WP_Error(
83
- 'metadata_update_failed',
84
- sprintf(
85
- __("Failed to update the meta field '%s' on %s [%d]", 'broken-link-checker'),
86
- $field,
87
- $this->meta_type,
88
- $this->container_id
89
- )
90
- );
91
- }
92
- }
93
-
94
- /**
95
- * "Unlink"-ing a custom fields removes all metadata fields that contain the specified URL.
96
- *
97
- * @param string $field_name
98
- * @param blcParser $parser
99
- * @param string $url
100
- * @param string $raw_url
101
- * @return bool|WP_Error True on success, or an error object if something went wrong.
102
- */
103
- function unlink($field_name, $parser, $url, $raw_url =''){
104
- if ( $this->fields[$field_name] !== 'metadata' ) {
105
- return parent::unlink($field_name, $parser, $url, $raw_url);
106
- }
107
-
108
- $rez = delete_metadata($this->meta_type, $this->container_id, $field_name, $raw_url);
109
- if ( $rez ){
110
- return true;
111
- } else {
112
- return new WP_Error(
113
- 'metadata_delete_failed',
114
- sprintf(
115
- __("Failed to delete the meta field '%s' on %s [%d]", 'broken-link-checker'),
116
- $field_name,
117
- $this->meta_type,
118
- $this->container_id
119
- )
120
- );
121
- }
122
- }
123
-
124
- /**
125
- * Change a meta field containing the specified URL to a new URL.
126
- *
127
- * @param string $field_name Meta name
128
- * @param blcParser $parser
129
- * @param string $new_url New URL.
130
- * @param string $old_url
131
- * @param string $old_raw_url Old meta value.
132
- * @param null $new_text
133
- * @return string|WP_Error The new value of raw_url on success, or an error object if something went wrong.
134
- */
135
- function edit_link($field_name, $parser, $new_url, $old_url = '', $old_raw_url = '', $new_text = null){
136
- /*
137
- FB::log(sprintf(
138
- 'Editing %s[%d]:%s - %s to %s',
139
- $this->container_type,
140
- $this->container_id,
141
- $field_name,
142
- $old_url,
143
- $new_url
144
- ));
145
- */
146
-
147
- if ( $this->fields[$field_name] !== 'metadata' ) {
148
- return parent::edit_link($field_name, $parser, $new_url, $old_url, $old_raw_url, $new_text);
149
- }
150
-
151
- if ( empty($old_raw_url) ){
152
- $old_raw_url = $old_url;
153
- }
154
-
155
- //Get the current values of the field that needs to be edited.
156
- //The default metadata parser ignores them, but we're still going
157
- //to set this argument to a valid value in case someone writes a
158
- //custom meta parser that needs it.
159
- $old_value = $this->get_field($field_name);
160
-
161
- //Get the new field value (a string).
162
- $edit_result = $parser->edit($old_value, $new_url, $old_url, $old_raw_url);
163
- if ( is_wp_error($edit_result) ){
164
- return $edit_result;
165
- }
166
-
167
- //Update the field with the new value returned by the parser.
168
- //Notice how $old_raw_url is used instead of $old_value. $old_raw_url contains the entire old
169
- //value of the metadata field (see blcMetadataParser::parse()) and thus can be used to
170
- //differentiate between multiple meta fields with identical names.
171
- $update_result = $this->update_field( $field_name, $edit_result['content'], $old_raw_url );
172
- if ( is_wp_error($update_result) ){
173
- return $update_result;
174
- }
175
-
176
- //Return the new "raw" URL.
177
- return $edit_result['raw_url'];
178
- }
179
-
180
- /**
181
- * Get the default link text to use for links found in a specific container field.
182
- *
183
- * @param string $field
184
- * @return string
185
- */
186
- function default_link_text($field = ''){
187
- //Just use the field name. There's no way to know how the links inside custom fields are
188
- //used, so no way to know the "real" link text. Displaying the field name at least gives
189
- //the user a clue where to look if they want to find/modify the field.
190
- return $field;
191
- }
192
-
193
- function ui_get_source($container_field = '', $context = 'display'){
194
- if ( !post_type_exists(get_post_type($this->container_id)) ) {
195
- //Error: Invalid post type. The user probably removed a CPT without removing the actual posts.
196
- $post_html = '';
197
-
198
- $post = get_post($this->container_id);
199
- if ( $post ) {
200
- $post_html .= sprintf(
201
- '<span class="row-title">%s</span><br>',
202
- get_the_title($post)
203
- );
204
- }
205
- $post_html .= sprintf(
206
- 'Invalid post type "%s"',
207
- htmlentities($this->container_type)
208
- );
209
-
210
- return $post_html;
211
- }
212
-
213
- $post_html = sprintf(
214
- '<a class="row-title" href="%s" title="%s">%s</a>',
215
- esc_url($this->get_edit_url()),
216
- esc_attr(__('Edit this post')),
217
- get_the_title($this->container_id)
218
- );
219
-
220
- return $post_html;
221
- }
222
-
223
- function ui_get_action_links($container_field){
224
- $actions = array();
225
- if ( !post_type_exists(get_post_type($this->container_id)) ) {
226
- return $actions;
227
- }
228
-
229
- if ( current_user_can('edit_post', $this->container_id) ) {
230
- $actions['edit'] = '<span class="edit"><a href="' . $this->get_edit_url() . '" title="' . esc_attr(__('Edit this item')) . '">' . __('Edit') . '</a>';
231
-
232
- if ( $this->current_user_can_delete() ){
233
- if ( $this->can_be_trashed() ) {
234
- $actions['trash'] = sprintf(
235
- "<span><a class='submitdelete' title='%s' href='%s'>%s</a>",
236
- esc_attr(__('Move this item to the Trash')),
237
- get_delete_post_link($this->container_id, '', false),
238
- __('Trash')
239
- );
240
- } else {
241
- $actions['delete'] = sprintf(
242
- "<span><a class='submitdelete' title='%s' href='%s'>%s</a>",
243
- esc_attr(__('Delete this item permanently')),
244
- get_delete_post_link($this->container_id, '', true),
245
- __('Delete')
246
- );
247
- }
248
- }
249
- }
250
- $actions['view'] = '<span class="view"><a href="' . esc_url(get_permalink($this->container_id)) . '" title="' . esc_attr(sprintf(__('View "%s"', 'broken-link-checker'), get_the_title($this->container_id))) . '" rel="permalink">' . __('View') . '</a>';
251
-
252
- return $actions;
253
- }
254
-
255
- /**
256
- * Get edit URL for this container. Returns the URL of the Dashboard page where the item
257
- * associated with this container can be edited.
258
- *
259
- * @access protected
260
- *
261
- * @return string
262
- */
263
- function get_edit_url(){
264
- /*
265
- The below is a near-exact copy of the get_post_edit_link() function.
266
- Unfortunately we can't just call that function because it has a hardcoded
267
- caps-check which fails when called from the email notification script
268
- executed by Cron.
269
- */
270
-
271
- if ( !($post = get_post( $this->container_id )) ){
272
- return '';
273
- }
274
-
275
- $context = 'display';
276
-
277
- //WP 3.0
278
- if ( 'display' == $context )
279
- $action = '&amp;action=edit';
280
- else
281
- $action = '&action=edit';
282
-
283
- $post_type_object = get_post_type_object( $post->post_type );
284
- if ( !$post_type_object ){
285
- return '';
286
- }
287
-
288
- return apply_filters( 'get_edit_post_link', admin_url( sprintf($post_type_object->_edit_link . $action, $post->ID) ), $post->ID, $context );
289
- }
290
-
291
- /**
292
- * Get the base URL of the container. For custom fields, the base URL is the permalink of
293
- * the post that the field is attached to.
294
- *
295
- * @return string
296
- */
297
- function base_url(){
298
- return get_permalink($this->container_id);
299
- }
300
-
301
- /**
302
- * Delete or trash the post corresponding to this container. If trash is enabled,
303
- * will always move the post to the trash instead of deleting.
304
- *
305
- * @return bool|WP_error
306
- */
307
- function delete_wrapped_object(){
308
- if ( EMPTY_TRASH_DAYS ){
309
- return $this->trash_wrapped_object();
310
- } else {
311
- if ( wp_delete_post($this->container_id) ){
312
- return true;
313
- } else {
314
- return new WP_Error(
315
- 'delete_failed',
316
- sprintf(
317
- __('Failed to delete post "%s" (%d)', 'broken-link-checker'),
318
- get_the_title($this->container_id),
319
- $this->container_id
320
- )
321
- );
322
- }
323
- }
324
- }
325
-
326
- /**
327
- * Move the post corresponding to this custom field to the Trash.
328
- *
329
- * @return bool|WP_Error
330
- */
331
- function trash_wrapped_object(){
332
- if ( !EMPTY_TRASH_DAYS ){
333
- return new WP_Error(
334
- 'trash_disabled',
335
- sprintf(
336
- __('Can\'t move post "%s" (%d) to the trash because the trash feature is disabled', 'broken-link-checker'),
337
- get_the_title($this->container_id),
338
- $this->container_id
339
- )
340
- );
341
- }
342
-
343
- $post = &get_post($this->container_id);
344
- if ( $post->post_status == 'trash' ){
345
- //Prevent conflicts between post and custom field containers trying to trash the same post.
346
- return true;
347
- }
348
-
349
- if ( wp_trash_post($this->container_id) ){
350
- return true;
351
- } else {
352
- return new WP_Error(
353
- 'trash_failed',
354
- sprintf(
355
- __('Failed to move post "%s" (%d) to the trash', 'broken-link-checker'),
356
- get_the_title($this->container_id),
357
- $this->container_id
358
- )
359
- );
360
- }
361
- }
362
-
363
- function current_user_can_delete(){
364
- $post = get_post($this->container_id);
365
- $post_type_object = get_post_type_object($post->post_type);
366
- return current_user_can( $post_type_object->cap->delete_post, $this->container_id );
367
- }
368
-
369
- function can_be_trashed(){
370
- return defined('EMPTY_TRASH_DAYS') && EMPTY_TRASH_DAYS;
371
- }
372
- }
373
-
374
- class blcPostMetaManager extends blcContainerManager {
375
- var $container_class_name = 'blcPostMeta';
376
- var $meta_type = 'post';
377
- protected $selected_fields = array();
378
-
379
- function init(){
380
- parent::init();
381
-
382
- //Figure out which custom fields we're interested in.
383
- if ( is_array($this->plugin_conf->options['custom_fields']) ){
384
- $prefix_formats = array(
385
- 'html' => 'html',
386
- 'url' => 'metadata',
387
- );
388
- foreach($this->plugin_conf->options['custom_fields'] as $meta_name){
389
- //The user can add an optional "format:" prefix to specify the format of the custom field.
390
- $parts = explode(':', $meta_name, 2);
391
- if ( (count($parts) == 2) && in_array($parts[0], $prefix_formats) ) {
392
- $this->selected_fields[$parts[1]] = $prefix_formats[$parts[0]];
393
- } else {
394
- $this->selected_fields[$meta_name] = 'metadata';
395
- }
396
- }
397
- }
398
-
399
- //Intercept 2.9+ style metadata modification actions
400
- add_action( "added_{$this->meta_type}_meta", array($this, 'meta_modified'), 10, 4 );
401
- add_action( "updated_{$this->meta_type}_meta", array($this, 'meta_modified'), 10, 4 );
402
- add_action( "deleted_{$this->meta_type}_meta", array($this, 'meta_modified'), 10, 4 );
403
-
404
- //When a post is deleted, also delete the custom field container associated with it.
405
- add_action('delete_post', array($this,'post_deleted'));
406
- add_action('trash_post', array($this,'post_deleted'));
407
-
408
- //Re-parse custom fields when a post is restored from trash
409
- add_action('untrashed_post', array($this,'post_untrashed'));
410
- }
411
-
412
-
413
- /**
414
- * Get a list of parseable fields.
415
- *
416
- * @return array
417
- */
418
- function get_parseable_fields(){
419
- return $this->selected_fields;
420
- }
421
-
422
- /**
423
- * Instantiate multiple containers of the container type managed by this class.
424
- *
425
- * @param array $containers Array of assoc. arrays containing container data.
426
- * @param string $purpose An optional code indicating how the retrieved containers will be used.
427
- * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
428
- *
429
- * @return array of blcPostMeta indexed by "container_type|container_id"
430
- */
431
- function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
432
- $containers = $this->make_containers($containers);
433
-
434
- /*
435
- When links from custom fields are displayed in Tools -> Broken Links,
436
- each one also shows the title of the post that the custom field(s)
437
- belong to. Thus it makes sense to pre-cache the posts beforehand - it's
438
- faster to load them all at once than to make a separate query for each
439
- one later.
440
-
441
- So make a list of involved post IDs and load them.
442
-
443
- Calling get_posts() will automatically populate the post cache, so we
444
- don't need to actually store the results anywhere in the container object().
445
- */
446
- $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY));
447
- if ( $preload ){
448
- $post_ids = array();
449
- foreach($containers as $container){
450
- $post_ids[] = $container->container_id;
451
- }
452
-
453
- $args = array('include' => implode(',', $post_ids));
454
- get_posts($args);
455
- }
456
-
457
- return $containers;
458
- }
459
-
460
- /**
461
- * Create or update synchronization records for all containers managed by this class.
462
- *
463
- * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
464
- * @return void
465
- */
466
- function resynch($forced = false){
467
- global $wpdb; /** @var wpdb $wpdb */
468
- global $blclog;
469
-
470
- //Only check custom fields on selected post types. By default, that's "post" and "page".
471
- $post_types = array('post', 'page');
472
- if ( class_exists('blcPostTypeOverlord') ) {
473
- $overlord = blcPostTypeOverlord::getInstance();
474
- $post_types = array_merge($post_types, $overlord->enabled_post_types);
475
- $post_types = array_unique($post_types);
476
- }
477
-
478
- $escaped_post_types = "'" . implode("', '", array_map('esc_sql', $post_types)) . "'";
479
-
480
- if ( $forced ){
481
- //Create new synchronization records for all posts.
482
- $blclog->log('...... Creating synch records for all custom fields on ' . $escaped_post_types);
483
- $start = microtime(true);
484
- $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
485
- SELECT id, '{$this->container_type}', 0
486
- FROM {$wpdb->posts}
487
- WHERE
488
- {$wpdb->posts}.post_status = 'publish'
489
- AND {$wpdb->posts}.post_type IN ({$escaped_post_types})";
490
- $wpdb->query( $q );
491
- $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
492
- } else {
493
- //Delete synch records corresponding to posts that no longer exist.
494
- $blclog->log('...... Deleting custom field synch records corresponding to deleted posts');
495
- $start = microtime(true);
496
- $q = "DELETE synch.*
497
- FROM
498
- {$wpdb->prefix}blc_synch AS synch LEFT JOIN {$wpdb->posts} AS posts
499
- ON posts.ID = synch.container_id
500
- WHERE
501
- synch.container_type = '{$this->container_type}' AND posts.ID IS NULL";
502
- $wpdb->query( $q );
503
- $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
504
-
505
- //Remove the 'synched' flag from all posts that have been updated
506
- //since the last time they were parsed/synchronized.
507
- $blclog->log('...... Marking custom fields on changed posts as unsynched');
508
- $start = microtime(true);
509
- $q = "UPDATE
510
- {$wpdb->prefix}blc_synch AS synch
511
- JOIN {$wpdb->posts} AS posts ON (synch.container_id = posts.ID and synch.container_type='{$this->container_type}')
512
- SET
513
- synched = 0
514
- WHERE
515
- synch.last_synch < posts.post_modified";
516
- $wpdb->query( $q );
517
- $blclog->log(sprintf('...... %d rows updated in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
518
-
519
- //Create synch. records for posts that don't have them.
520
- $blclog->log('...... Creating custom field synch records for new ' . $escaped_post_types);
521
- $start = microtime(true);
522
- $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
523
- SELECT id, '{$this->container_type}', 0
524
- FROM
525
- {$wpdb->posts} AS posts LEFT JOIN {$wpdb->prefix}blc_synch AS synch
526
- ON (synch.container_id = posts.ID and synch.container_type='{$this->container_type}')
527
- WHERE
528
- posts.post_status = 'publish'
529
- AND posts.post_type IN ({$escaped_post_types})
530
- AND synch.container_id IS NULL";
531
- $wpdb->query($q);
532
- $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
533
- }
534
- }
535
-
536
- /**
537
- * Mark custom fields as unsynched when they're modified or deleted.
538
- *
539
- * @param array|int $meta_id
540
- * @param int $object_id
541
- * @param string $meta_key
542
- * @param string $meta_value
543
- * @return void
544
- */
545
- function meta_modified($meta_id, $object_id = 0, $meta_key= '', $meta_value = ''){
546
- global $wpdb; /** @var wpdb $wpdb */
547
-
548
- //If object_id isn't specified then the hook was probably called from the
549
- //stupidly inconsistent delete_meta() function in /wp-admin/includes/post.php.
550
- if ( empty($object_id) ){
551
- //We must manually retrieve object_id and meta_key from the DB.
552
- if ( is_array($meta_id) ){
553
- $meta_id = array_shift($meta_id);
554
- }
555
-
556
- $meta = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_id = %d", $meta_id), ARRAY_A );
557
- if ( empty($meta) ){
558
- return;
559
- }
560
-
561
- $object_id = $meta['post_id'];
562
- $meta_key = $meta['meta_key'];
563
- }
564
-
565
-
566
- //Metadata changes only matter to us if the modified key
567
- //is one that the user wants checked.
568
- if ( empty($this->selected_fields) ){
569
- return;
570
- }
571
- if ( !array_key_exists($meta_key, $this->selected_fields) ){
572
- return;
573
- }
574
-
575
- //Skip revisions. We only care about custom fields on the main post.
576
- $post = get_post($object_id);
577
- if ( empty($post) || !isset($post->post_type) || ($post->post_type === 'revision') ) {
578
- return;
579
- }
580
-
581
- $container = blcContainerHelper::get_container( array($this->container_type, intval($object_id)) );
582
- $container->mark_as_unsynched();
583
- }
584
-
585
- /**
586
- * Delete custom field synch. records when the post that they belong to is deleted.
587
- *
588
- * @param int $post_id
589
- * @return void
590
- */
591
- function post_deleted($post_id){
592
- //Get the associated container object
593
-
594
- $container = blcContainerHelper::get_container(array($this->container_type, intval($post_id)));
595
- if ($container != null) {
596
- //Delete it
597
- $container->delete();
598
- //Clean up any dangling links
599
- blc_cleanup_links();
600
- }
601
- }
602
-
603
- /**
604
- * When a post is restored, mark all of its custom fields as unparsed.
605
- * Called via the 'untrashed_post' action.
606
- *
607
- * @param int $post_id
608
- * @return void
609
- */
610
- function post_untrashed($post_id){
611
- //Get the associated container object
612
- $container = blcContainerHelper::get_container( array($this->container_type, intval($post_id)) );
613
- $container->mark_as_unsynched();
614
- }
615
-
616
- /**
617
- * Get the message to display after $n posts have been deleted.
618
- *
619
- * @uses blcAnyPostContainerManager::ui_bulk_delete_message()
620
- *
621
- * @param int $n Number of deleted posts.
622
- * @return string A delete confirmation message, e.g. "5 posts were moved to the trash"
623
- */
624
- function ui_bulk_delete_message($n){
625
- return blcAnyPostContainerManager::ui_bulk_delete_message($n);
626
- }
627
-
628
- /**
629
- * Get the message to display after $n posts have been trashed.
630
- *
631
- * @param int $n Number of deleted posts.
632
- * @return string A confirmation message, e.g. "5 posts were moved to trash"
633
- */
634
- function ui_bulk_trash_message($n){
635
- return blcAnyPostContainerManager::ui_bulk_trash_message($n);
636
- }
637
- }
1
+ <?php
2
+
3
+ /*
4
+ Plugin Name: Custom fields
5
+ Description: Container module for post metadata.
6
+ Version: 1.0
7
+ Author: Janis Elsts
8
+
9
+ ModuleID: custom_field
10
+ ModuleCategory: container
11
+ ModuleClassName: blcPostMetaManager
12
+ */
13
+
14
+ //Note : If it ever becomes necessary to check metadata on objects other than posts, it will
15
+ //be fairly easy to extract a more general metadata container class from blcPostMeta.
16
+
17
+ /**
18
+ * blcPostMeta - A link container class for post metadata (AKA custom fields).
19
+ *
20
+ * Due to the way metadata works, this container differs significantly from other containers :
21
+ * - container_field is equal to meta name, and container_id holds the ID of the post.
22
+ * - There is one synch. record per post that determines the synch. state of all metadata fields of that post.
23
+ * - Unlinking simply deletes the meta entry in question without involving the parser.
24
+ * - The list of parse-able $fields is not fixed. Instead, it's initialized based on the
25
+ * custom field list defined in Settings -> Link Checker.
26
+ * - The $wrapped_object is an array (and isn't really used for anything).
27
+ * - update_wrapped_object() does nothing.
28
+ *
29
+ * @package Broken Link Checker
30
+ * @access public
31
+ */
32
+ class blcPostMeta extends blcContainer {
33
+
34
+ var $meta_type = 'post';
35
+
36
+ /**
37
+ * Retrieve all metadata fields of the post associated with this container.
38
+ * The results are cached in the internal $wrapped_object variable.
39
+ *
40
+ * @param bool $ensure_consistency
41
+ * @return object The wrapped object.
42
+ */
43
+ function get_wrapped_object($ensure_consistency = false){
44
+ if ( is_null($this->wrapped_object) || $ensure_consistency ) {
45
+ $this->wrapped_object = get_metadata($this->meta_type, $this->container_id);
46
+ }
47
+ return $this->wrapped_object;
48
+ }
49
+
50
+ function update_wrapped_object(){
51
+ trigger_error('Function blcPostMeta::update_wrapped_object() does nothing and should not be used.', E_USER_WARNING);
52
+ }
53
+
54
+ /**
55
+ * Get the value of the specified metadata field of the object wrapped by this container.
56
+ *
57
+ * @access protected
58
+ *
59
+ * @param string $field Field name. If omitted, the value of the default field will be returned.
60
+ * @return array
61
+ */
62
+ function get_field($field = ''){
63
+ $get_only_first_field = ($this->fields[$field] !== 'metadata');
64
+ return get_metadata($this->meta_type, $this->container_id, $field, $get_only_first_field);
65
+ }
66
+
67
+ /**
68
+ * Update the value of the specified metadata field of the object wrapped by this container.
69
+ *
70
+ * @access protected
71
+ *
72
+ * @param string $field Meta name.
73
+ * @param string $new_value New meta value.
74
+ * @param string $old_value old meta value.
75
+ * @return bool|WP_Error True on success, an error object if something went wrong.
76
+ */
77
+ function update_field($field, $new_value, $old_value = ''){
78
+ $rez = update_metadata($this->meta_type, $this->container_id, $field, $new_value, $old_value);
79
+ if ( $rez ){
80
+ return true;
81
+ } else {
82
+ return new WP_Error(
83
+ 'metadata_update_failed',
84
+ sprintf(
85
+ __("Failed to update the meta field '%s' on %s [%d]", 'broken-link-checker'),
86
+ $field,
87
+ $this->meta_type,
88
+ $this->container_id
89
+ )
90
+ );
91
+ }
92
+ }
93
+
94
+ /**
95
+ * "Unlink"-ing a custom fields removes all metadata fields that contain the specified URL.
96
+ *
97
+ * @param string $field_name
98
+ * @param blcParser $parser
99
+ * @param string $url
100
+ * @param string $raw_url
101
+ * @return bool|WP_Error True on success, or an error object if something went wrong.
102
+ */
103
+ function unlink($field_name, $parser, $url, $raw_url =''){
104
+ if ( $this->fields[$field_name] !== 'metadata' ) {
105
+ return parent::unlink($field_name, $parser, $url, $raw_url);
106
+ }
107
+
108
+ $rez = delete_metadata($this->meta_type, $this->container_id, $field_name, $raw_url);
109
+ if ( $rez ){
110
+ return true;
111
+ } else {
112
+ return new WP_Error(
113
+ 'metadata_delete_failed',
114
+ sprintf(
115
+ __("Failed to delete the meta field '%s' on %s [%d]", 'broken-link-checker'),
116
+ $field_name,
117
+ $this->meta_type,
118
+ $this->container_id
119
+ )
120
+ );
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Change a meta field containing the specified URL to a new URL.
126
+ *
127
+ * @param string $field_name Meta name
128
+ * @param blcParser $parser
129
+ * @param string $new_url New URL.
130
+ * @param string $old_url
131
+ * @param string $old_raw_url Old meta value.
132
+ * @param null $new_text
133
+ * @return string|WP_Error The new value of raw_url on success, or an error object if something went wrong.
134
+ */
135
+ function edit_link($field_name, $parser, $new_url, $old_url = '', $old_raw_url = '', $new_text = null){
136
+ /*
137
+ FB::log(sprintf(
138
+ 'Editing %s[%d]:%s - %s to %s',
139
+ $this->container_type,
140
+ $this->container_id,
141
+ $field_name,
142
+ $old_url,
143
+ $new_url
144
+ ));
145
+ */
146
+
147
+ if ( $this->fields[$field_name] !== 'metadata' ) {
148
+ return parent::edit_link($field_name, $parser, $new_url, $old_url, $old_raw_url, $new_text);
149
+ }
150
+
151
+ if ( empty($old_raw_url) ){
152
+ $old_raw_url = $old_url;
153
+ }
154
+
155
+ //Get the current values of the field that needs to be edited.
156
+ //The default metadata parser ignores them, but we're still going
157
+ //to set this argument to a valid value in case someone writes a
158
+ //custom meta parser that needs it.
159
+ $old_value = $this->get_field($field_name);
160
+
161
+ //Get the new field value (a string).
162
+ $edit_result = $parser->edit($old_value, $new_url, $old_url, $old_raw_url);
163
+ if ( is_wp_error($edit_result) ){
164
+ return $edit_result;
165
+ }
166
+
167
+ //Update the field with the new value returned by the parser.
168
+ //Notice how $old_raw_url is used instead of $old_value. $old_raw_url contains the entire old
169
+ //value of the metadata field (see blcMetadataParser::parse()) and thus can be used to
170
+ //differentiate between multiple meta fields with identical names.
171
+ $update_result = $this->update_field( $field_name, $edit_result['content'], $old_raw_url );
172
+ if ( is_wp_error($update_result) ){
173
+ return $update_result;
174
+ }
175
+
176
+ //Return the new "raw" URL.
177
+ return $edit_result['raw_url'];
178
+ }
179
+
180
+ /**
181
+ * Get the default link text to use for links found in a specific container field.
182
+ *
183
+ * @param string $field
184
+ * @return string
185
+ */
186
+ function default_link_text($field = ''){
187
+ //Just use the field name. There's no way to know how the links inside custom fields are
188
+ //used, so no way to know the "real" link text. Displaying the field name at least gives
189
+ //the user a clue where to look if they want to find/modify the field.
190
+ return $field;
191
+ }
192
+
193
+ function ui_get_source($container_field = '', $context = 'display'){
194
+ if ( !post_type_exists(get_post_type($this->container_id)) ) {
195
+ //Error: Invalid post type. The user probably removed a CPT without removing the actual posts.
196
+ $post_html = '';
197
+
198
+ $post = get_post($this->container_id);
199
+ if ( $post ) {
200
+ $post_html .= sprintf(
201
+ '<span class="row-title">%s</span><br>',
202
+ get_the_title($post)
203
+ );
204
+ }
205
+ $post_html .= sprintf(
206
+ 'Invalid post type "%s"',
207
+ htmlentities($this->container_type)
208
+ );
209
+
210
+ return $post_html;
211
+ }
212
+
213
+ $post_html = sprintf(
214
+ '<a class="row-title" href="%s" title="%s">%s</a>',
215
+ esc_url($this->get_edit_url()),
216
+ esc_attr(__('Edit this post')),
217
+ get_the_title($this->container_id)
218
+ );
219
+
220
+ return $post_html;
221
+ }
222
+
223
+ function ui_get_action_links($container_field){
224
+ $actions = array();
225
+ if ( !post_type_exists(get_post_type($this->container_id)) ) {
226
+ return $actions;
227
+ }
228
+
229
+ if ( current_user_can('edit_post', $this->container_id) ) {
230
+ $actions['edit'] = '<span class="edit"><a href="' . $this->get_edit_url() . '" title="' . esc_attr(__('Edit this item')) . '">' . __('Edit') . '</a>';
231
+
232
+ if ( $this->current_user_can_delete() ){
233
+ if ( $this->can_be_trashed() ) {
234
+ $actions['trash'] = sprintf(
235
+ "<span><a class='submitdelete' title='%s' href='%s'>%s</a>",
236
+ esc_attr(__('Move this item to the Trash')),
237
+ get_delete_post_link($this->container_id, '', false),
238
+ __('Trash')
239
+ );
240
+ } else {
241
+ $actions['delete'] = sprintf(
242
+ "<span><a class='submitdelete' title='%s' href='%s'>%s</a>",
243
+ esc_attr(__('Delete this item permanently')),
244
+ get_delete_post_link($this->container_id, '', true),
245
+ __('Delete')
246
+ );
247
+ }
248
+ }
249
+ }
250
+ $actions['view'] = '<span class="view"><a href="' . esc_url(get_permalink($this->container_id)) . '" title="' . esc_attr(sprintf(__('View "%s"', 'broken-link-checker'), get_the_title($this->container_id))) . '" rel="permalink">' . __('View') . '</a>';
251
+
252
+ return $actions;
253
+ }
254
+
255
+ /**
256
+ * Get edit URL for this container. Returns the URL of the Dashboard page where the item
257
+ * associated with this container can be edited.
258
+ *
259
+ * @access protected
260
+ *
261
+ * @return string
262
+ */
263
+ function get_edit_url(){
264
+ /*
265
+ The below is a near-exact copy of the get_post_edit_link() function.
266
+ Unfortunately we can't just call that function because it has a hardcoded
267
+ caps-check which fails when called from the email notification script
268
+ executed by Cron.
269
+ */
270
+
271
+ if ( !($post = get_post( $this->container_id )) ){
272
+ return '';
273
+ }
274
+
275
+ $context = 'display';
276
+
277
+ //WP 3.0
278
+ if ( 'display' == $context )
279
+ $action = '&amp;action=edit';
280
+ else
281
+ $action = '&action=edit';
282
+
283
+ $post_type_object = get_post_type_object( $post->post_type );
284
+ if ( !$post_type_object ){
285
+ return '';
286
+ }
287
+
288
+ return apply_filters( 'get_edit_post_link', admin_url( sprintf($post_type_object->_edit_link . $action, $post->ID) ), $post->ID, $context );
289
+ }
290
+
291
+ /**
292
+ * Get the base URL of the container. For custom fields, the base URL is the permalink of
293
+ * the post that the field is attached to.
294
+ *
295
+ * @return string
296
+ */
297
+ function base_url(){
298
+ return get_permalink($this->container_id);
299
+ }
300
+
301
+ /**
302
+ * Delete or trash the post corresponding to this container. If trash is enabled,
303
+ * will always move the post to the trash instead of deleting.
304
+ *
305
+ * @return bool|WP_error
306
+ */
307
+ function delete_wrapped_object(){
308
+ if ( EMPTY_TRASH_DAYS ){
309
+ return $this->trash_wrapped_object();
310
+ } else {
311
+ if ( wp_delete_post($this->container_id) ){
312
+ return true;
313
+ } else {
314
+ return new WP_Error(
315
+ 'delete_failed',
316
+ sprintf(
317
+ __('Failed to delete post "%s" (%d)', 'broken-link-checker'),
318
+ get_the_title($this->container_id),
319
+ $this->container_id
320
+ )
321
+ );
322
+ }
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Move the post corresponding to this custom field to the Trash.
328
+ *
329
+ * @return bool|WP_Error
330
+ */
331
+ function trash_wrapped_object(){
332
+ if ( !EMPTY_TRASH_DAYS ){
333
+ return new WP_Error(
334
+ 'trash_disabled',
335
+ sprintf(
336
+ __('Can\'t move post "%s" (%d) to the trash because the trash feature is disabled', 'broken-link-checker'),
337
+ get_the_title($this->container_id),
338
+ $this->container_id
339
+ )
340
+ );
341
+ }
342
+
343
+ $post = &get_post($this->container_id);
344
+ if ( $post->post_status == 'trash' ){
345
+ //Prevent conflicts between post and custom field containers trying to trash the same post.
346
+ return true;
347
+ }
348
+
349
+ if ( wp_trash_post($this->container_id) ){
350
+ return true;
351
+ } else {
352
+ return new WP_Error(
353
+ 'trash_failed',
354
+ sprintf(
355
+ __('Failed to move post "%s" (%d) to the trash', 'broken-link-checker'),
356
+ get_the_title($this->container_id),
357
+ $this->container_id
358
+ )
359
+ );
360
+ }
361
+ }
362
+
363
+ function current_user_can_delete(){
364
+ $post = get_post($this->container_id);
365
+ $post_type_object = get_post_type_object($post->post_type);
366
+ return current_user_can( $post_type_object->cap->delete_post, $this->container_id );
367
+ }
368
+
369
+ function can_be_trashed(){
370
+ return defined('EMPTY_TRASH_DAYS') && EMPTY_TRASH_DAYS;
371
+ }
372
+ }
373
+
374
+ class blcPostMetaManager extends blcContainerManager {
375
+ var $container_class_name = 'blcPostMeta';
376
+ var $meta_type = 'post';
377
+ protected $selected_fields = array();
378
+
379
+ function init(){
380
+ parent::init();
381
+
382
+ //Figure out which custom fields we're interested in.
383
+ if ( is_array($this->plugin_conf->options['custom_fields']) ){
384
+ $prefix_formats = array(
385
+ 'html' => 'html',
386
+ 'url' => 'metadata',
387
+ );
388
+ foreach($this->plugin_conf->options['custom_fields'] as $meta_name){
389
+ //The user can add an optional "format:" prefix to specify the format of the custom field.
390
+ $parts = explode(':', $meta_name, 2);
391
+ if ( (count($parts) == 2) && in_array($parts[0], $prefix_formats) ) {
392
+ $this->selected_fields[$parts[1]] = $prefix_formats[$parts[0]];
393
+ } else {
394
+ $this->selected_fields[$meta_name] = 'metadata';
395
+ }
396
+ }
397
+ }
398
+
399
+ //Intercept 2.9+ style metadata modification actions
400
+ add_action( "added_{$this->meta_type}_meta", array($this, 'meta_modified'), 10, 4 );
401
+ add_action( "updated_{$this->meta_type}_meta", array($this, 'meta_modified'), 10, 4 );
402
+ add_action( "deleted_{$this->meta_type}_meta", array($this, 'meta_modified'), 10, 4 );
403
+
404
+ //When a post is deleted, also delete the custom field container associated with it.
405
+ add_action('delete_post', array($this,'post_deleted'));
406
+ add_action('trash_post', array($this,'post_deleted'));
407
+
408
+ //Re-parse custom fields when a post is restored from trash
409
+ add_action('untrashed_post', array($this,'post_untrashed'));
410
+ }
411
+
412
+
413
+ /**
414
+ * Get a list of parseable fields.
415
+ *
416
+ * @return array
417
+ */
418
+ function get_parseable_fields(){
419
+ return $this->selected_fields;
420
+ }
421
+
422
+ /**
423
+ * Instantiate multiple containers of the container type managed by this class.
424
+ *
425
+ * @param array $containers Array of assoc. arrays containing container data.
426
+ * @param string $purpose An optional code indicating how the retrieved containers will be used.
427
+ * @param bool $load_wrapped_objects Preload wrapped objects regardless of purpose.
428
+ *
429
+ * @return array of blcPostMeta indexed by "container_type|container_id"
430
+ */
431
+ function get_containers($containers, $purpose = '', $load_wrapped_objects = false){
432
+ $containers = $this->make_containers($containers);
433
+
434
+ /*
435
+ When links from custom fields are displayed in Tools -> Broken Links,
436
+ each one also shows the title of the post that the custom field(s)
437
+ belong to. Thus it makes sense to pre-cache the posts beforehand - it's
438
+ faster to load them all at once than to make a separate query for each
439
+ one later.
440
+
441
+ So make a list of involved post IDs and load them.
442
+
443
+ Calling get_posts() will automatically populate the post cache, so we
444
+ don't need to actually store the results anywhere in the container object().
445
+ */
446
+ $preload = $load_wrapped_objects || in_array($purpose, array(BLC_FOR_DISPLAY));
447
+ if ( $preload ){
448
+ $post_ids = array();
449
+ foreach($containers as $container){
450
+ $post_ids[] = $container->container_id;
451
+ }
452
+
453
+ $args = array('include' => implode(',', $post_ids));
454
+ get_posts($args);
455
+ }
456
+
457
+ return $containers;
458
+ }
459
+
460
+ /**
461
+ * Create or update synchronization records for all containers managed by this class.
462
+ *
463
+ * @param bool $forced If true, assume that all synch. records are gone and will need to be recreated from scratch.
464
+ * @return void
465
+ */
466
+ function resynch($forced = false){
467
+ global $wpdb; /** @var wpdb $wpdb */
468
+ global $blclog;
469
+
470
+ //Only check custom fields on selected post types. By default, that's "post" and "page".
471
+ $post_types = array('post', 'page');
472
+ if ( class_exists('blcPostTypeOverlord') ) {
473
+ $overlord = blcPostTypeOverlord::getInstance();
474
+ $post_types = array_merge($post_types, $overlord->enabled_post_types);
475
+ $post_types = array_unique($post_types);
476
+ }
477
+
478
+ $escaped_post_types = "'" . implode("', '", array_map('esc_sql', $post_types)) . "'";
479
+
480
+ if ( $forced ){
481
+ //Create new synchronization records for all posts.
482
+ $blclog->log('...... Creating synch records for all custom fields on ' . $escaped_post_types);
483
+ $start = microtime(true);
484
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
485
+ SELECT id, '{$this->container_type}', 0
486
+ FROM {$wpdb->posts}
487
+ WHERE
488
+ {$wpdb->posts}.post_status = 'publish'
489
+ AND {$wpdb->posts}.post_type IN ({$escaped_post_types})";
490
+ $wpdb->query( $q );
491
+ $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
492
+ } else {
493
+ //Delete synch records corresponding to posts that no longer exist.
494
+ $blclog->log('...... Deleting custom field synch records corresponding to deleted posts');
495
+ $start = microtime(true);
496
+ $q = "DELETE synch.*
497
+ FROM
498
+ {$wpdb->prefix}blc_synch AS synch LEFT JOIN {$wpdb->posts} AS posts
499
+ ON posts.ID = synch.container_id
500
+ WHERE
501
+ synch.container_type = '{$this->container_type}' AND posts.ID IS NULL";
502
+ $wpdb->query( $q );
503
+ $blclog->log(sprintf('...... %d rows deleted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
504
+
505
+ //Remove the 'synched' flag from all posts that have been updated
506
+ //since the last time they were parsed/synchronized.
507
+ $blclog->log('...... Marking custom fields on changed posts as unsynched');
508
+ $start = microtime(true);
509
+ $q = "UPDATE
510
+ {$wpdb->prefix}blc_synch AS synch
511
+ JOIN {$wpdb->posts} AS posts ON (synch.container_id = posts.ID and synch.container_type='{$this->container_type}')
512
+ SET
513
+ synched = 0
514
+ WHERE
515
+ synch.last_synch < posts.post_modified";
516
+ $wpdb->query( $q );
517
+ $blclog->log(sprintf('...... %d rows updated in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
518
+
519
+ //Create synch. records for posts that don't have them.
520
+ $blclog->log('...... Creating custom field synch records for new ' . $escaped_post_types);
521
+ $start = microtime(true);
522
+ $q = "INSERT INTO {$wpdb->prefix}blc_synch(container_id, container_type, synched)
523
+ SELECT id, '{$this->container_type}', 0
524
+ FROM
525
+ {$wpdb->posts} AS posts LEFT JOIN {$wpdb->prefix}blc_synch AS synch
526
+ ON (synch.container_id = posts.ID and synch.container_type='{$this->container_type}')
527
+ WHERE
528
+ posts.post_status = 'publish'
529
+ AND posts.post_type IN ({$escaped_post_types})
530
+ AND synch.container_id IS NULL";
531
+ $wpdb->query($q);
532
+ $blclog->log(sprintf('...... %d rows inserted in %.3f seconds', $wpdb->rows_affected, microtime(true) - $start));
533
+ }
534
+ }
535
+
536
+ /**
537
+ * Mark custom fields as unsynched when they're modified or deleted.
538
+ *
539
+ * @param array|int $meta_id
540
+ * @param int $object_id
541
+ * @param string $meta_key
542
+ * @param string $meta_value
543
+ * @return void
544
+ */
545
+ function meta_modified($meta_id, $object_id = 0, $meta_key= '', $meta_value = ''){
546
+ global $wpdb; /** @var wpdb $wpdb */
547
+
548
+ //If object_id isn't specified then the hook was probably called from the
549
+ //stupidly inconsistent delete_meta() function in /wp-admin/includes/post.php.
550
+ if ( empty($object_id) ){
551
+ //We must manually retrieve object_id and meta_key from the DB.
552
+ if ( is_array($meta_id) ){
553
+ $meta_id = array_shift($meta_id);
554
+ }
555
+
556
+ $meta = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_id = %d", $meta_id), ARRAY_A );
557
+ if ( empty($meta) ){
558
+ return;
559
+ }
560
+
561
+ $object_id = $meta['post_id'];
562
+ $meta_key = $meta['meta_key'];
563
+ }
564
+
565
+
566
+ //Metadata changes only matter to us if the modified key
567
+ //is one that the user wants checked.
568
+ if ( empty($this->selected_fields) ){
569
+ return;
570
+ }
571
+ if ( !array_key_exists($meta_key, $this->selected_fields) ){
572
+ return;
573
+ }
574
+
575
+ //Skip revisions. We only care about custom fields on the main post.
576
+ $post = get_post($object_id);
577
+ if ( empty($post) || !isset($post->post_type) || ($post->post_type === 'revision') ) {
578
+ return;
579
+ }
580
+
581
+ $container = blcContainerHelper::get_container( array($this->container_type, intval($object_id)) );
582
+ $container->mark_as_unsynched();
583
+ }
584
+
585
+ /**
586
+ * Delete custom field synch. records when the post that they belong to is deleted.
587
+ *
588
+ * @param int $post_id
589
+ * @return void
590
+ */
591
+ function post_deleted($post_id){
592
+ //Get the associated container object
593
+
594
+ $container = blcContainerHelper::get_container(array($this->container_type, intval($post_id)));
595
+ if ($container != null) {
596
+ //Delete it
597
+ $container->delete();
598
+ //Clean up any dangling links
599
+ blc_cleanup_links();
600
+ }
601
+ }
602
+
603
+ /**
604
+ * When a post is restored, mark all of its custom fields as unparsed.
605
+ * Called via the 'untrashed_post' action.
606
+ *
607
+ * @param int $post_id
608
+ * @return void
609
+ */
610
+ function post_untrashed($post_id){
611
+ //Get the associated container object
612
+ $container = blcContainerHelper::get_container( array($this->container_type, intval($post_id)) );
613
+ $container->mark_as_unsynched();
614
+ }
615
+
616
+ /**
617
+ * Get the message to display after $n posts have been deleted.
618
+ *
619
+ * @uses blcAnyPostContainerManager::ui_bulk_delete_message()
620
+ *
621
+ * @param int $n Number of deleted posts.
622
+ * @return string A delete confirmation message, e.g. "5 posts were moved to the trash"
623
+ */
624
+ function ui_bulk_delete_message($n){
625
+ return blcAnyPostContainerManager::ui_bulk_delete_message($n);
626
+ }
627
+
628
+ /**
629
+ * Get the message to display after $n posts have been trashed.
630
+ *
631
+ * @param int $n Number of deleted posts.
632
+ * @return string A confirmation message, e.g. "5 posts were moved to trash"
633
+ */
634
+ function ui_bulk_trash_message($n){
635
+ return blcAnyPostContainerManager::ui_bulk_trash_message($n);
636
+ }
637
+ }
modules/containers/dummy.php CHANGED
@@ -1,75 +1,75 @@
1
- <?php
2
-
3
- /*
4
- Plugin Name: Dummy
5
- Description:
6
- Version: 1.0
7
- Author: Janis Elsts
8
-
9
- ModuleID: dummy
10
- ModuleCategory: container
11
- ModuleClassName: blcDummyManager
12
- ModuleAlwaysActive: true
13
- ModuleHidden: true
14
- */
15
-
16
- /**
17
- * A "dummy" container class that can be used as a fallback when the real container class can't be found.
18
- *
19
- *
20
- * @package Broken Link Checker
21
- * @access public
22
- */
23
- class blcDummyContainer extends blcContainer{
24
-
25
- function synch(){
26
- //Just mark it as synched so that it doesn't bother us anymore.
27
- $this->mark_as_synched();
28
- }
29
-
30
- function edit_link($field_name, $parser, $new_url, $old_url = '', $old_raw_url = '', $new_text = null){
31
- return new WP_Error(
32
- 'container_not_found',
33
- sprintf(
34
- __("I don't know how to edit a '%s' [%d].", 'broken-link-checker'),
35
- $this->container_type,
36
- $this->container_id
37
- )
38
- );
39
- }
40
-
41
- function unlink($field_name, $parser, $url, $raw_url =''){
42
- return new WP_Error(
43
- 'container_not_found',
44
- sprintf(
45
- __("I don't know how to edit a '%s' [%d].", 'broken-link-checker'),
46
- $this->container_type,
47
- $this->container_id
48
- )
49
- );
50
- }
51
-
52
- function ui_get_source($container_field, $context = 'display'){
53
- return sprintf(
54
- '<em>Unknown source %s[%d]:%s</em>',
55
- $this->container_type,
56
- $this->container_id,
57
- $container_field
58
- );
59
- }
60
- }
61
-
62
- /**
63
- * A dummy manager class.
64
- *
65
- * @package Broken Link Checker
66
- * @access public
67
- */
68
- class blcDummyManager extends blcContainerManager {
69
-
70
- var $container_class_name = 'blcDummyContainer';
71
-
72
- function resynch($forced = false){
73
- //Do nothing.
74
- }
75
- }
1
+ <?php
2
+
3
+ /*
4
+ Plugin Name: Dummy
5
+ Description:
6
+ Version: 1.0
7
+ Author: Janis Elsts
8
+
9
+ ModuleID: dummy
10
+ ModuleCategory: container
11
+ ModuleClassName: blcDummyManager
12
+ ModuleAlwaysActive: true
13
+ ModuleHidden: true
14
+ */
15
+
16
+ /**
17
+ * A "dummy" container class that can be used as a fallback when the real container class can't be found.
18
+ *
19
+ *
20
+ * @package Broken Link Checker
21
+ * @access public
22
+ */
23
+ class blcDummyContainer extends blcContainer{
24
+
25
+ function synch(){
26
+ //Just mark it as synched so that it doesn't bother us anymore.
27
+ $this->mark_as_synched();
28
+ }
29
+
30
+ function edit_link($field_name, $parser, $new_url, $old_url = '', $old_raw_url = '', $new_text = null){
31
+ return new WP_Error(
32
+ 'container_not_found',
33
+ sprintf(
34
+ __("I don't know how to edit a '%s' [%d].", 'broken-link-checker'),
35
+ $this->container_type,
36
+ $this->container_id
37
+ )
38
+ );
39
+ }
40
+
41
+ function unlink($field_name, $parser, $url, $raw_url =''){
42
+ return new WP_Error(
43
+ 'container_not_found',
44
+ sprintf(
45
+ __("I don't know how to edit a '%s' [%d].", 'broken-link-checker'),
46
+ $this->container_type,
47
+ $this->container_id
48
+ )
49
+ );
50
+ }
51
+
52
+ function ui_get_source($container_field, $context = 'display'){
53
+ return sprintf(
54
+ '<em>Unknown source %s[%d]:%s</em>',
55
+ $this->container_type,
56
+ $this->container_id,
57
+ $container_field
58
+ );
59
+ }
60
+ }
61
+
62
+ /**
63
+ * A dummy manager class.
64
+ *
65
+ * @package Broken Link Checker
66
+ * @access public
67
+ */
68
+ class blcDummyManager extends blcContainerManager {
69
+
70
+ var $container_class_name = 'blcDummyContainer';
71
+
72
+ function resynch($forced = false){
73
+ //Do nothing.
74
+ }
75
+ }
modules/extras/dailymotion-embed.php CHANGED
@@ -1,37 +1,37 @@
1
- <?php
2
- /*
3
- Plugin Name: Embedded DailyMotion videos
4
- Description: Parse embedded videos from DailyMotion
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcDailyMotionEmbed
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
- */
13
-
14
- if ( !class_exists('blcEmbedParserBase') ){
15
- require 'embed-parser-base.php';
16
- }
17
-
18
- class blcDailyMotionEmbed extends blcEmbedParserBase {
19
-
20
- function init(){
21
- parent::init();
22
- $this->url_search_string = 'dailymotion.com/swf/video/';
23
- $this->short_title = __('DailyMotion Video','broken-link-checker');
24
- $this->long_title = __('Embedded DailyMotion video', 'broken-link-checker');
25
- }
26
-
27
- function link_url_from_src($src){
28
- //Extract video ID from the SRC. Only the part before the underscore matters,
29
- //but we're going to use the entire slug to make the display URL look better.
30
- $video_id = end(explode('/', $src));
31
-
32
- //Reconstruct the video permalink based on the ID
33
- $url = 'http://www.dailymotion.com/video/' . $video_id;
34
-
35
- return $url;
36
- }
37
  }
1
+ <?php
2
+ /*
3
+ Plugin Name: Embedded DailyMotion videos
4
+ Description: Parse embedded videos from DailyMotion
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcDailyMotionEmbed
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+ */
13
+
14
+ if ( !class_exists('blcEmbedParserBase') ){
15
+ require 'embed-parser-base.php';
16
+ }
17
+
18
+ class blcDailyMotionEmbed extends blcEmbedParserBase {
19
+
20
+ function init(){
21
+ parent::init();
22
+ $this->url_search_string = 'dailymotion.com/swf/video/';
23
+ $this->short_title = __('DailyMotion Video','broken-link-checker');
24
+ $this->long_title = __('Embedded DailyMotion video', 'broken-link-checker');
25
+ }
26
+
27
+ function link_url_from_src($src){
28
+ //Extract video ID from the SRC. Only the part before the underscore matters,
29
+ //but we're going to use the entire slug to make the display URL look better.
30
+ $video_id = end(explode('/', $src));
31
+
32
+ //Reconstruct the video permalink based on the ID
33
+ $url = 'http://www.dailymotion.com/video/' . $video_id;
34
+
35
+ return $url;
36
+ }
37
  }
modules/extras/embed-parser-base.php CHANGED
@@ -1,207 +1,207 @@
1
- <?php
2
-
3
- /**
4
- * @author Janis Elsts
5
- * @copyright 2010
6
- */
7
-
8
- if ( !class_exists('blcEmbedParserBase') ):
9
-
10
- /**
11
- * Base class for embedded video/audio parsers.
12
- *
13
- * Sub-classes should override the link_url_from_src() method and set the $url_search_string,
14
- * $short_title and $long_title properties to meaningful values.
15
- *
16
- * @package Broken Link Checker
17
- * @author Janis Elsts
18
- * @access public
19
- */
20
- class blcEmbedParserBase extends blcParser {
21
- var $supported_formats = array('html');
22
-
23
- var $short_title = ''; //Short desc. of embeds handled by this parser, singular. Example: "YouTube Video".
24
- var $long_title = ''; //Longer version of the above, e.g. "Embedded YouTube video".
25
- var $url_search_string = '';//Only consider embeds where the SRC contains this string. Example: "youtube.com/v/"
26
-
27
- /**
28
- * Parse a string for embed codes.
29
- *
30
- * @param string $content The text to parse.
31
- * @param string $base_url The base URL. Ignored.
32
- * @param string $default_link_text Default link text. Ignored.
33
- * @return array An array of new blcLinkInstance objects. The objects will include info about the embeds found, but not about the corresponding container entity.
34
- */
35
- function parse($content, $base_url = '', $default_link_text = ''){
36
- $instances = array();
37
-
38
- //Find likely-looking <embed> elements
39
- $embeds = $this->extract_embeds($content);
40
- foreach($embeds as $embed){
41
- //Do we know how to handle this embed? (first-pass verification)
42
- if ( strpos($embed['attributes']['src'], $this->url_search_string) === false ){
43
- continue;
44
- }
45
-
46
- //Get the original URL of the embedded object (may perform more complex verification)
47
- $url = $this->link_url_from_src($embed['attributes']['src']);
48
- if ( empty($url) ){
49
- continue;
50
- }
51
-
52
- //Create a new link instance.
53
- $instance = new blcLinkInstance();
54
-
55
- $instance->set_parser($this);
56
- $instance->raw_url = $embed['embed_code'];
57
- $instance->link_text = '[' . $this->short_title .']';
58
-
59
- $link_obj = new blcLink($url); //Creates or loads the link
60
- $instance->set_link($link_obj);
61
-
62
- $instances[] = $instance;
63
- }
64
-
65
- return $instances;
66
- }
67
-
68
- /**
69
- * Extract embedded elements from a HTML string.
70
- *
71
- * This function returns an array of <embed> elements found in the input
72
- * string. Embeds without a 'src' attribute are skipped.
73
- *
74
- * Each array item has the same basic structure as the array items
75
- * returned by blcUtility::extract_tags(), plus an additional 'embed_code' key
76
- * that contains the HTML code for the element. If the embed element is wrapped
77
- * in an <object>, the 'embed_code' key contains the full HTML for the entire
78
- * <object> + <embed> structure.
79
- *
80
- * @uses blcUtility::extract_tags() This function is a simple wrapper around extract_tags()
81
- *
82
- * @param string $html
83
- * @return array
84
- */
85
- function extract_embeds($html){
86
- $results = array();
87
-
88
- //remove all <code></code> blocks first
89
- $html = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $html);
90
-
91
- //Find likely-looking <object> elements
92
- $objects = blcUtility::extract_tags($html, 'object', false, true);
93
- foreach($objects as $candidate){
94
- //Find the <embed> tag
95
- $embed = blcUtility::extract_tags($candidate['full_tag'], 'embed', true);
96
- if ( empty($embed)) continue;
97
- $embed = reset($embed); //Take the first (and only) found <embed> element
98
-
99
- if ( empty($embed['attributes']['src']) ){
100
- continue;
101
- }
102
-
103
- $embed['embed_code'] = $candidate['full_tag'];
104
-
105
- $results[] = $embed;
106
-
107
- //Remove the element so it doesn't come up when we search for plain <embed> elements.
108
- $html = str_replace($candidate['full_tag'], ' ', $html);
109
- }
110
-
111
- //Find <embed> elements not wrapped in an <object> element.
112
- $embeds = blcUtility::extract_tags($html, 'embed', true, true);
113
- foreach($embeds as $embed) {
114
- if ( !empty($embed['attributes']['src']) ){
115
- $embed['embed_code'] = $embed['full_tag'];
116
- $results[] = $embed;
117
- }
118
- }
119
-
120
- return $results;
121
- }
122
-
123
- /**
124
- * Remove all occurrences of the specified embed from a string.
125
- *
126
- * @param string $content Look for embeds in this string.
127
- * @param string $url Ignored.
128
- * @param string $embed_code The full embed code to look for.
129
- * @return string Input string with all matching embeds removed.
130
- */
131
- function unlink($content, $url, $embed_code){
132
- if ( empty($embed_code) ){
133
- return $content;
134
- }
135
-
136
- return str_replace($embed_code, '', $content); //Super-simple.
137
- }
138
-
139
- /**
140
- * Get the link text for printing in the "Broken Links" table.
141
- *
142
- * @param blcLinkInstance $instance
143
- * @param string $context
144
- * @return string HTML
145
- */
146
- function ui_get_link_text($instance, $context = 'display'){
147
- $image_url = sprintf(
148
- '/images/%s.png',
149
- $this->parser_type
150
- );
151
-
152
- $image_html = sprintf(
153
- '<img src="%s" class="blc-small-image" title="%2$s" alt="%2$s"> ',
154
- esc_attr( plugins_url($image_url, BLC_PLUGIN_FILE) ),
155
- $this->long_title
156
- );
157
-
158
- $field_html = sprintf(
159
- '%s',
160
- $this->short_title
161
- );
162
-
163
- if ( $context != 'email' ){
164
- $field_html = $image_html . $field_html;
165
- }
166
-
167
- return $field_html;
168
- }
169
-
170
- /**
171
- * Determine the original URL of an embedded object by analysing its SRC attribute.
172
- *
173
- * For example, if the object in question is an embedded YouTube video, this
174
- * method should return the URL of the original video; e.g. 'http://www.youtube.com/watch?v=example1234'
175
- *
176
- * Should be overridden in a sub-class.
177
- *
178
- * @param string $src
179
- * @return string The URL of the embedded object, or an empty string if the URL can't be determined.
180
- */
181
- function link_url_from_src($src){
182
- return '';
183
- }
184
-
185
- /**
186
- * Editing is disabled in embed parsers. Calling this function will yield an instance of WP_Error.
187
- *
188
- * @param string $content
189
- * @param string $new_url
190
- * @param string $old_url
191
- * @param string $old_raw_url
192
- * @return WP_Error
193
- */
194
- function edit($content, $new_url, $old_url, $old_raw_url){
195
- return new WP_Error(
196
- 'not_implemented',
197
- sprintf(__("Embedded videos can't be edited using Broken Link Checker. Please edit or replace the video in question manually.", 'broken-link-checker'), $this->parser_type)
198
- );
199
- }
200
-
201
- public function is_url_editable() {
202
- return false;
203
- }
204
-
205
- }
206
-
207
  endif;
1
+ <?php
2
+
3
+ /**
4
+ * @author Janis Elsts
5
+ * @copyright 2010
6
+ */
7
+
8
+ if ( !class_exists('blcEmbedParserBase') ):
9
+
10
+ /**
11
+ * Base class for embedded video/audio parsers.
12
+ *
13
+ * Sub-classes should override the link_url_from_src() method and set the $url_search_string,
14
+ * $short_title and $long_title properties to meaningful values.
15
+ *
16
+ * @package Broken Link Checker
17
+ * @author Janis Elsts
18
+ * @access public
19
+ */
20
+ class blcEmbedParserBase extends blcParser {
21
+ var $supported_formats = array('html');
22
+
23
+ var $short_title = ''; //Short desc. of embeds handled by this parser, singular. Example: "YouTube Video".
24
+ var $long_title = ''; //Longer version of the above, e.g. "Embedded YouTube video".
25
+ var $url_search_string = '';//Only consider embeds where the SRC contains this string. Example: "youtube.com/v/"
26
+
27
+ /**
28
+ * Parse a string for embed codes.
29
+ *
30
+ * @param string $content The text to parse.
31
+ * @param string $base_url The base URL. Ignored.
32
+ * @param string $default_link_text Default link text. Ignored.
33
+ * @return array An array of new blcLinkInstance objects. The objects will include info about the embeds found, but not about the corresponding container entity.
34
+ */
35
+ function parse($content, $base_url = '', $default_link_text = ''){
36
+ $instances = array();
37
+
38
+ //Find likely-looking <embed> elements
39
+ $embeds = $this->extract_embeds($content);
40
+ foreach($embeds as $embed){
41
+ //Do we know how to handle this embed? (first-pass verification)
42
+ if ( strpos($embed['attributes']['src'], $this->url_search_string) === false ){
43
+ continue;
44
+ }
45
+
46
+ //Get the original URL of the embedded object (may perform more complex verification)
47
+ $url = $this->link_url_from_src($embed['attributes']['src']);
48
+ if ( empty($url) ){
49
+ continue;
50
+ }
51
+
52
+ //Create a new link instance.
53
+ $instance = new blcLinkInstance();
54
+
55
+ $instance->set_parser($this);
56
+ $instance->raw_url = $embed['embed_code'];
57
+ $instance->link_text = '[' . $this->short_title .']';
58
+
59
+ $link_obj = new blcLink($url); //Creates or loads the link
60
+ $instance->set_link($link_obj);
61
+
62
+ $instances[] = $instance;
63
+ }
64
+
65
+ return $instances;
66
+ }
67
+
68
+ /**
69
+ * Extract embedded elements from a HTML string.
70
+ *
71
+ * This function returns an array of <embed> elements found in the input
72
+ * string. Embeds without a 'src' attribute are skipped.
73
+ *
74
+ * Each array item has the same basic structure as the array items
75
+ * returned by blcUtility::extract_tags(), plus an additional 'embed_code' key
76
+ * that contains the HTML code for the element. If the embed element is wrapped
77
+ * in an <object>, the 'embed_code' key contains the full HTML for the entire
78
+ * <object> + <embed> structure.
79
+ *
80
+ * @uses blcUtility::extract_tags() This function is a simple wrapper around extract_tags()
81
+ *
82
+ * @param string $html
83
+ * @return array
84
+ */
85
+ function extract_embeds($html){
86
+ $results = array();
87
+
88
+ //remove all <code></code> blocks first
89
+ $html = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $html);
90
+
91
+ //Find likely-looking <object> elements
92
+ $objects = blcUtility::extract_tags($html, 'object', false, true);
93
+ foreach($objects as $candidate){
94
+ //Find the <embed> tag
95
+ $embed = blcUtility::extract_tags($candidate['full_tag'], 'embed', true);
96
+ if ( empty($embed)) continue;
97
+ $embed = reset($embed); //Take the first (and only) found <embed> element
98
+
99
+ if ( empty($embed['attributes']['src']) ){
100
+ continue;
101
+ }
102
+
103
+ $embed['embed_code'] = $candidate['full_tag'];
104
+
105
+ $results[] = $embed;
106
+
107
+ //Remove the element so it doesn't come up when we search for plain <embed> elements.
108
+ $html = str_replace($candidate['full_tag'], ' ', $html);
109
+ }
110
+
111
+ //Find <embed> elements not wrapped in an <object> element.
112
+ $embeds = blcUtility::extract_tags($html, 'embed', true, true);
113
+ foreach($embeds as $embed) {
114
+ if ( !empty($embed['attributes']['src']) ){
115
+ $embed['embed_code'] = $embed['full_tag'];
116
+ $results[] = $embed;
117
+ }
118
+ }
119
+
120
+ return $results;
121
+ }
122
+
123
+ /**
124
+ * Remove all occurrences of the specified embed from a string.
125
+ *
126
+ * @param string $content Look for embeds in this string.
127
+ * @param string $url Ignored.
128
+ * @param string $embed_code The full embed code to look for.
129
+ * @return string Input string with all matching embeds removed.
130
+ */
131
+ function unlink($content, $url, $embed_code){
132
+ if ( empty($embed_code) ){
133
+ return $content;
134
+ }
135
+
136
+ return str_replace($embed_code, '', $content); //Super-simple.
137
+ }
138
+
139
+ /**
140
+ * Get the link text for printing in the "Broken Links" table.
141
+ *
142
+ * @param blcLinkInstance $instance
143
+ * @param string $context
144
+ * @return string HTML
145
+ */
146
+ function ui_get_link_text($instance, $context = 'display'){
147
+ $image_url = sprintf(
148
+ '/images/%s.png',
149
+ $this->parser_type
150
+ );
151
+
152
+ $image_html = sprintf(
153
+ '<img src="%s" class="blc-small-image" title="%2$s" alt="%2$s"> ',
154
+ esc_attr( plugins_url($image_url, BLC_PLUGIN_FILE) ),
155
+ $this->long_title
156
+ );
157
+
158
+ $field_html = sprintf(
159
+ '%s',
160
+ $this->short_title
161
+ );
162
+
163
+ if ( $context != 'email' ){
164
+ $field_html = $image_html . $field_html;
165
+ }
166
+
167
+ return $field_html;
168
+ }
169
+
170
+ /**
171
+ * Determine the original URL of an embedded object by analysing its SRC attribute.
172
+ *
173
+ * For example, if the object in question is an embedded YouTube video, this
174
+ * method should return the URL of the original video; e.g. 'http://www.youtube.com/watch?v=example1234'
175
+ *
176
+ * Should be overridden in a sub-class.
177
+ *
178
+ * @param string $src
179
+ * @return string The URL of the embedded object, or an empty string if the URL can't be determined.
180
+ */
181
+ function link_url_from_src($src){
182
+ return '';
183
+ }
184
+
185
+ /**
186
+ * Editing is disabled in embed parsers. Calling this function will yield an instance of WP_Error.
187
+ *
188
+ * @param string $content
189
+ * @param string $new_url
190
+ * @param string $old_url
191
+ * @param string $old_raw_url
192
+ * @return WP_Error
193
+ */
194
+ function edit($content, $new_url, $old_url, $old_raw_url){
195
+ return new WP_Error(
196
+ 'not_implemented',
197
+ sprintf(__("Embedded videos can't be edited using Broken Link Checker. Please edit or replace the video in question manually.", 'broken-link-checker'), $this->parser_type)
198
+ );
199
+ }
200
+
201
+ public function is_url_editable() {
202
+ return false;
203
+ }
204
+
205
+ }
206
+
207
  endif;
modules/extras/googlevideo-embed.php CHANGED
@@ -1,35 +1,35 @@
1
- <?php
2
- /*
3
- Plugin Name: Embedded GoogleVideo videos
4
- Description: Parse embedded videos from GoogleVideo
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcGoogleVideoEmbed
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
-
13
- ModulePriority: 110
14
- */
15
-
16
- if ( !class_exists('blcEmbedParserBase') ){
17
- require 'embed-parser-base.php';
18
- }
19
-
20
- class blcGoogleVideoEmbed extends blcEmbedParserBase {
21
-
22
- function init(){
23
- parent::init();
24
- $this->short_title = __('GoogleVideo Video', 'broken-link-checker');
25
- $this->long_title = __('Embedded GoogleVideo video', 'broken-link-checker');
26
- $this->url_search_string = 'video.google.com/';
27
- }
28
-
29
- function link_url_from_src($src){
30
- parse_str(parse_url($src, PHP_URL_QUERY), $query);
31
- $url = 'http://video.google.com/videoplay?' . build_query(array('docid' => $query['docid']));
32
- return $url;
33
- }
34
- }
35
-
1
+ <?php
2
+ /*
3
+ Plugin Name: Embedded GoogleVideo videos
4
+ Description: Parse embedded videos from GoogleVideo
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcGoogleVideoEmbed
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+
13
+ ModulePriority: 110
14
+ */
15
+
16
+ if ( !class_exists('blcEmbedParserBase') ){
17
+ require 'embed-parser-base.php';
18
+ }
19
+
20
+ class blcGoogleVideoEmbed extends blcEmbedParserBase {
21
+
22
+ function init(){
23
+ parent::init();
24
+ $this->short_title = __('GoogleVideo Video', 'broken-link-checker');
25
+ $this->long_title = __('Embedded GoogleVideo video', 'broken-link-checker');
26
+ $this->url_search_string = 'video.google.com/';
27
+ }
28
+
29
+ function link_url_from_src($src){
30
+ parse_str(parse_url($src, PHP_URL_QUERY), $query);
31
+ $url = 'http://video.google.com/videoplay?' . build_query(array('docid' => $query['docid']));
32
+ return $url;
33
+ }
34
+ }
35
+
modules/extras/mediafire.php CHANGED
@@ -1,166 +1,166 @@
1
- <?php
2
- /*
3
- Plugin Name: MediaFire API
4
- Description: Check links to files hosted on MediaFire.
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleID: mediafire-checker
9
- ModuleCategory: checker
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
- ModuleClassName: blcMediaFireChecker
13
- ModulePriority: 100
14
-
15
- ModuleCheckerUrlPattern: @^http://(?:www\.)?mediafire\.com/(?:(?:download\.php)?\?|download/)([0-9a-zA-Z]{11,20})(?:$|[^0-9a-zA-Z])@
16
- */
17
-
18
- /**
19
- * MediaFire link checker.
20
- *
21
- * @package Broken Link Checker
22
- * @author Janis Elsts
23
- * @access public
24
- */
25
- class blcMediaFireChecker extends blcChecker {
26
-
27
- /**
28
- * Determine if the checker can parse a specific URL.
29
- * Always returns true because the ModuleCheckerUrlPattern header constitutes sufficient verification.
30
- *
31
- * @param string $url
32
- * @param array $parsed
33
- * @return bool True.
34
- */
35
- function can_check($url, $parsed){
36
- return true;
37
- }
38
-
39
- /**
40
- * Check a MediaFire link.
41
- *
42
- * @param string $url
43
- * @return array
44
- */
45
- function check($url){
46
- $result = array(
47
- 'final_url' => $url,
48
- 'redirect_count' => 0,
49
- 'timeout' => false,
50
- 'broken' => false,
51
- 'log' => "<em>(Using MediaFire checker module)</em>\n\n",
52
- 'http_code' => 0,
53
- 'result_hash' => '',
54
- );
55
-
56
- //URLs like http://www.mediafire.com/download.php?03mj0mwmnnm are technically valid,
57
- //but they introduce unnecessary redirects.
58
- $url = str_replace('download.php','', $url);
59
-
60
- //Since MediaFire doesn't have an API, we just send a HEAD request
61
- //and try do divine the file state from the response headers.
62
- $start = microtime_float();
63
- $rez = $this->head($url);
64
- $result['request_duration'] = microtime_float() - $start;
65
-
66
- if ( is_wp_error($rez) ){
67
-
68
- //An unexpected error.
69
- $result['broken'] = true;
70
- $result['log'] .= "Error : " . $rez->get_error_message();
71
- if ( $data = $rez->get_error_data() ){
72
- $result['log'] .= "\n\nError data : " . print_r($data, true);
73
- }
74
-
75
- } else {
76
-
77
- $result['http_code'] = intval($rez['response']['code']);
78
-
79
- if ( $result['http_code'] == 200 ){
80
- //200 - OK
81
- $result['broken'] = false;
82
- $result['log'] .= "File OK";
83
- } elseif ( isset($rez['headers']['location']) ) {
84
- //Redirect = either an error or a redirect to the full file URL.
85
- //For errors, the redirect URL is structured like this : '/error.php?errno=320'.
86
- //The 'errno' argument contains an (undocumented) error code.
87
- $result['broken'] = true;
88
-
89
- if ( strpos($rez['headers']['location'], '/download/') !== false ) {
90
- $result['broken'] = false;
91
- $result['http_code'] = 200;
92
- $result['log'] .= "File OK";
93
- $result['log'] .= "\nFull URL: " . $rez['headers']['location'];
94
-
95
- } elseif ( strpos($rez['headers']['location'], 'errno=320') !== false ){
96
- $result['status_code'] = BLC_LINK_STATUS_ERROR;
97
- $result['status_text'] = __('Not Found', 'broken-link-checker');
98
- $result['http_code'] = 0;
99
- $result['log'] .= "The file is invalid or has been removed.";
100
-
101
- } elseif ( strpos($rez['headers']['location'], 'errno=378') !== false ) {
102
- $result['status_code'] = BLC_LINK_STATUS_ERROR;
103
- $result['status_text'] = __('Not Found', 'broken-link-checker');
104
- $result['http_code'] = 0;
105
- $result['log'] .= "The file has been removed due to a violation of MediaFire ToS.";
106
-
107
- } elseif ( strpos($rez['headers']['location'], 'errno=388') !== false ) {
108
- $result['status_code'] = BLC_LINK_STATUS_WARNING;
109
- $result['status_text'] = __('Permission Denied', 'broken-link-checker');
110
- $result['http_code'] = 0;
111
- $result['log'] .= "Permission denied. Most likely the plugin sent too many requests too quickly. Try again later.";
112
-
113
- } else {
114
- $result['status_code'] = BLC_LINK_STATUS_INFO;
115
- $result['status_text'] = __('Unknown Error', 'broken-link-checker');
116
- $result['log'] .= "Unknown error.\n\n";
117
- foreach($rez['headers'] as $name => $value){
118
- $result['log'] .= sprintf("%s: %s\n", $name, $value);
119
- }
120
- }
121
-
122
- } else {
123
- $result['log'] .= "Unknown error.\n\n" . implode("\n",$rez['headers']);
124
- }
125
- }
126
-
127
- //Generate the result hash (used for detecting false positives)
128
- $result['result_hash'] = implode('|', array(
129
- 'mediafire',
130
- $result['http_code'],
131
- $result['broken']?'broken':'0',
132
- $result['timeout']?'timeout':'0'
133
- ));
134
-
135
- return $result;
136
- }
137
-
138
- /**
139
- * Perform a HEAD request to the specified URL.
140
- *
141
- * Note :
142
- *
143
- * Since the MediaFire checker works by parsing the "Location" header, redirect following
144
- * _must_ be disabled. This can become a problem on servers where WP is forced to fall back
145
- * on using WP_Http_Fopen which ignores the 'redirection' flag. WP_Http_Fsockopen would work,
146
- * but it has the lowest priority of all transports.
147
- *
148
- * Alas, there is no way to reliably influence which transport is chosen - the WP_Http::_getTransport
149
- * function caches the available choices, so plugins can disable individual transports only during
150
- * its first run. Therefore, we must pick the best transport manually.
151
- *
152
- * @param string $url
153
- * @return array|WP_Error
154
- */
155
- function head($url){
156
- $conf = blc_get_configuration();
157
- $args = array(
158
- 'timeout' => $conf->options['timeout'],
159
- 'redirection' => 0,
160
- '_redirection' => 0, //Internal flag that turns off redirect handling. See WP_Http::handle_redirects()
161
- );
162
-
163
- return wp_remote_head($url, $args);
164
- }
165
-
166
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: MediaFire API
4
+ Description: Check links to files hosted on MediaFire.
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleID: mediafire-checker
9
+ ModuleCategory: checker
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+ ModuleClassName: blcMediaFireChecker
13
+ ModulePriority: 100
14
+
15
+ ModuleCheckerUrlPattern: @^http://(?:www\.)?mediafire\.com/(?:(?:download\.php)?\?|download/)([0-9a-zA-Z]{11,20})(?:$|[^0-9a-zA-Z])@
16
+ */
17
+
18
+ /**
19
+ * MediaFire link checker.
20
+ *
21
+ * @package Broken Link Checker
22
+ * @author Janis Elsts
23
+ * @access public
24
+ */
25
+ class blcMediaFireChecker extends blcChecker {
26
+
27
+ /**
28
+ * Determine if the checker can parse a specific URL.
29
+ * Always returns true because the ModuleCheckerUrlPattern header constitutes sufficient verification.
30
+ *
31
+ * @param string $url
32
+ * @param array $parsed
33
+ * @return bool True.
34
+ */
35
+ function can_check($url, $parsed){
36
+ return true;
37
+ }
38
+
39
+ /**
40
+ * Check a MediaFire link.
41
+ *
42
+ * @param string $url
43
+ * @return array
44
+ */
45
+ function check($url){
46
+ $result = array(
47
+ 'final_url' => $url,
48
+ 'redirect_count' => 0,
49
+ 'timeout' => false,
50
+ 'broken' => false,
51
+ 'log' => "<em>(Using MediaFire checker module)</em>\n\n",
52
+ 'http_code' => 0,
53
+ 'result_hash' => '',
54
+ );
55
+
56
+ //URLs like http://www.mediafire.com/download.php?03mj0mwmnnm are technically valid,
57
+ //but they introduce unnecessary redirects.
58
+ $url = str_replace('download.php','', $url);
59
+
60
+ //Since MediaFire doesn't have an API, we just send a HEAD request
61
+ //and try do divine the file state from the response headers.
62
+ $start = microtime_float();
63
+ $rez = $this->head($url);
64
+ $result['request_duration'] = microtime_float() - $start;
65
+
66
+ if ( is_wp_error($rez) ){
67
+
68
+ //An unexpected error.
69
+ $result['broken'] = true;
70
+ $result['log'] .= "Error : " . $rez->get_error_message();
71
+ if ( $data = $rez->get_error_data() ){
72
+ $result['log'] .= "\n\nError data : " . print_r($data, true);
73
+ }
74
+
75
+ } else {
76
+
77
+ $result['http_code'] = intval($rez['response']['code']);
78
+
79
+ if ( $result['http_code'] == 200 ){
80
+ //200 - OK
81
+ $result['broken'] = false;
82
+ $result['log'] .= "File OK";
83
+ } elseif ( isset($rez['headers']['location']) ) {
84
+ //Redirect = either an error or a redirect to the full file URL.
85
+ //For errors, the redirect URL is structured like this : '/error.php?errno=320'.
86
+ //The 'errno' argument contains an (undocumented) error code.
87
+ $result['broken'] = true;
88
+
89
+ if ( strpos($rez['headers']['location'], '/download/') !== false ) {
90
+ $result['broken'] = false;
91
+ $result['http_code'] = 200;
92
+ $result['log'] .= "File OK";
93
+ $result['log'] .= "\nFull URL: " . $rez['headers']['location'];
94
+
95
+ } elseif ( strpos($rez['headers']['location'], 'errno=320') !== false ){
96
+ $result['status_code'] = BLC_LINK_STATUS_ERROR;
97
+ $result['status_text'] = __('Not Found', 'broken-link-checker');
98
+ $result['http_code'] = 0;
99
+ $result['log'] .= "The file is invalid or has been removed.";
100
+
101
+ } elseif ( strpos($rez['headers']['location'], 'errno=378') !== false ) {
102
+ $result['status_code'] = BLC_LINK_STATUS_ERROR;
103
+ $result['status_text'] = __('Not Found', 'broken-link-checker');
104
+ $result['http_code'] = 0;
105
+ $result['log'] .= "The file has been removed due to a violation of MediaFire ToS.";
106
+
107
+ } elseif ( strpos($rez['headers']['location'], 'errno=388') !== false ) {
108
+ $result['status_code'] = BLC_LINK_STATUS_WARNING;
109
+ $result['status_text'] = __('Permission Denied', 'broken-link-checker');
110
+ $result['http_code'] = 0;
111
+ $result['log'] .= "Permission denied. Most likely the plugin sent too many requests too quickly. Try again later.";
112
+
113
+ } else {
114
+ $result['status_code'] = BLC_LINK_STATUS_INFO;
115
+ $result['status_text'] = __('Unknown Error', 'broken-link-checker');
116
+ $result['log'] .= "Unknown error.\n\n";
117
+ foreach($rez['headers'] as $name => $value){
118
+ $result['log'] .= sprintf("%s: %s\n", $name, $value);
119
+ }
120
+ }
121
+
122
+ } else {
123
+ $result['log'] .= "Unknown error.\n\n" . implode("\n",$rez['headers']);
124
+ }
125
+ }
126
+
127
+ //Generate the result hash (used for detecting false positives)
128
+ $result['result_hash'] = implode('|', array(
129
+ 'mediafire',
130
+ $result['http_code'],
131
+ $result['broken']?'broken':'0',
132
+ $result['timeout']?'timeout':'0'
133
+ ));
134
+
135
+ return $result;
136
+ }
137
+
138
+ /**
139
+ * Perform a HEAD request to the specified URL.
140
+ *
141
+ * Note :
142
+ *
143
+ * Since the MediaFire checker works by parsing the "Location" header, redirect following
144
+ * _must_ be disabled. This can become a problem on servers where WP is forced to fall back
145
+ * on using WP_Http_Fopen which ignores the 'redirection' flag. WP_Http_Fsockopen would work,
146
+ * but it has the lowest priority of all transports.
147
+ *
148
+ * Alas, there is no way to reliably influence which transport is chosen - the WP_Http::_getTransport
149
+ * function caches the available choices, so plugins can disable individual transports only during
150
+ * its first run. Therefore, we must pick the best transport manually.
151
+ *
152
+ * @param string $url
153
+ * @return array|WP_Error
154
+ */
155
+ function head($url){
156
+ $conf = blc_get_configuration();
157
+ $args = array(
158
+ 'timeout' => $conf->options['timeout'],
159
+ 'redirection' => 0,
160
+ '_redirection' => 0, //Internal flag that turns off redirect handling. See WP_Http::handle_redirects()
161
+ );
162
+
163
+ return wp_remote_head($url, $args);
164
+ }
165
+
166
+ }
modules/extras/plaintext-url-parser-base.php CHANGED
@@ -1,154 +1,154 @@
1
- <?php
2
-
3
- class blcPlaintextUrlBase extends blcParser {
4
- var $supported_formats = array('html', 'plaintext');
5
-
6
- //Regexp for detecting plaintext URLs lifted from make_clickable()
7
- var $url_regexp = '#(?<=[\s>\]]|^)(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/=?@\[\](+-]|[.,;:](?![\s<]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is';
8
-
9
- //Used by the edit and unlink callbacks
10
- var $old_url = '';
11
- var $new_url = '';
12
-
13
- /**
14
- * Parse a string for plaintext URLs
15
- *
16
- * @param string $content The text to parse.
17
- * @param string $base_url The base URL. Ignored.
18
- * @param string $default_link_text Default link text.
19
- * @return array An array of new blcLinkInstance objects.
20
- */
21
- function parse($content, $base_url = '', $default_link_text = ''){
22
- //Don't want to detect URLs inside links or tag attributes -
23
- //there are already other parsers for that.
24
-
25
- //Avoid <a href="http://...">http://...</a>
26
- $content = preg_replace('#<a[^>]*>.*?</a>#si', '', $content);
27
- //HTML tags are treated as natural boundaries for plaintext URLs
28
- //(since we strip tags, we must place another boundary char where they were).
29
- //The closing tag of [shortcodes] is also treated as a boundary.
30
- $content = str_replace(array('<', '>', '[/'), array("\n<", ">\n", "\n[/"), $content);
31
- //Finally, kill all tags.
32
- $content = strip_tags($content);
33
-
34
- //Find all URLs
35
- $found = preg_match_all(
36
- $this->url_regexp,
37
- $content,
38
- $matches
39
- );
40
-
41
- $instances = array();
42
-
43
- if ( $found ){
44
- //Create a new instance for each match
45
- foreach($matches[2] as $match){
46
- $url = $this->validate_url(trim($match));
47
- if ( $url == false ) {
48
- continue;
49
- }
50
-
51
- //Create a new link instance.
52
- $instance = new blcLinkInstance();
53
-
54
- $instance->set_parser($this);
55
- $instance->raw_url = $match;
56
- $instance->link_text = $match;
57
-
58
- $link_obj = new blcLink($url); //Creates or loads the link
59
- $instance->set_link($link_obj);
60
-
61
- $instances[] = $instance;
62
- }
63
- }
64
-
65
- return $instances;
66
- }
67
-
68
- /**
69
- * Validate and sanitize a URL.
70
- *
71
- * @param string $url
72
- * @return bool|string A valid URL, or false if the URL is not valid.
73
- */
74
- protected function validate_url($url) {
75
- //Do a little bit of validation
76
- $url = esc_url_raw($url);
77
- if ( empty($url) ){
78
- return false;
79
- }
80
- if ( function_exists('filter_var') ){
81
- //Note: filter_var() is no panacea as it accepts many invalid URLs
82
- if ( !filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) ){
83
- return false;
84
- }
85
- }
86
- $parts = @parse_url($url);
87
- if ( empty($parts['host']) || !strpos($parts['host'], '.') ){
88
- return false;
89
- }
90
- return $url;
91
- }
92
-
93
- /**
94
- * Change all occurrences of a given plaintext URLs to a new URL.
95
- *
96
- * @param string $content Look for URLs in this string.
97
- * @param string $new_url Change them to this URL.
98
- * @param string $old_url The URL to look for.
99
- * @param string $old_raw_url The raw, not-normalized URL. Optional.
100
- *
101
- * @return array|WP_Error If successful, the return value will be an associative array with two
102
- * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
103
- * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
104
- */
105
- function edit($content, $new_url, $old_url, $old_raw_url = ''){
106
- $this->new_url = $new_url;
107
- if ( empty($old_raw_url) ){
108
- $this->old_url = $old_url;
109
- } else {
110
- $this->old_url = $old_raw_url;
111
- }
112
-
113
- return array(
114
- 'content' => preg_replace_callback($this->url_regexp, array(&$this, 'edit_callback'), $content),
115
- 'raw_url' => $new_url,
116
- 'link_text' => $new_url,
117
- );
118
- }
119
-
120
- function edit_callback($match){
121
- if ( $match[2] == $this->old_url ){
122
- return $this->new_url;
123
- } else {
124
- return $match[0];
125
- }
126
- }
127
-
128
-
129
- /**
130
- * Remove all occurrences of a specific plaintext URL.
131
- *
132
- * @param string $content Look for URLs in this string.
133
- * @param string $url The URL to look for.
134
- * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
135
- * @return string Input string with all matching plaintext URLs removed.
136
- */
137
- function unlink($content, $url, $raw_url = ''){
138
- if ( empty($raw_url) ){
139
- $this->old_url = $url;
140
- } else {
141
- $this->old_url = $raw_url;
142
- }
143
-
144
- return preg_replace_callback($this->url_regexp, array(&$this, 'unlink_callback'), $content);
145
- }
146
-
147
- function unlink_callback($match){
148
- if ( $match[2] == $this->old_url ){
149
- return '';
150
- } else {
151
- return $match[0];
152
- }
153
- }
154
  }
1
+ <?php
2
+
3
+ class blcPlaintextUrlBase extends blcParser {
4
+ var $supported_formats = array('html', 'plaintext');
5
+
6
+ //Regexp for detecting plaintext URLs lifted from make_clickable()
7
+ var $url_regexp = '#(?<=[\s>\]]|^)(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/=?@\[\](+-]|[.,;:](?![\s<]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is';
8
+
9
+ //Used by the edit and unlink callbacks
10
+ var $old_url = '';
11
+ var $new_url = '';
12
+
13
+ /**
14
+ * Parse a string for plaintext URLs
15
+ *
16
+ * @param string $content The text to parse.
17
+ * @param string $base_url The base URL. Ignored.
18
+ * @param string $default_link_text Default link text.
19
+ * @return array An array of new blcLinkInstance objects.
20
+ */
21
+ function parse($content, $base_url = '', $default_link_text = ''){
22
+ //Don't want to detect URLs inside links or tag attributes -
23
+ //there are already other parsers for that.
24
+
25
+ //Avoid <a href="http://...">http://...</a>
26
+ $content = preg_replace('#<a[^>]*>.*?</a>#si', '', $content);
27
+ //HTML tags are treated as natural boundaries for plaintext URLs
28
+ //(since we strip tags, we must place another boundary char where they were).
29
+ //The closing tag of [shortcodes] is also treated as a boundary.
30
+ $content = str_replace(array('<', '>', '[/'), array("\n<", ">\n", "\n[/"), $content);
31
+ //Finally, kill all tags.
32
+ $content = strip_tags($content);
33
+
34
+ //Find all URLs
35
+ $found = preg_match_all(
36
+ $this->url_regexp,
37
+ $content,
38
+ $matches
39
+ );
40
+
41
+ $instances = array();
42
+
43
+ if ( $found ){
44
+ //Create a new instance for each match
45
+ foreach($matches[2] as $match){
46
+ $url = $this->validate_url(trim($match));
47
+ if ( $url == false ) {
48
+ continue;
49
+ }
50
+
51
+ //Create a new link instance.
52
+ $instance = new blcLinkInstance();
53
+
54
+ $instance->set_parser($this);
55
+ $instance->raw_url = $match;
56
+ $instance->link_text = $match;
57
+
58
+ $link_obj = new blcLink($url); //Creates or loads the link
59
+ $instance->set_link($link_obj);
60
+
61
+ $instances[] = $instance;
62
+ }
63
+ }
64
+
65
+ return $instances;
66
+ }
67
+
68
+ /**
69
+ * Validate and sanitize a URL.
70
+ *
71
+ * @param string $url
72
+ * @return bool|string A valid URL, or false if the URL is not valid.
73
+ */
74
+ protected function validate_url($url) {
75
+ //Do a little bit of validation
76
+ $url = esc_url_raw($url);
77
+ if ( empty($url) ){
78
+ return false;
79
+ }
80
+ if ( function_exists('filter_var') ){
81
+ //Note: filter_var() is no panacea as it accepts many invalid URLs
82
+ if ( !filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) ){
83
+ return false;
84
+ }
85
+ }
86
+ $parts = @parse_url($url);
87
+ if ( empty($parts['host']) || !strpos($parts['host'], '.') ){
88
+ return false;
89
+ }
90
+ return $url;
91
+ }
92
+
93
+ /**
94
+ * Change all occurrences of a given plaintext URLs to a new URL.
95
+ *
96
+ * @param string $content Look for URLs in this string.
97
+ * @param string $new_url Change them to this URL.
98
+ * @param string $old_url The URL to look for.
99
+ * @param string $old_raw_url The raw, not-normalized URL. Optional.
100
+ *
101
+ * @return array|WP_Error If successful, the return value will be an associative array with two
102
+ * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
103
+ * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
104
+ */
105
+ function edit($content, $new_url, $old_url, $old_raw_url = ''){
106
+ $this->new_url = $new_url;
107
+ if ( empty($old_raw_url) ){
108
+ $this->old_url = $old_url;
109
+ } else {
110
+ $this->old_url = $old_raw_url;
111
+ }
112
+
113
+ return array(
114
+ 'content' => preg_replace_callback($this->url_regexp, array(&$this, 'edit_callback'), $content),
115
+ 'raw_url' => $new_url,
116
+ 'link_text' => $new_url,
117
+ );
118
+ }
119
+
120
+ function edit_callback($match){
121
+ if ( $match[2] == $this->old_url ){
122
+ return $this->new_url;
123
+ } else {
124
+ return $match[0];
125
+ }
126
+ }
127
+
128
+
129
+ /**
130
+ * Remove all occurrences of a specific plaintext URL.
131
+ *
132
+ * @param string $content Look for URLs in this string.
133
+ * @param string $url The URL to look for.
134
+ * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
135
+ * @return string Input string with all matching plaintext URLs removed.
136
+ */
137
+ function unlink($content, $url, $raw_url = ''){
138
+ if ( empty($raw_url) ){
139
+ $this->old_url = $url;
140
+ } else {
141
+ $this->old_url = $raw_url;
142
+ }
143
+
144
+ return preg_replace_callback($this->url_regexp, array(&$this, 'unlink_callback'), $content);
145
+ }
146
+
147
+ function unlink_callback($match){
148
+ if ( $match[2] == $this->old_url ){
149
+ return '';
150
+ } else {
151
+ return $match[0];
152
+ }
153
+ }
154
  }
modules/extras/plaintext-url.php CHANGED
@@ -1,22 +1,22 @@
1
- <?php
2
- /*
3
- Plugin Name: Plaintext URLs
4
- Description: Parse plaintext URLs as links
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcPlaintextURL
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
-
13
- ModulePriority: 800
14
- */
15
-
16
- if ( !class_exists('blcPlaintextUrlBase') ) {
17
- require_once 'plaintext-url-parser-base.php';
18
- }
19
-
20
- class blcPlaintextURL extends blcPlaintextUrlBase {
21
-
22
  }
1
+ <?php
2
+ /*
3
+ Plugin Name: Plaintext URLs
4
+ Description: Parse plaintext URLs as links
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcPlaintextURL
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+
13
+ ModulePriority: 800
14
+ */
15
+
16
+ if ( !class_exists('blcPlaintextUrlBase') ) {
17
+ require_once 'plaintext-url-parser-base.php';
18
+ }
19
+
20
+ class blcPlaintextURL extends blcPlaintextUrlBase {
21
+
22
  }
modules/extras/rapidshare.php CHANGED
@@ -1,213 +1,213 @@
1
- <?php
2
- /*
3
- Plugin Name: RapidShare API
4
- Description: Check links to RapidShare files using the RapidShare API.
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleID: rapidshare-checker
9
- ModuleCategory: checker
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
- ModuleClassName: blcRapidShareChecker
13
- ModulePriority: 100
14
-
15
- ModuleCheckerUrlPattern: @^https?://(?:[\w\d]+\.)*rapidshare\.\w+/files/(\d+)/([^&?#/]+?)(?:$|[&?#/])@i
16
- */
17
-
18
- /**
19
- * RapidShare API link checker.
20
- *
21
- * @package Broken Link Checker
22
- * @author Janis Elsts
23
- * @access public
24
- */
25
- class blcRapidShareChecker extends blcChecker {
26
-
27
- /**
28
- * Determine if the checker can parse a specific URL.
29
- * Always returns true because the ModuleCheckerUrlPattern header constitutes sufficient verification.
30
- *
31
- * @param string $url
32
- * @param array $parsed
33
- * @return bool True.
34
- */
35
- function can_check($url, $parsed){
36
- return true;
37
- }
38
-
39
- /**
40
- * Check a RapidShare file.
41
- *
42
- * @param string $url File URL.
43
- * @return array
44
- */
45
- function check($url){
46
- $result = array(
47
- 'final_url' => $url,
48
- 'redirect_count' => 0,
49
- 'timeout' => false,
50
- 'broken' => false,
51
- 'log' => sprintf("<em>(%s)</em>\n\n", __('Using RapidShare API', 'broken-link-checker')),
52
- 'result_hash' => '',
53
- 'status_code' => '',
54
- 'status_text' => '',
55
- );
56
-
57
- //We know the URL will match because ModuleCheckerUrlPattern matched.
58
- preg_match('@^https?://(?:[\w\d]+\.)*rapidshare\.\w+/files/(\d+)/([^&?#/]+?)(?:$|[&?#/])@i', $url, $matches);
59
-
60
- $file_id = $matches[1];
61
- $file_name = $matches[2];
62
-
63
- /*
64
- We use the checkfiles function to check file status. The RapidShare API docs can be found here :
65
- http://images.rapidshare.com/apidoc.txt
66
-
67
- The relevant function is documented thusly :
68
-
69
- sub=checkfiles
70
-
71
- Description:
72
- Gets status details about a list of given files. (files parameter limited to 3000 bytes.
73
- filenames parameter limited to 30000 bytes.)
74
-
75
- Parameters:
76
- files=comma separated list of file ids
77
- filenames=comma separated list of the respective filename. Example: files=50444381,50444382 filenames=test1.rar,test2.rar
78
-
79
- Reply fields:
80
- 1:File ID
81
- 2:Filename
82
- 3:Size (in bytes. If size is 0, this file does not exist.)
83
- 4:Server ID
84
- 5:Status integer, which can have the following numeric values:
85
- 0=File not found
86
- 1=File OK
87
- 3=Server down
88
- 4=File marked as illegal
89
- 6:Short host (Use the short host to get the best download mirror: http://rs$serverid$shorthost.rapidshare.com/files/$fileid/$filename)
90
- 7:MD5 (hexadecimal)
91
-
92
- Reply format: integer,string,integer,integer,integer,string,string
93
- */
94
-
95
- $api_url = sprintf(
96
- 'http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles&files=%d&filenames=%s',
97
- $file_id,
98
- $file_name
99
- );
100
-
101
- $conf = blc_get_configuration();
102
- $args = array( 'timeout' => $conf->options['timeout'], );
103
-
104
- $start = microtime_float();
105
- $response = wp_remote_get($api_url, $args);
106
- $result['request_duration'] = microtime_float() - $start;
107
-
108
- $file_status = 0;
109
- $file_status_text = '';
110
-
111
- //Is the response valid?
112
- if ( is_wp_error($response) ){
113
- $result['log'] .= "Error : " . $response->get_error_message();
114
- $result['broken'] = true;
115
- $result['http_code'] = 0;
116
- } else {
117
- $result['http_code'] = intval($response['response']['code']);
118
-
119
- if ( $result['http_code'] == 200 ){
120
- //Parse the API response
121
- $data = explode(',', $response['body']);
122
-
123
- //Check file status
124
- if ( isset($data[4]) ){
125
-
126
- $file_status = intval($data[4]);
127
- $file_status_text = '';
128
- if ( $file_status >= 0 && $file_status <= 6 ){
129
- //Lets not confuse the user by showing the HTTP code we got from the API.
130
- //It's always "200" - whether the file exists or not.
131
- $result['http_code'] = 0;
132
- }
133
-
134
- switch( $file_status ){
135
- case 0:
136
- $file_status_text = 'File not found';
137
- $result['broken'] = true;
138
- $result['status_code'] = BLC_LINK_STATUS_ERROR;
139
- $result['status_text'] = __('Not Found', 'broken-link-checker');
140
- break;
141
-
142
- case 1:
143
- $file_status_text = 'File OK (Anonymous downloading)';
144
- $result['status_code'] = BLC_LINK_STATUS_OK;
145
- $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
146
- break;
147
-
148
- case 2:
149
- $file_status_text = 'File OK (TrafficShare direct download without any logging)';
150
- $result['status_code'] = BLC_LINK_STATUS_OK;
151
- $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
152
- break;
153
-
154
- case 3:
155
- $file_status_text = 'Server down';
156
- $result['broken'] = true;
157
- $result['status_code'] = BLC_LINK_STATUS_WARNING;
158
- $result['status_text'] = __('RS Server Down', 'broken-link-checker');
159
- break;
160
-
161
- case 4:
162
- $file_status_text = 'File marked as illegal';
163
- $result['broken'] = true;
164
- $result['status_code'] = BLC_LINK_STATUS_ERROR;
165
- $result['status_text'] = __('File Blocked', 'broken-link-checker');
166
- break;
167
-
168
- case 5:
169
- $file_status_text = 'Anonymous file locked because it has more than 10 downloads';
170
- $result['broken'] = true;
171
- $result['status_code'] = BLC_LINK_STATUS_WARNING;
172
- $result['status_text'] = __('File Locked', 'broken-link-checker');
173
- break;
174
-
175
- case 6:
176
- $file_status_text = 'File OK (TrafficShare direct download with enabled logging)';
177
- $result['status_code'] = BLC_LINK_STATUS_OK;
178
- $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
179
- break;
180
- }
181
-
182
- $result['log'] .= sprintf(
183
- __('RapidShare : %s', 'broken-link-checker'),
184
- $file_status_text
185
- );
186
-
187
- } else {
188
- $result['log'] .= sprintf(
189
- __('RapidShare API error: %s', 'broken-link-checker'),
190
- $response['body']
191
- );
192
- }
193
-
194
- } else {
195
- //Unexpected error.
196
- $result['log'] .= $response['body'];
197
- $result['broken'] = true;
198
- }
199
- }
200
-
201
- //Generate the result hash (used for detecting false positives)
202
- $result['result_hash'] = implode('|', array(
203
- 'rapidshare',
204
- $result['http_code'],
205
- $result['broken']?'broken':'0',
206
- $result['timeout']?'timeout':'0',
207
- $file_status
208
- ));
209
-
210
- return $result;
211
- }
212
-
213
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: RapidShare API
4
+ Description: Check links to RapidShare files using the RapidShare API.
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleID: rapidshare-checker
9
+ ModuleCategory: checker
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+ ModuleClassName: blcRapidShareChecker
13
+ ModulePriority: 100
14
+
15
+ ModuleCheckerUrlPattern: @^https?://(?:[\w\d]+\.)*rapidshare\.\w+/files/(\d+)/([^&?#/]+?)(?:$|[&?#/])@i
16
+ */
17
+
18
+ /**
19
+ * RapidShare API link checker.
20
+ *
21
+ * @package Broken Link Checker
22
+ * @author Janis Elsts
23
+ * @access public
24
+ */
25
+ class blcRapidShareChecker extends blcChecker {
26
+
27
+ /**
28
+ * Determine if the checker can parse a specific URL.
29
+ * Always returns true because the ModuleCheckerUrlPattern header constitutes sufficient verification.
30
+ *
31
+ * @param string $url
32
+ * @param array $parsed
33
+ * @return bool True.
34
+ */
35
+ function can_check($url, $parsed){
36
+ return true;
37
+ }
38
+
39
+ /**
40
+ * Check a RapidShare file.
41
+ *
42
+ * @param string $url File URL.
43
+ * @return array
44
+ */
45
+ function check($url){
46
+ $result = array(
47
+ 'final_url' => $url,
48
+ 'redirect_count' => 0,
49
+ 'timeout' => false,
50
+ 'broken' => false,
51
+ 'log' => sprintf("<em>(%s)</em>\n\n", __('Using RapidShare API', 'broken-link-checker')),
52
+ 'result_hash' => '',
53
+ 'status_code' => '',
54
+ 'status_text' => '',
55
+ );
56
+
57
+ //We know the URL will match because ModuleCheckerUrlPattern matched.
58
+ preg_match('@^https?://(?:[\w\d]+\.)*rapidshare\.\w+/files/(\d+)/([^&?#/]+?)(?:$|[&?#/])@i', $url, $matches);
59
+
60
+ $file_id = $matches[1];
61
+ $file_name = $matches[2];
62
+
63
+ /*
64
+ We use the checkfiles function to check file status. The RapidShare API docs can be found here :
65
+ http://images.rapidshare.com/apidoc.txt
66
+
67
+ The relevant function is documented thusly :
68
+
69
+ sub=checkfiles
70
+
71
+ Description:
72
+ Gets status details about a list of given files. (files parameter limited to 3000 bytes.
73
+ filenames parameter limited to 30000 bytes.)
74
+
75
+ Parameters:
76
+ files=comma separated list of file ids
77
+ filenames=comma separated list of the respective filename. Example: files=50444381,50444382 filenames=test1.rar,test2.rar
78
+
79
+ Reply fields:
80
+ 1:File ID
81
+ 2:Filename
82
+ 3:Size (in bytes. If size is 0, this file does not exist.)
83
+ 4:Server ID
84
+ 5:Status integer, which can have the following numeric values:
85
+ 0=File not found
86
+ 1=File OK
87
+ 3=Server down
88
+ 4=File marked as illegal
89
+ 6:Short host (Use the short host to get the best download mirror: http://rs$serverid$shorthost.rapidshare.com/files/$fileid/$filename)
90
+ 7:MD5 (hexadecimal)
91
+
92
+ Reply format: integer,string,integer,integer,integer,string,string
93
+ */
94
+
95
+ $api_url = sprintf(
96
+ 'http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles&files=%d&filenames=%s',
97
+ $file_id,
98
+ $file_name
99
+ );
100
+
101
+ $conf = blc_get_configuration();
102
+ $args = array( 'timeout' => $conf->options['timeout'], );
103
+
104
+ $start = microtime_float();
105
+ $response = wp_remote_get($api_url, $args);
106
+ $result['request_duration'] = microtime_float() - $start;
107
+
108
+ $file_status = 0;
109
+ $file_status_text = '';
110
+
111
+ //Is the response valid?
112
+ if ( is_wp_error($response) ){
113
+ $result['log'] .= "Error : " . $response->get_error_message();
114
+ $result['broken'] = true;
115
+ $result['http_code'] = 0;
116
+ } else {
117
+ $result['http_code'] = intval($response['response']['code']);
118
+
119
+ if ( $result['http_code'] == 200 ){
120
+ //Parse the API response
121
+ $data = explode(',', $response['body']);
122
+
123
+ //Check file status
124
+ if ( isset($data[4]) ){
125
+
126
+ $file_status = intval($data[4]);
127
+ $file_status_text = '';
128
+ if ( $file_status >= 0 && $file_status <= 6 ){
129
+ //Lets not confuse the user by showing the HTTP code we got from the API.
130
+ //It's always "200" - whether the file exists or not.
131
+ $result['http_code'] = 0;
132
+ }
133
+
134
+ switch( $file_status ){
135
+ case 0:
136
+ $file_status_text = 'File not found';
137
+ $result['broken'] = true;
138
+ $result['status_code'] = BLC_LINK_STATUS_ERROR;
139
+ $result['status_text'] = __('Not Found', 'broken-link-checker');
140
+ break;
141
+
142
+ case 1:
143
+ $file_status_text = 'File OK (Anonymous downloading)';
144
+ $result['status_code'] = BLC_LINK_STATUS_OK;
145
+ $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
146
+ break;
147
+
148
+ case 2:
149
+ $file_status_text = 'File OK (TrafficShare direct download without any logging)';
150
+ $result['status_code'] = BLC_LINK_STATUS_OK;
151
+ $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
152
+ break;
153
+
154
+ case 3:
155
+ $file_status_text = 'Server down';
156
+ $result['broken'] = true;
157
+ $result['status_code'] = BLC_LINK_STATUS_WARNING;
158
+ $result['status_text'] = __('RS Server Down', 'broken-link-checker');
159
+ break;
160
+
161
+ case 4:
162
+ $file_status_text = 'File marked as illegal';
163
+ $result['broken'] = true;
164
+ $result['status_code'] = BLC_LINK_STATUS_ERROR;
165
+ $result['status_text'] = __('File Blocked', 'broken-link-checker');
166
+ break;
167
+
168
+ case 5:
169
+ $file_status_text = 'Anonymous file locked because it has more than 10 downloads';
170
+ $result['broken'] = true;
171
+ $result['status_code'] = BLC_LINK_STATUS_WARNING;
172
+ $result['status_text'] = __('File Locked', 'broken-link-checker');
173
+ break;
174
+
175
+ case 6:
176
+ $file_status_text = 'File OK (TrafficShare direct download with enabled logging)';
177
+ $result['status_code'] = BLC_LINK_STATUS_OK;
178
+ $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
179
+ break;
180
+ }
181
+
182
+ $result['log'] .= sprintf(
183
+ __('RapidShare : %s', 'broken-link-checker'),
184
+ $file_status_text
185
+ );
186
+
187
+ } else {
188
+ $result['log'] .= sprintf(
189
+ __('RapidShare API error: %s', 'broken-link-checker'),
190
+ $response['body']
191
+ );
192
+ }
193
+
194
+ } else {
195
+ //Unexpected error.
196
+ $result['log'] .= $response['body'];
197
+ $result['broken'] = true;
198
+ }
199
+ }
200
+
201
+ //Generate the result hash (used for detecting false positives)
202
+ $result['result_hash'] = implode('|', array(
203
+ 'rapidshare',
204
+ $result['http_code'],
205
+ $result['broken']?'broken':'0',
206
+ $result['timeout']?'timeout':'0',
207
+ $file_status
208
+ ));
209
+
210
+ return $result;
211
+ }
212
+
213
+ }
modules/extras/smart-youtube-embed.php CHANGED
@@ -1,82 +1,82 @@
1
- <?php
2
- /*
3
- Plugin Name: Smart YouTube httpv:// URLs
4
- Description: Parse video URLs used by the Smart YouTube plugin
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcSmartYouTubeURL
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
-
13
- ModulePriority: 100
14
- */
15
-
16
- if ( !class_exists('blcPlaintextUrlBase') ) {
17
- require_once 'plaintext-url-parser-base.php';
18
- }
19
-
20
- class blcSmartYouTubeURL extends blcPlaintextUrlBase {
21
-
22
- protected function validate_url($url) {
23
- //Ignore invalid URLs.
24
- $parts = @parse_url($url);
25
- if ( empty($parts) ) {
26
- return false;
27
- }
28
-
29
- //We only care about httpv[hp]:// URLs as used by the Smart YouTube plugin.
30
- if ( stripos($parts['scheme'], 'httpv') !== 0 ) {
31
- return false;
32
- }
33
-
34
- //The URL should contain a domain name. AFAIK, Smart YouTube doesn't accept relative URLs.
35
- if ( empty($parts['host']) || !strpos($parts['host'], '.') ){
36
- return false;
37
- }
38
-
39
- //Replace the plugin-specific scheme with plain old http://.
40
- $url = preg_replace('#^httpv[^:]*?:#i', 'http:', $url);
41
-
42
- return $url;
43
- }
44
-
45
- /**
46
- * Change all occurrences of a given URLs to a new URL.
47
- *
48
- * @param string $content Look for URLs in this string.
49
- * @param string $new_url Change them to this URL.
50
- * @param string $old_url The URL to look for.
51
- * @param string $old_raw_url The raw, not-normalized URL. Optional.
52
- *
53
- * @return array|WP_Error If successful, the return value will be an associative array with two
54
- * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
55
- * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
56
- */
57
- function edit($content, $new_url, $old_url, $old_raw_url = ''){
58
- //If the user manually prefixes the URL with "httpv://" or other Smart YouTube scheme
59
- //then use the URL as-is. Otherwise change the scheme to the prefix from the old URL (if available).
60
- $new_scheme = @parse_url($new_url, PHP_URL_SCHEME);
61
- if ( empty($new_scheme) || (stripos($new_scheme, 'httpv') !== 0) ) {
62
- if ( !empty($old_raw_url) ) {
63
- $scheme = parse_url($old_raw_url, PHP_URL_SCHEME);
64
- } else {
65
- $scheme = 'httpv';
66
- }
67
-
68
- if ( empty($new_scheme) ) {
69
- $new_url = $scheme . '://' . $new_url;
70
- } else {
71
- $new_url = preg_replace(
72
- '#^' . preg_quote($new_scheme) . '://#i',
73
- $scheme . '://',
74
- $new_url
75
- );
76
- }
77
- }
78
-
79
- return parent::edit($content, $new_url, $old_url, $old_raw_url);
80
- }
81
-
82
  }
1
+ <?php
2
+ /*
3
+ Plugin Name: Smart YouTube httpv:// URLs
4
+ Description: Parse video URLs used by the Smart YouTube plugin
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcSmartYouTubeURL
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+
13
+ ModulePriority: 100
14
+ */
15
+
16
+ if ( !class_exists('blcPlaintextUrlBase') ) {
17
+ require_once 'plaintext-url-parser-base.php';
18
+ }
19
+
20
+ class blcSmartYouTubeURL extends blcPlaintextUrlBase {
21
+
22
+ protected function validate_url($url) {
23
+ //Ignore invalid URLs.
24
+ $parts = @parse_url($url);
25
+ if ( empty($parts) ) {
26
+ return false;
27
+ }
28
+
29
+ //We only care about httpv[hp]:// URLs as used by the Smart YouTube plugin.
30
+ if ( stripos($parts['scheme'], 'httpv') !== 0 ) {
31
+ return false;
32
+ }
33
+
34
+ //The URL should contain a domain name. AFAIK, Smart YouTube doesn't accept relative URLs.
35
+ if ( empty($parts['host']) || !strpos($parts['host'], '.') ){
36
+ return false;
37
+ }
38
+
39
+ //Replace the plugin-specific scheme with plain old http://.
40
+ $url = preg_replace('#^httpv[^:]*?:#i', 'http:', $url);
41
+
42
+ return $url;
43
+ }
44
+
45
+ /**
46
+ * Change all occurrences of a given URLs to a new URL.
47
+ *
48
+ * @param string $content Look for URLs in this string.
49
+ * @param string $new_url Change them to this URL.
50
+ * @param string $old_url The URL to look for.
51
+ * @param string $old_raw_url The raw, not-normalized URL. Optional.
52
+ *
53
+ * @return array|WP_Error If successful, the return value will be an associative array with two
54
+ * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
55
+ * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
56
+ */
57
+ function edit($content, $new_url, $old_url, $old_raw_url = ''){
58
+ //If the user manually prefixes the URL with "httpv://" or other Smart YouTube scheme
59
+ //then use the URL as-is. Otherwise change the scheme to the prefix from the old URL (if available).
60
+ $new_scheme = @parse_url($new_url, PHP_URL_SCHEME);
61
+ if ( empty($new_scheme) || (stripos($new_scheme, 'httpv') !== 0) ) {
62
+ if ( !empty($old_raw_url) ) {
63
+ $scheme = parse_url($old_raw_url, PHP_URL_SCHEME);
64
+ } else {
65
+ $scheme = 'httpv';
66
+ }
67
+
68
+ if ( empty($new_scheme) ) {
69
+ $new_url = $scheme . '://' . $new_url;
70
+ } else {
71
+ $new_url = preg_replace(
72
+ '#^' . preg_quote($new_scheme) . '://#i',
73
+ $scheme . '://',
74
+ $new_url
75
+ );
76
+ }
77
+ }
78
+
79
+ return parent::edit($content, $new_url, $old_url, $old_raw_url);
80
+ }
81
+
82
  }
modules/extras/vimeo-embed.php CHANGED
@@ -1,47 +1,47 @@
1
- <?php
2
- /*
3
- Plugin Name: Embedded Vimeo videos
4
- Description: Parse embedded videos from Vimeo
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcVimeoEmbed
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
- */
13
-
14
- if ( !class_exists('blcEmbedParserBase') ){
15
- require 'embed-parser-base.php';
16
- }
17
-
18
- class blcVimeoEmbed extends blcEmbedParserBase {
19
- var $supported_formats = array('html');
20
-
21
- function init(){
22
- parent::init();
23
- $this->url_search_string = 'vimeo.com/moogaloop.swf?';
24
- $this->short_title = __('Vimeo Video', 'broken-link-checker');
25
- $this->long_title = __('Embedded Vimeo video', 'broken-link-checker');
26
- }
27
-
28
- function link_url_from_src($src){
29
- //Extract video ID from the SRC
30
- $components = @parse_url($src);
31
- if ( empty($components['query']) ) {
32
- return '';
33
- }
34
-
35
- parse_str($components['query'], $query);
36
- if ( empty($query['clip_id']) ){
37
- return '';
38
- } else {
39
- $video_id = $query['clip_id'];
40
- }
41
-
42
- //Reconstruct the video permalink based on the ID
43
- $url = 'http://vimeo.com/'.$video_id;
44
-
45
- return $url;
46
- }
47
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: Embedded Vimeo videos
4
+ Description: Parse embedded videos from Vimeo
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcVimeoEmbed
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+ */
13
+
14
+ if ( !class_exists('blcEmbedParserBase') ){
15
+ require 'embed-parser-base.php';
16
+ }
17
+
18
+ class blcVimeoEmbed extends blcEmbedParserBase {
19
+ var $supported_formats = array('html');
20
+
21
+ function init(){
22
+ parent::init();
23
+ $this->url_search_string = 'vimeo.com/moogaloop.swf?';
24
+ $this->short_title = __('Vimeo Video', 'broken-link-checker');
25
+ $this->long_title = __('Embedded Vimeo video', 'broken-link-checker');
26
+ }
27
+
28
+ function link_url_from_src($src){
29
+ //Extract video ID from the SRC
30
+ $components = @parse_url($src);
31
+ if ( empty($components['query']) ) {
32
+ return '';
33
+ }
34
+
35
+ parse_str($components['query'], $query);
36
+ if ( empty($query['clip_id']) ){
37
+ return '';
38
+ } else {
39
+ $video_id = $query['clip_id'];
40
+ }
41
+
42
+ //Reconstruct the video permalink based on the ID
43
+ $url = 'http://vimeo.com/'.$video_id;
44
+
45
+ return $url;
46
+ }
47
+ }
modules/extras/youtube-embed.php CHANGED
@@ -1,39 +1,39 @@
1
- <?php
2
- /*
3
- Plugin Name: Embedded YouTube videos (old embed code)
4
- Description: Parse embedded videos from YouTube
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcYouTubeEmbed
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
-
13
- ModulePriority: 110
14
- */
15
-
16
- if ( !class_exists('blcEmbedParserBase') ){
17
- require 'embed-parser-base.php';
18
- }
19
-
20
- class blcYouTubeEmbed extends blcEmbedParserBase {
21
-
22
- function init(){
23
- parent::init();
24
- $this->short_title = __('YouTube Video', 'broken-link-checker');
25
- $this->long_title = __('Embedded YouTube video', 'broken-link-checker');
26
- $this->url_search_string = 'youtube.com/v/';
27
- }
28
-
29
- function link_url_from_src($src){
30
- //Extract video ID from the SRC. The ID is always 11 characters.
31
- $parts = explode('/', $src);
32
- $video_id = substr( end($parts), 0, 11 );
33
-
34
- //Reconstruct the video permalink based on the ID
35
- $url = 'http://www.youtube.com/watch?v='.$video_id;
36
-
37
- return $url;
38
- }
39
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: Embedded YouTube videos (old embed code)
4
+ Description: Parse embedded videos from YouTube
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcYouTubeEmbed
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+
13
+ ModulePriority: 110
14
+ */
15
+
16
+ if ( !class_exists('blcEmbedParserBase') ){
17
+ require 'embed-parser-base.php';
18
+ }
19
+
20
+ class blcYouTubeEmbed extends blcEmbedParserBase {
21
+
22
+ function init(){
23
+ parent::init();
24
+ $this->short_title = __('YouTube Video', 'broken-link-checker');
25
+ $this->long_title = __('Embedded YouTube video', 'broken-link-checker');
26
+ $this->url_search_string = 'youtube.com/v/';
27
+ }
28
+
29
+ function link_url_from_src($src){
30
+ //Extract video ID from the SRC. The ID is always 11 characters.
31
+ $parts = explode('/', $src);
32
+ $video_id = substr( end($parts), 0, 11 );
33
+
34
+ //Reconstruct the video permalink based on the ID
35
+ $url = 'http://www.youtube.com/watch?v='.$video_id;
36
+
37
+ return $url;
38
+ }
39
+ }
modules/extras/youtube-iframe.php CHANGED
@@ -1,103 +1,103 @@
1
- <?php
2
- /*
3
- Plugin Name: Embedded YouTube videos
4
- Description: Parse embedded videos from YouTube
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcYouTubeIframe
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
-
13
- ModulePriority: 120
14
- */
15
-
16
- if ( !class_exists('blcEmbedParserBase') ){
17
- require 'embed-parser-base.php';
18
- }
19
-
20
- class blcYouTubeIframe extends blcEmbedParserBase {
21
- var $supported_formats = array('html');
22
-
23
- function init(){
24
- parent::init();
25
- $this->short_title = __('YouTube Video', 'broken-link-checker');
26
- $this->long_title = __('Embedded YouTube video', 'broken-link-checker');
27
- $this->url_search_string = 'youtube.com/embed/';
28
- }
29
-
30
- /**
31
- * Extract embedded elements from a HTML string.
32
- *
33
- * Returns an array of IFrame elements found in the input string.
34
- * Elements without a 'src' attribute are skipped.
35
- *
36
- * Each array item has the same basic structure as the array items
37
- * returned by blcUtility::extract_tags(), plus an additional 'embed_code' key
38
- * that contains the full HTML code for the entire <ifram> tag.
39
- *
40
- * @uses blcUtility::extract_tags() This function is a simple wrapper around extract_tags()
41
- *
42
- * @param string $html
43
- * @return array
44
- */
45
- function extract_embeds($html){
46
- $results = array();
47
-
48
- //remove all <code></code> blocks first
49
- $html = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $html);
50
-
51
- //Find likely-looking <iframe> elements
52
- $iframes = blcUtility::extract_tags($html, 'iframe', false, true);
53
- foreach($iframes as $embed){
54
- if ( empty($embed['attributes']['src']) ){
55
- continue;
56
- }
57
-
58
- $embed['embed_code'] = $embed['full_tag'];
59
-
60
- $results[] = $embed;
61
- }
62
-
63
- return $results;
64
- }
65
-
66
- function link_url_from_src($src){
67
- $parts = @parse_url($src);
68
- if ( empty($parts) || !isset($parts['path']) ) {
69
- return null;
70
- }
71
-
72
- //Is this a playlist?
73
- if ( strpos($parts['path'], 'videoseries') !== false ) {
74
-
75
- //Extract the playlist ID from the query string.
76
- if ( !isset($parts['query']) || empty($parts['query']) ) {
77
- return null;
78
- }
79
- parse_str($parts['query'], $query);
80
- if ( !isset($query['list']) || empty($query['list']) ) {
81
- return null;
82
- }
83
-
84
- $playlist_id = $query['list'];
85
- if ( substr($playlist_id, 0, 2) === 'PL' ) {
86
- $playlist_id = substr($playlist_id, 2);
87
- }
88
-
89
- //Reconstruct the playlist URL.
90
- $url = 'http://www.youtube.com/playlist?list=' . $playlist_id;
91
-
92
- } else {
93
- //Extract video ID from the SRC. The ID is always 11 characters.
94
- $exploded = explode('/', $parts['path']);
95
- $video_id = substr( end($exploded), 0, 11 );
96
-
97
- //Reconstruct the video permalink based on the ID
98
- $url = 'http://www.youtube.com/watch?v='.$video_id;
99
- }
100
-
101
- return $url;
102
- }
103
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: Embedded YouTube videos
4
+ Description: Parse embedded videos from YouTube
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcYouTubeIframe
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+
13
+ ModulePriority: 120
14
+ */
15
+
16
+ if ( !class_exists('blcEmbedParserBase') ){
17
+ require 'embed-parser-base.php';
18
+ }
19
+
20
+ class blcYouTubeIframe extends blcEmbedParserBase {
21
+ var $supported_formats = array('html');
22
+
23
+ function init(){
24
+ parent::init();
25
+ $this->short_title = __('YouTube Video', 'broken-link-checker');
26
+ $this->long_title = __('Embedded YouTube video', 'broken-link-checker');
27
+ $this->url_search_string = 'youtube.com/embed/';
28
+ }
29
+
30
+ /**
31
+ * Extract embedded elements from a HTML string.
32
+ *
33
+ * Returns an array of IFrame elements found in the input string.
34
+ * Elements without a 'src' attribute are skipped.
35
+ *
36
+ * Each array item has the same basic structure as the array items
37
+ * returned by blcUtility::extract_tags(), plus an additional 'embed_code' key
38
+ * that contains the full HTML code for the entire <ifram> tag.
39
+ *
40
+ * @uses blcUtility::extract_tags() This function is a simple wrapper around extract_tags()
41
+ *
42
+ * @param string $html
43
+ * @return array
44
+ */
45
+ function extract_embeds($html){
46
+ $results = array();
47
+
48
+ //remove all <code></code> blocks first
49
+ $html = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $html);
50
+
51
+ //Find likely-looking <iframe> elements
52
+ $iframes = blcUtility::extract_tags($html, 'iframe', false, true);
53
+ foreach($iframes as $embed){
54
+ if ( empty($embed['attributes']['src']) ){
55
+ continue;
56
+ }
57
+
58
+ $embed['embed_code'] = $embed['full_tag'];
59
+
60
+ $results[] = $embed;
61
+ }
62
+
63
+ return $results;
64
+ }
65
+
66
+ function link_url_from_src($src){
67
+ $parts = @parse_url($src);
68
+ if ( empty($parts) || !isset($parts['path']) ) {
69
+ return null;
70
+ }
71
+
72
+ //Is this a playlist?
73
+ if ( strpos($parts['path'], 'videoseries') !== false ) {
74
+
75
+ //Extract the playlist ID from the query string.
76
+ if ( !isset($parts['query']) || empty($parts['query']) ) {
77
+ return null;
78
+ }
79
+ parse_str($parts['query'], $query);
80
+ if ( !isset($query['list']) || empty($query['list']) ) {
81
+ return null;
82
+ }
83
+
84
+ $playlist_id = $query['list'];
85
+ if ( substr($playlist_id, 0, 2) === 'PL' ) {
86
+ $playlist_id = substr($playlist_id, 2);
87
+ }
88
+
89
+ //Reconstruct the playlist URL.
90
+ $url = 'http://www.youtube.com/playlist?list=' . $playlist_id;
91
+
92
+ } else {
93
+ //Extract video ID from the SRC. The ID is always 11 characters.
94
+ $exploded = explode('/', $parts['path']);
95
+ $video_id = substr( end($exploded), 0, 11 );
96
+
97
+ //Reconstruct the video permalink based on the ID
98
+ $url = 'http://www.youtube.com/watch?v='.$video_id;
99
+ }
100
+
101
+ return $url;
102
+ }
103
+ }
modules/extras/youtube-playlist-embed.php CHANGED
@@ -1,47 +1,47 @@
1
- <?php
2
- /*
3
- Plugin Name: Embedded YouTube playlists (old embed code)
4
- Description: Parse embedded playlists from YouTube
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleCategory: parser
9
- ModuleClassName: blcYouTubePlaylistEmbed
10
- ModuleContext: on-demand
11
- ModuleLazyInit: true
12
-
13
- ModulePriority: 110
14
- */
15
-
16
- if ( !class_exists('blcEmbedParserBase') ){
17
- require 'embed-parser-base.php';
18
- }
19
-
20
- class blcYouTubePlaylistEmbed extends blcEmbedParserBase {
21
-
22
- function init(){
23
- parent::init();
24
- $this->short_title = __('YouTube Playlist', 'broken-link-checker');
25
- $this->long_title = __('Embedded YouTube playlist', 'broken-link-checker');
26
- $this->url_search_string = 'youtube.com/p/';
27
- }
28
-
29
- function link_url_from_src($src){
30
- //Extract playlist ID from the SRC.
31
- $path = parse_url($src, PHP_URL_PATH);
32
- if ( empty($path) ) {
33
- return null;
34
- }
35
-
36
- if ( preg_match('@/p/(?P<id>[^/?&#]+?)(?:[?&#]|$)@', trim($path), $matches) ) {
37
- $playlist_id = $matches['id'];
38
- } else {
39
- return null;
40
- }
41
-
42
- //Reconstruct the playlist permalink based on the ID
43
- $url = 'http://www.youtube.com/playlist?list=' . $playlist_id;
44
-
45
- return $url;
46
- }
47
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: Embedded YouTube playlists (old embed code)
4
+ Description: Parse embedded playlists from YouTube
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleCategory: parser
9
+ ModuleClassName: blcYouTubePlaylistEmbed
10
+ ModuleContext: on-demand
11
+ ModuleLazyInit: true
12
+
13
+ ModulePriority: 110
14
+ */
15
+
16
+ if ( !class_exists('blcEmbedParserBase') ){
17
+ require 'embed-parser-base.php';
18
+ }
19
+
20
+ class blcYouTubePlaylistEmbed extends blcEmbedParserBase {
21
+
22
+ function init(){
23
+ parent::init();
24
+ $this->short_title = __('YouTube Playlist', 'broken-link-checker');
25
+ $this->long_title = __('Embedded YouTube playlist', 'broken-link-checker');
26
+ $this->url_search_string = 'youtube.com/p/';
27
+ }
28
+
29
+ function link_url_from_src($src){
30
+ //Extract playlist ID from the SRC.
31
+ $path = parse_url($src, PHP_URL_PATH);
32
+ if ( empty($path) ) {
33
+ return null;
34
+ }
35
+
36
+ if ( preg_match('@/p/(?P<id>[^/?&#]+?)(?:[?&#]|$)@', trim($path), $matches) ) {
37
+ $playlist_id = $matches['id'];
38
+ } else {
39
+ return null;
40
+ }
41
+
42
+ //Reconstruct the playlist permalink based on the ID
43
+ $url = 'http://www.youtube.com/playlist?list=' . $playlist_id;
44
+
45
+ return $url;
46
+ }
47
+ }
modules/extras/youtube.php CHANGED
@@ -1,285 +1,285 @@
1
- <?php
2
-
3
- /*
4
- Plugin Name: YouTube API
5
- Description: Check links to YouTube videos and playlists using the YouTube API.
6
- Version: 3
7
- Author: Janis Elsts
8
-
9
- ModuleID: youtube-checker
10
- ModuleCategory: checker
11
- ModuleContext: on-demand
12
- ModuleLazyInit: true
13
- ModuleClassName: blcYouTubeChecker
14
- ModulePriority: 100
15
-
16
- ModuleCheckerUrlPattern: @^https?://(?:([\w\d]+\.)*youtube\.[^/]+/watch\?.*v=[^/#]|youtu\.be/[^/#\?]+|(?:[\w\d]+\.)*?youtube\.[^/]+/(playlist|view_play_list)\?[^/#]{15,}?)@i
17
- */
18
-
19
- class blcYouTubeChecker extends blcChecker {
20
- var $youtube_developer_key = 'AIzaSyAyye_rE5jYd7VpwvcLNItXQCo5zxVvMFY';
21
- var $api_grace_period = 0.3; //How long to wait between YouTube API requests.
22
- var $last_api_request = 0; //Timestamp of the last request.
23
-
24
- function can_check($url, $parsed){
25
- return true;
26
- }
27
-
28
- function check($url){
29
- //Throttle API requests to avoid getting blocked due to quota violation.
30
- $delta = microtime_float() - $this->last_api_request;
31
- if ( $delta < $this->api_grace_period ) {
32
- usleep(($this->api_grace_period - $delta) * 1000000);
33
- }
34
-
35
- $result = array(
36
- 'final_url' => $url,
37
- 'redirect_count' => 0,
38
- 'timeout' => false,
39
- 'broken' => false,
40
- 'log' => "<em>(Using YouTube API)</em>\n\n",
41
- 'result_hash' => '',
42
- );
43
-
44
- $components = @parse_url($url);
45
- if ( isset($components['query']) ) {
46
- parse_str($components['query'], $query);
47
- } else {
48
- $query = array();
49
- }
50
-
51
- //Extract the video or playlist ID from the URL
52
- $video_id = $playlist_id = null;
53
- if ( strtolower($components['host']) === 'youtu.be' ) {
54
- $video_id = trim($components['path'], '/');
55
- } else if ( (strpos($components['path'], 'watch') !== false) && isset($query['v']) ) {
56
- $video_id = $query['v'];
57
- } else if ( $components['path'] == '/playlist' ) {
58
- $playlist_id = $query['list'];
59
- } else if ( $components['path'] == '/view_play_list' ) {
60
- $playlist_id = $query['p'];
61
- }
62
-
63
- if ( empty($playlist_id) && empty($video_id) ) {
64
- $result['status_text'] = 'Unsupported URL Syntax';
65
- $result['status_code'] = BLC_LINK_STATUS_UNKNOWN;
66
- return $result;
67
- }
68
-
69
- //Fetch video or playlist from the YouTube API
70
- if ( !empty($video_id) ) {
71
- $api_url = $this->get_video_resource_url($video_id);
72
- } else {
73
- $api_url = $this->get_playlist_resource_url($playlist_id);
74
- }
75
-
76
- $conf = blc_get_configuration();
77
- $args = array( 'timeout' => $conf->options['timeout'], );
78
-
79
- $start = microtime_float();
80
- $response = wp_remote_get($api_url, $args);
81
- $result['request_duration'] = microtime_float() - $start;
82
- $this->last_api_request = $start;
83
-
84
- //Got anything?
85
- if ( is_wp_error($response) ){
86
- $result['log'] .= "Error.\n" . $response->get_error_message();
87
- //WP doesn't make it easy to distinguish between different internal errors.
88
- $result['broken'] = true;
89
- $result['http_code'] = 0;
90
- } else {
91
- $result['http_code'] = intval($response['response']['code']);
92
-
93
- if ( !empty($video_id) ) {
94
- $result = $this->check_video($response, $result);
95
- } else {
96
- $result = $this->check_playlist($response, $result);
97
- }
98
- }
99
-
100
- //The hash should contain info about all pieces of data that pertain to determining if the
101
- //link is working.
102
- $result['result_hash'] = implode('|', array(
103
- 'youtube',
104
- $result['http_code'],
105
- $result['broken']?'broken':'0',
106
- $result['timeout']?'timeout':'0',
107
- isset($result['state_name']) ? $result['state_name'] : '-',
108
- isset($result['state_reason']) ? $result['state_reason'] : '-',
109
- ));
110
-
111
- return $result;
112
- }
113
-
114
- /**
115
- * Check API response for a single video.
116
- *
117
- * @param array $response WP HTTP API response.
118
- * @param array $result Current result array.
119
- * @return array New result array.
120
- */
121
- protected function check_video($response, $result) {
122
- $api = json_decode($response['body'], true);
123
- $videoFound = ($result['http_code'] == 200) && isset($api['items'], $api['items'][0]);
124
-
125
- if ( isset($api['error']) && ($result['http_code'] != 404) ) { //404's are handled later.
126
- $result['status_code'] = BLC_LINK_STATUS_WARNING;
127
- $result['warning'] = true;
128
-
129
- if ( isset($api['error']['message']) ) {
130
- $result['status_text'] = $api['error']['message'];
131
- } else {
132
- $result['status_text'] = __('Unknown Error', 'broken-link-checker');
133
- }
134
- $result['log'] .= $this->format_api_error($response, $api);
135
-
136
- } else if ( $videoFound ) {
137
- $result['log'] .= __("Video OK", 'broken-link-checker');
138
- $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
139
- $result['status_code'] = BLC_LINK_STATUS_OK;
140
- $result['http_code'] = 0;
141
-
142
- //Add the video title to the log, purely for information.
143
- if ( isset($api['items'][0]['snippet']['title']) ) {
144
- $title = $api['items'][0]['snippet']['title'];
145
- $result['log'] .= "\n\nTitle : \"" . htmlentities($title) . '"';
146
- }
147
-
148
- } else {
149
- $result['log'] .= __('Video Not Found', 'broken-link-checker');
150
- $result['broken'] = true;
151
- $result['http_code'] = 0;
152
- $result['status_text'] = __('Video Not Found', 'broken-link-checker');
153
- $result['status_code'] = BLC_LINK_STATUS_ERROR;
154
- }
155
-
156
- return $result;
157
- }
158
-
159
- /**
160
- * Check a YouTube API response that contains a single playlist.
161
- *
162
- * @param array $response
163
- * @param array $result
164
- * @return array
165
- */
166
- protected function check_playlist($response, $result) {
167
- $api = json_decode($response['body'], true);
168
-
169
- if ( $result['http_code'] == 404 ) {
170
- //Not found.
171
- $result['log'] .= __('Playlist Not Found', 'broken-link-checker');
172
- $result['broken'] = true;
173
- $result['http_code'] = 0;
174
- $result['status_text'] = __('Playlist Not Found', 'broken-link-checker');
175
- $result['status_code'] = BLC_LINK_STATUS_ERROR;
176
-
177
- } else if ( $result['http_code'] == 403 ) {
178
- //Forbidden. We're unlikely to see this code for playlists, but lets allow it.
179
- $result['log'] .= htmlentities($response['body']);
180
- $result['broken'] = true;
181
- $result['status_text'] = __('Playlist Restricted', 'broken-link-checker');
182
- $result['status_code'] = BLC_LINK_STATUS_ERROR;
183
-
184
- } else if ( ($result['http_code'] == 200) && isset($api['items']) && is_array($api['items']) ) {
185
- //The playlist exists.
186
- if ( empty($api['items']) ) {
187
- //An empty playlist. It is possible that all of the videos have been deleted.
188
- $result['log'] .= __("This playlist has no entries or all entries have been deleted.", 'broken-link-checker');
189
- $result['status_text'] = _x('Empty Playlist', 'link status', 'broken-link-checker');
190
- $result['status_code'] = BLC_LINK_STATUS_WARNING;
191
- $result['http_code'] = 0;
192
- $result['broken'] = true;
193
- } else {
194
- //Treat the playlist as broken if at least one video is inaccessible.
195
- foreach($api['items'] as $video) {
196
- $is_private = isset($video['status']['privacyStatus']) && ($video['status']['privacyStatus'] == 'private');
197
- if ( $is_private ) {
198
- $result['log'] .= sprintf(
199
- __('Video status : %s%s', 'broken-link-checker'),
200
- $video['status']['privacyStatus'],
201
- ''
202
- );
203
-
204
- $result['broken'] = true;
205
- $result['status_text'] = __('Video Restricted', 'broken-link-checker');
206
- $result['status_code'] = BLC_LINK_STATUS_WARNING;
207
- $result['http_code'] = 0;
208
- break;
209
- }
210
- }
211
-
212
- if ( !$result['broken'] ) {
213
- //All is well.
214
- $result['log'] .= __("Playlist OK", 'broken-link-checker');
215
- $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
216
- $result['status_code'] = BLC_LINK_STATUS_OK;
217
- $result['http_code'] = 0;
218
- }
219
- }
220
-
221
- } else {
222
- //Some other error.
223
- $result['status_code'] = BLC_LINK_STATUS_WARNING;
224
- $result['warning'] = true;
225
-
226
- if ( isset($api['error']['message']) ) {
227
- $result['status_text'] = $api['error']['message'];
228
- } else {
229
- $result['status_text'] = __('Unknown Error', 'broken-link-checker');
230
- }
231
- $result['log'] .= $this->format_api_error($response, $api);
232
- }
233
-
234
- return $result;
235
- }
236
-
237
- protected function get_video_resource_url($video_id) {
238
- $params = array(
239
- 'part' => 'status,snippet',
240
- 'id' => $video_id,
241
- 'key' => $this->youtube_developer_key,
242
- );
243
- $params = array_map('urlencode', $params);
244
- return 'https://www.googleapis.com/youtube/v3/videos?' . build_query($params);
245
- }
246
-
247
- protected function get_playlist_resource_url($playlist_id) {
248
- if ( strpos($playlist_id, 'PL') === 0 ) {
249
- $playlist_id = substr($playlist_id, 2);
250
- }
251
- $params = array(
252
- 'key' => $this->youtube_developer_key,
253
- 'playlistId' => $playlist_id,
254
- 'part' => 'snippet,status',
255
- 'maxResults' => 10, //Playlists can be big. Lets just check the first few videos.
256
- );
257
- $query = build_query(array_map('urlencode', $params));
258
- return 'https://www.googleapis.com/youtube/v3/playlistItems?' . $query;
259
- }
260
-
261
- protected function format_api_error($response, $api) {
262
- $log = $response['response']['code'] . ' ' . $response['response']['message'];
263
- $log .= "\n" . __('Unknown YouTube API response received.');
264
-
265
- //Log error details.
266
- if ( isset($api['error']['errors']) && is_array($api['error']['errors']) ) {
267
- foreach($api['error']['errors'] as $error) {
268
- $log .= "\n---\n";
269
-
270
- if (is_array($error)) {
271
- foreach($error as $key => $value) {
272
- $log .= sprintf(
273
- "%s: %s\n",
274
- htmlentities($key),
275
- htmlentities($value)
276
- );
277
- }
278
- }
279
- }
280
- }
281
-
282
- return $log;
283
- }
284
-
285
- }
1
+ <?php
2
+
3
+ /*
4
+ Plugin Name: YouTube API
5
+ Description: Check links to YouTube videos and playlists using the YouTube API.
6
+ Version: 3
7
+ Author: Janis Elsts
8
+
9
+ ModuleID: youtube-checker
10
+ ModuleCategory: checker
11
+ ModuleContext: on-demand
12
+ ModuleLazyInit: true
13
+ ModuleClassName: blcYouTubeChecker
14
+ ModulePriority: 100
15
+
16
+ ModuleCheckerUrlPattern: @^https?://(?:([\w\d]+\.)*youtube\.[^/]+/watch\?.*v=[^/#]|youtu\.be/[^/#\?]+|(?:[\w\d]+\.)*?youtube\.[^/]+/(playlist|view_play_list)\?[^/#]{15,}?)@i
17
+ */
18
+
19
+ class blcYouTubeChecker extends blcChecker {
20
+ var $youtube_developer_key = 'AIzaSyAyye_rE5jYd7VpwvcLNItXQCo5zxVvMFY';
21
+ var $api_grace_period = 0.3; //How long to wait between YouTube API requests.
22
+ var $last_api_request = 0; //Timestamp of the last request.
23
+
24
+ function can_check($url, $parsed){
25
+ return true;
26
+ }
27
+
28
+ function check($url){
29
+ //Throttle API requests to avoid getting blocked due to quota violation.
30
+ $delta = microtime_float() - $this->last_api_request;
31
+ if ( $delta < $this->api_grace_period ) {
32
+ usleep(($this->api_grace_period - $delta) * 1000000);
33
+ }
34
+
35
+ $result = array(
36
+ 'final_url' => $url,
37
+ 'redirect_count' => 0,
38
+ 'timeout' => false,
39
+ 'broken' => false,
40
+ 'log' => "<em>(Using YouTube API)</em>\n\n",
41
+ 'result_hash' => '',
42
+ );
43
+
44
+ $components = @parse_url($url);
45
+ if ( isset($components['query']) ) {
46
+ parse_str($components['query'], $query);
47
+ } else {
48
+ $query = array();
49
+ }
50
+
51
+ //Extract the video or playlist ID from the URL
52
+ $video_id = $playlist_id = null;
53
+ if ( strtolower($components['host']) === 'youtu.be' ) {
54
+ $video_id = trim($components['path'], '/');
55
+ } else if ( (strpos($components['path'], 'watch') !== false) && isset($query['v']) ) {
56
+ $video_id = $query['v'];
57
+ } else if ( $components['path'] == '/playlist' ) {
58
+ $playlist_id = $query['list'];
59
+ } else if ( $components['path'] == '/view_play_list' ) {
60
+ $playlist_id = $query['p'];
61
+ }
62
+
63
+ if ( empty($playlist_id) && empty($video_id) ) {
64
+ $result['status_text'] = 'Unsupported URL Syntax';
65
+ $result['status_code'] = BLC_LINK_STATUS_UNKNOWN;
66
+ return $result;
67
+ }
68
+
69
+ //Fetch video or playlist from the YouTube API
70
+ if ( !empty($video_id) ) {
71
+ $api_url = $this->get_video_resource_url($video_id);
72
+ } else {
73
+ $api_url = $this->get_playlist_resource_url($playlist_id);
74
+ }
75
+
76
+ $conf = blc_get_configuration();
77
+ $args = array( 'timeout' => $conf->options['timeout'], );
78
+
79
+ $start = microtime_float();
80
+ $response = wp_remote_get($api_url, $args);
81
+ $result['request_duration'] = microtime_float() - $start;
82
+ $this->last_api_request = $start;
83
+
84
+ //Got anything?
85
+ if ( is_wp_error($response) ){
86
+ $result['log'] .= "Error.\n" . $response->get_error_message();
87
+ //WP doesn't make it easy to distinguish between different internal errors.
88
+ $result['broken'] = true;
89
+ $result['http_code'] = 0;
90
+ } else {
91
+ $result['http_code'] = intval($response['response']['code']);
92
+
93
+ if ( !empty($video_id) ) {
94
+ $result = $this->check_video($response, $result);
95
+ } else {
96
+ $result = $this->check_playlist($response, $result);
97
+ }
98
+ }
99
+
100
+ //The hash should contain info about all pieces of data that pertain to determining if the
101
+ //link is working.
102
+ $result['result_hash'] = implode('|', array(
103
+ 'youtube',
104
+ $result['http_code'],
105
+ $result['broken']?'broken':'0',
106
+ $result['timeout']?'timeout':'0',
107
+ isset($result['state_name']) ? $result['state_name'] : '-',
108
+ isset($result['state_reason']) ? $result['state_reason'] : '-',
109
+ ));
110
+
111
+ return $result;
112
+ }
113
+
114
+ /**
115
+ * Check API response for a single video.
116
+ *
117
+ * @param array $response WP HTTP API response.
118
+ * @param array $result Current result array.
119
+ * @return array New result array.
120
+ */
121
+ protected function check_video($response, $result) {
122
+ $api = json_decode($response['body'], true);
123
+ $videoFound = ($result['http_code'] == 200) && isset($api['items'], $api['items'][0]);
124
+
125
+ if ( isset($api['error']) && ($result['http_code'] != 404) ) { //404's are handled later.
126
+ $result['status_code'] = BLC_LINK_STATUS_WARNING;
127
+ $result['warning'] = true;
128
+
129
+ if ( isset($api['error']['message']) ) {
130
+ $result['status_text'] = $api['error']['message'];
131
+ } else {
132
+ $result['status_text'] = __('Unknown Error', 'broken-link-checker');
133
+ }
134
+ $result['log'] .= $this->format_api_error($response, $api);
135
+
136
+ } else if ( $videoFound ) {
137
+ $result['log'] .= __("Video OK", 'broken-link-checker');
138
+ $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
139
+ $result['status_code'] = BLC_LINK_STATUS_OK;
140
+ $result['http_code'] = 0;
141
+
142
+ //Add the video title to the log, purely for information.
143
+ if ( isset($api['items'][0]['snippet']['title']) ) {
144
+ $title = $api['items'][0]['snippet']['title'];
145
+ $result['log'] .= "\n\nTitle : \"" . htmlentities($title) . '"';
146
+ }
147
+
148
+ } else {
149
+ $result['log'] .= __('Video Not Found', 'broken-link-checker');
150
+ $result['broken'] = true;
151
+ $result['http_code'] = 0;
152
+ $result['status_text'] = __('Video Not Found', 'broken-link-checker');
153
+ $result['status_code'] = BLC_LINK_STATUS_ERROR;
154
+ }
155
+
156
+ return $result;
157
+ }
158
+
159
+ /**
160
+ * Check a YouTube API response that contains a single playlist.
161
+ *
162
+ * @param array $response
163
+ * @param array $result
164
+ * @return array
165
+ */
166
+ protected function check_playlist($response, $result) {
167
+ $api = json_decode($response['body'], true);
168
+
169
+ if ( $result['http_code'] == 404 ) {
170
+ //Not found.
171
+ $result['log'] .= __('Playlist Not Found', 'broken-link-checker');
172
+ $result['broken'] = true;
173
+ $result['http_code'] = 0;
174
+ $result['status_text'] = __('Playlist Not Found', 'broken-link-checker');
175
+ $result['status_code'] = BLC_LINK_STATUS_ERROR;
176
+
177
+ } else if ( $result['http_code'] == 403 ) {
178
+ //Forbidden. We're unlikely to see this code for playlists, but lets allow it.
179
+ $result['log'] .= htmlentities($response['body']);
180
+ $result['broken'] = true;
181
+ $result['status_text'] = __('Playlist Restricted', 'broken-link-checker');
182
+ $result['status_code'] = BLC_LINK_STATUS_ERROR;
183
+
184
+ } else if ( ($result['http_code'] == 200) && isset($api['items']) && is_array($api['items']) ) {
185
+ //The playlist exists.
186
+ if ( empty($api['items']) ) {
187
+ //An empty playlist. It is possible that all of the videos have been deleted.
188
+ $result['log'] .= __("This playlist has no entries or all entries have been deleted.", 'broken-link-checker');
189
+ $result['status_text'] = _x('Empty Playlist', 'link status', 'broken-link-checker');
190
+ $result['status_code'] = BLC_LINK_STATUS_WARNING;
191
+ $result['http_code'] = 0;
192
+ $result['broken'] = true;
193
+ } else {
194
+ //Treat the playlist as broken if at least one video is inaccessible.
195
+ foreach($api['items'] as $video) {
196
+ $is_private = isset($video['status']['privacyStatus']) && ($video['status']['privacyStatus'] == 'private');
197
+ if ( $is_private ) {
198
+ $result['log'] .= sprintf(
199
+ __('Video status : %s%s', 'broken-link-checker'),
200
+ $video['status']['privacyStatus'],
201
+ ''
202
+ );
203
+
204
+ $result['broken'] = true;
205
+ $result['status_text'] = __('Video Restricted', 'broken-link-checker');
206
+ $result['status_code'] = BLC_LINK_STATUS_WARNING;
207
+ $result['http_code'] = 0;
208
+ break;
209
+ }
210
+ }
211
+
212
+ if ( !$result['broken'] ) {
213
+ //All is well.
214
+ $result['log'] .= __("Playlist OK", 'broken-link-checker');
215
+ $result['status_text'] = _x('OK', 'link status', 'broken-link-checker');
216
+ $result['status_code'] = BLC_LINK_STATUS_OK;
217
+ $result['http_code'] = 0;
218
+ }
219
+ }
220
+
221
+ } else {
222
+ //Some other error.
223
+ $result['status_code'] = BLC_LINK_STATUS_WARNING;
224
+ $result['warning'] = true;
225
+
226
+ if ( isset($api['error']['message']) ) {
227
+ $result['status_text'] = $api['error']['message'];
228
+ } else {
229
+ $result['status_text'] = __('Unknown Error', 'broken-link-checker');
230
+ }
231
+ $result['log'] .= $this->format_api_error($response, $api);
232
+ }
233
+
234
+ return $result;
235
+ }
236
+
237
+ protected function get_video_resource_url($video_id) {
238
+ $params = array(
239
+ 'part' => 'status,snippet',
240
+ 'id' => $video_id,
241
+ 'key' => $this->youtube_developer_key,
242
+ );
243
+ $params = array_map('urlencode', $params);
244
+ return 'https://www.googleapis.com/youtube/v3/videos?' . build_query($params);
245
+ }
246
+
247
+ protected function get_playlist_resource_url($playlist_id) {
248
+ if ( strpos($playlist_id, 'PL') === 0 ) {
249
+ $playlist_id = substr($playlist_id, 2);
250
+ }
251
+ $params = array(
252
+ 'key' => $this->youtube_developer_key,
253
+ 'playlistId' => $playlist_id,
254
+ 'part' => 'snippet,status',
255
+ 'maxResults' => 10, //Playlists can be big. Lets just check the first few videos.
256
+ );
257
+ $query = build_query(array_map('urlencode', $params));
258
+ return 'https://www.googleapis.com/youtube/v3/playlistItems?' . $query;
259
+ }
260
+
261
+ protected function format_api_error($response, $api) {
262
+ $log = $response['response']['code'] . ' ' . $response['response']['message'];
263
+ $log .= "\n" . __('Unknown YouTube API response received.');
264
+
265
+ //Log error details.
266
+ if ( isset($api['error']['errors']) && is_array($api['error']['errors']) ) {
267
+ foreach($api['error']['errors'] as $error) {
268
+ $log .= "\n---\n";
269
+
270
+ if (is_array($error)) {
271
+ foreach($error as $key => $value) {
272
+ $log .= sprintf(
273
+ "%s: %s\n",
274
+ htmlentities($key),
275
+ htmlentities($value)
276
+ );
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ return $log;
283
+ }
284
+
285
+ }
modules/parsers/acf_field.php CHANGED
@@ -1,134 +1,134 @@
1
- <?php
2
- /*
3
- Plugin Name: ACF
4
- Description: Parses acf fields (AKA custom fields)
5
- Version: 1.0
6
- Author: Janne Aalto
7
-
8
- ModuleID: acf
9
- ModuleCategory: parser
10
- ModuleClassName: blcACFParser
11
- ModuleContext: on-demand
12
- ModuleLazyInit: true
13
- ModuleAlwaysActive: true
14
- ModuleHidden: true
15
- */
16
-
17
- class blcACFParser extends blcParser {
18
-
19
- var $supported_formats = array('acf_field');
20
- var $supported_containers = array();
21
-
22
- /**
23
- * Parse a acf value.
24
- *
25
- * @param string|array $content ACF value(s).
26
- * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
27
- * @param string $default_link_text
28
- * @return array An array of new blcLinkInstance objects.
29
- */
30
- function parse($content, $base_url = '', $default_link_text = ''){
31
- $instances = array();
32
-
33
- if ( !is_array($content) ){
34
- $content = array($content);
35
- }
36
-
37
- foreach($content as $value){
38
- //The complete contents of the meta field are stored in raw_url.
39
- //This is useful for editing/unlinking, when one may need to
40
- //distinguish between multiple fields with the same name.
41
- $raw_url = $value;
42
-
43
- //If this is a multiline acf field take only the first line (workaround for the 'enclosure' field).
44
- $lines = explode("\n", $value);
45
- $url = trim(reset($lines));
46
-
47
- //Attempt to parse the URL
48
- $parts = @parse_url($url);
49
- if(!$parts) {
50
- return $instances; //Ignore invalid URLs
51
- };
52
-
53
- if ( !isset($parts['scheme']) ){
54
- //No scheme - likely a relative URL. Turn it into an absolute one.
55
- $url = $this->relative2absolute($url, $base_url);
56
-
57
- //Skip invalid URLs (again)
58
- if ( !$url || (strlen($url)<6) ) {
59
- return $instances;
60
- }
61
- }
62
-
63
- //The URL is okay, create and populate a new link instance.
64
- $instance = new blcLinkInstance();
65
-
66
- $instance->set_parser($this);
67
- $instance->raw_url = $raw_url;
68
- $instance->link_text = $default_link_text;
69
-
70
- $link_obj = new blcLink($url); //Creates or loads the link
71
- $instance->set_link($link_obj);
72
-
73
- $instances[] = $instance;
74
- }
75
-
76
- return $instances;
77
- }
78
-
79
- /**
80
- * Change the URL in a acf field to another one.
81
- *
82
- * This is tricky because there can be multiple acf fields with the same name
83
- * but different values. So we ignore $content (which might be an array of multiple
84
- * acf values) and use the old raw_url that we stored when parsing the field(s)
85
- * instead.
86
- *
87
- * @see blcACFParser::parse()
88
- *
89
- * @param string $content Ignored.
90
- * @param string $new_url The new URL.
91
- * @param string $old_url Ignored.
92
- * @param string $old_raw_url The current meta value.
93
- *
94
- * @return array|WP_Error
95
- */
96
- function edit($content, $new_url, $old_url, $old_raw_url){
97
- //For multiline fields (like 'enclosure') we only want to change the first line.
98
- $lines = explode("\n", $old_raw_url);
99
- array_shift($lines); //Discard the old first line
100
- array_unshift($lines, $new_url); //Insert the new URL in its place.
101
- $content = implode("\n", $lines);
102
-
103
- return array(
104
- 'content' => $content,
105
- 'raw_url' => $new_url,
106
- );
107
- }
108
-
109
- /**
110
- * Get the link text for printing in the "Broken Links" table.
111
- *
112
- * @param blcLinkInstance $instance
113
- * @param string $context
114
- * @return string HTML
115
- */
116
- function ui_get_link_text($instance, $context = 'display'){
117
- $image_html = sprintf(
118
- '<img src="%s" class="blc-small-image" title="%2$s" alt="%2$s"> ',
119
- esc_attr( plugins_url('/images/font-awesome/font-awesome-code.png', BLC_PLUGIN_FILE) ),
120
- __('Custom field', 'broken-link-checker')
121
- );
122
-
123
- $field_html = sprintf(
124
- '<code>%s</code>',
125
- $instance->container_field
126
- );
127
-
128
- if ( $context != 'email' ){
129
- $field_html = $image_html . $field_html;
130
- }
131
-
132
- return $field_html;
133
- }
134
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: ACF
4
+ Description: Parses acf fields (AKA custom fields)
5
+ Version: 1.0
6
+ Author: Janne Aalto
7
+
8
+ ModuleID: acf
9
+ ModuleCategory: parser
10
+ ModuleClassName: blcACFParser
11
+ ModuleContext: on-demand
12
+ ModuleLazyInit: true
13
+ ModuleAlwaysActive: true
14
+ ModuleHidden: true
15
+ */
16
+
17
+ class blcACFParser extends blcParser {
18
+
19
+ var $supported_formats = array('acf_field');
20
+ var $supported_containers = array();
21
+
22
+ /**
23
+ * Parse a acf value.
24
+ *
25
+ * @param string|array $content ACF value(s).
26
+ * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
27
+ * @param string $default_link_text
28
+ * @return array An array of new blcLinkInstance objects.
29
+ */
30
+ function parse($content, $base_url = '', $default_link_text = ''){
31
+ $instances = array();
32
+
33
+ if ( !is_array($content) ){
34
+ $content = array($content);
35
+ }
36
+
37
+ foreach($content as $value){
38
+ //The complete contents of the meta field are stored in raw_url.
39
+ //This is useful for editing/unlinking, when one may need to
40
+ //distinguish between multiple fields with the same name.
41
+ $raw_url = $value;
42
+
43
+ //If this is a multiline acf field take only the first line (workaround for the 'enclosure' field).
44
+ $lines = explode("\n", $value);
45
+ $url = trim(reset($lines));
46
+
47
+ //Attempt to parse the URL
48
+ $parts = @parse_url($url);
49
+ if(!$parts) {
50
+ return $instances; //Ignore invalid URLs
51
+ };
52
+
53
+ if ( !isset($parts['scheme']) ){
54
+ //No scheme - likely a relative URL. Turn it into an absolute one.
55
+ $url = $this->relative2absolute($url, $base_url);
56
+
57
+ //Skip invalid URLs (again)
58
+ if ( !$url || (strlen($url)<6) ) {
59
+ return $instances;
60
+ }
61
+ }
62
+
63
+ //The URL is okay, create and populate a new link instance.
64
+ $instance = new blcLinkInstance();
65
+
66
+ $instance->set_parser($this);
67
+ $instance->raw_url = $raw_url;
68
+ $instance->link_text = $default_link_text;
69
+
70
+ $link_obj = new blcLink($url); //Creates or loads the link
71
+ $instance->set_link($link_obj);
72
+
73
+ $instances[] = $instance;
74
+ }
75
+
76
+ return $instances;
77
+ }
78
+
79
+ /**
80
+ * Change the URL in a acf field to another one.
81
+ *
82
+ * This is tricky because there can be multiple acf fields with the same name
83
+ * but different values. So we ignore $content (which might be an array of multiple
84
+ * acf values) and use the old raw_url that we stored when parsing the field(s)
85
+ * instead.
86
+ *
87
+ * @see blcACFParser::parse()
88
+ *
89
+ * @param string $content Ignored.
90
+ * @param string $new_url The new URL.
91
+ * @param string $old_url Ignored.
92
+ * @param string $old_raw_url The current meta value.
93
+ *
94
+ * @return array|WP_Error
95
+ */
96
+ function edit($content, $new_url, $old_url, $old_raw_url){
97
+ //For multiline fields (like 'enclosure') we only want to change the first line.
98
+ $lines = explode("\n", $old_raw_url);
99
+ array_shift($lines); //Discard the old first line
100
+ array_unshift($lines, $new_url); //Insert the new URL in its place.
101
+ $content = implode("\n", $lines);
102
+
103
+ return array(
104
+ 'content' => $content,
105
+ 'raw_url' => $new_url,
106
+ );
107
+ }
108
+
109
+ /**
110
+ * Get the link text for printing in the "Broken Links" table.
111
+ *
112
+ * @param blcLinkInstance $instance
113
+ * @param string $context
114
+ * @return string HTML
115
+ */
116
+ function ui_get_link_text($instance, $context = 'display'){
117
+ $image_html = sprintf(
118
+ '<img src="%s" class="blc-small-image" title="%2$s" alt="%2$s"> ',
119
+ esc_attr( plugins_url('/images/font-awesome/font-awesome-code.png', BLC_PLUGIN_FILE) ),
120
+ __('Custom field', 'broken-link-checker')
121
+ );
122
+
123
+ $field_html = sprintf(
124
+ '<code>%s</code>',
125
+ $instance->container_field
126
+ );
127
+
128
+ if ( $context != 'email' ){
129
+ $field_html = $image_html . $field_html;
130
+ }
131
+
132
+ return $field_html;
133
+ }
134
+ }
modules/parsers/html_link.php CHANGED
@@ -1,372 +1,372 @@
1
- <?php
2
-
3
- /*
4
- Plugin Name: HTML links
5
- Description: Example : <code>&lt;a href="http://example.com/"&gt;link text&lt;/a&gt;</code>
6
- Version: 1.0
7
- Author: Janis Elsts
8
-
9
- ModuleID: link
10
- ModuleCategory: parser
11
- ModuleClassName: blcHTMLLink
12
- ModuleContext: on-demand
13
- ModuleLazyInit: true
14
-
15
- ModulePriority: 1000
16
- */
17
-
18
- class blcHTMLLink extends blcParser {
19
- var $supported_formats = array('html');
20
-
21
- /**
22
- * Parse a string for HTML links - <a href="URL">anchor text</a>
23
- *
24
- * @param string $content The text to parse.
25
- * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
26
- * @param string $default_link_text
27
- * @return array An array of new blcLinkInstance objects. The objects will include info about the links found, but not about the corresponding container entity.
28
- */
29
- function parse($content, $base_url = '', $default_link_text = ''){
30
- $content = apply_filters( 'blc-parser-html-link-content', $content );
31
-
32
- //remove all <code></code> blocks first
33
- $content = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $content);
34
-
35
- //Find links
36
- $params = array(
37
- 'base_url' => $base_url,
38
- 'default_link_text' => $default_link_text,
39
- );
40
- $instances = $this->map($content, array($this, 'parser_callback'), $params);
41
-
42
- //The parser callback returns NULL when it finds an invalid link. Filter out those nulls
43
- //from the list of instances.
44
- $instances = array_filter($instances);
45
-
46
- return $instances;
47
- }
48
-
49
- /**
50
- * blcHTMLLink::parser_callback()
51
- *
52
- * @access private
53
- *
54
- * @param array $link
55
- * @param array $params
56
- * @return blcLinkInstance|null
57
- */
58
- function parser_callback($link, $params){
59
- global $blclog;
60
- $base_url = $params['base_url'];
61
-
62
- $url = $raw_url = $link['href'];
63
- $url = trim($url);
64
- //$blclog->debug(__CLASS__ .':' . __FUNCTION__ . ' Found a link, raw URL = "' . $raw_url . '"');
65
-
66
- //Sometimes links may contain shortcodes. Execute them.
67
- $url = do_shortcode($url);
68
-
69
- //Skip empty URLs
70
- if ( empty($url) ){
71
- $blclog->warn(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (empty URL)');
72
- return null;
73
- };
74
-
75
- //Attempt to parse the URL
76
- $parts = @parse_url($url);
77
- if(!$parts) {
78
- $blclog->warn(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (parse_url failed)', $url);
79
- return null; //Skip invalid URLs
80
- };
81
-
82
- if ( !isset($parts['scheme']) ){
83
- //No scheme - likely a relative URL. Turn it into an absolute one.
84
- //TODO: Also log the original URL and base URL.
85
- $url = $this->relative2absolute($url, $base_url); //$base_url comes from $params
86
- $blclog->info(__CLASS__ .':' . __FUNCTION__ . ' Convert relative URL to absolute. Absolute URL = "' . $url . '"');
87
- }
88
-
89
- //Skip invalid links (again)
90
- if ( !$url || (strlen($url)<6) ) {
91
- $blclog->info(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (invalid/short URL)', $url);
92
- return null;
93
- }
94
-
95
- //Remove left-to-right marks. See: https://en.wikipedia.org/wiki/Left-to-right_mark
96
- $ltrm = json_decode('"\u200E"');
97
- $url = str_replace($ltrm, '', $url);
98
-
99
- $text = $link['#link_text'];
100
-
101
- //The URL is okay, create and populate a new link instance.
102
- $instance = new blcLinkInstance();
103
-
104
- $instance->set_parser($this);
105
- $instance->raw_url = $raw_url;
106
- $instance->link_text = $text;
107
-
108
- $link_obj = new blcLink($url); //Creates or loads the link
109
- $instance->set_link($link_obj);
110
-
111
- return $instance;
112
- }
113
-
114
- /**
115
- * Change all links that have a certain URL to a new URL.
116
- *
117
- * @param string $content Look for links in this string.
118
- * @param string $new_url Change the links to this URL.
119
- * @param string $old_url The URL to look for.
120
- * @param string $old_raw_url The raw, not-normalized URL of the links to look for. Optional.
121
- * @param string $new_text New link text. Optional.
122
- *
123
- * @return array|WP_Error If successful, the return value will be an associative array with two
124
- * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
125
- * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
126
- */
127
- function edit($content, $new_url, $old_url, $old_raw_url, $new_text = null){
128
- if ( empty($old_raw_url) ){
129
- $old_raw_url = $old_url;
130
- }
131
-
132
- //Save the old & new URLs for use in the edit callback.
133
- $args = array(
134
- 'old_url' => $old_raw_url,
135
- 'new_url' => $new_url,
136
- 'new_text' => $new_text,
137
- );
138
-
139
- //Find all links and replace those that match $old_url.
140
- $content = $this->multi_edit($content, array(&$this, 'edit_callback'), $args);
141
-
142
- $result = array(
143
- 'content' => $content,
144
- 'raw_url' => $new_url,
145
- );
146
- if ( isset($new_text) ) {
147
- $result['link_text'] = $new_text;
148
- }
149
- return $result;
150
- }
151
-
152
- function edit_callback($link, $params){
153
- if ($link['href'] == $params['old_url']){
154
- $modified = array(
155
- 'href' => $params['new_url'],
156
- );
157
- if ( isset($params['new_text']) ) {
158
- $modified['#link_text'] = $params['new_text'];
159
- }
160
- return $modified;
161
- } else {
162
- return $link['#raw'];
163
- }
164
- }
165
-
166
- public function is_link_text_editable() {
167
- return true;
168
- }
169
-
170
- public function is_url_editable() {
171
- return true;
172
- }
173
-
174
- /**
175
- * Remove all links that have a certain URL, leaving anchor text intact.
176
- *
177
- * @param string $content Look for links in this string.
178
- * @param string $url The URL to look for.
179
- * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
180
- * @return string Input string with all matching links removed.
181
- */
182
- function unlink($content, $url, $raw_url){
183
- if ( empty($raw_url) ){
184
- $raw_url = $url;
185
- }
186
-
187
- $args = array(
188
- 'old_url' => $raw_url,
189
- );
190
-
191
- //Find all links and remove those that match $raw_url.
192
- $content = $this->multi_edit($content, array(&$this, 'unlink_callback'), $args);
193
-
194
- return $content;
195
- }
196
-
197
- /**
198
- * blcHTMLLink::unlink_callback()
199
- *
200
- * @access private
201
- *
202
- * @param array $link
203
- * @param array $params
204
- * @return string
205
- */
206
- function unlink_callback($link, $params){
207
- //Skip links that don't match the specified URL
208
- if ($link['href'] != $params['old_url']){
209
- return $link['#raw'];
210
- }
211
-
212
- $config = blc_get_configuration();
213
- if ( $config->options['mark_removed_links'] ){
214
- //Leave only the anchor text + the removed_link CSS class
215
- return sprintf(
216
- '<span class="removed_link" title="%s">%s</span>',
217
- esc_attr($link['href']),
218
- $link['#link_text']
219
- );
220
- } else {
221
- //Just the anchor text
222
- return $link['#link_text'];
223
- }
224
- }
225
-
226
- /**
227
- * Get the link text for printing in the "Broken Links" table.
228
- * Sub-classes should override this method and display the link text in a way appropriate for the link type.
229
- *
230
- * @param blcLinkInstance $instance
231
- * @param string $context
232
- * @return string HTML
233
- */
234
- function ui_get_link_text($instance, $context = 'display'){
235
- return strip_tags($instance->link_text);
236
- }
237
-
238
- /**
239
- * Apply a callback function to all HTML links found in a string and return the results.
240
- *
241
- * The link data array will contain at least these keys :
242
- * 'href' - the URL of the link (with htmlentitydecode() already applied).
243
- * '#raw' - the raw link code, e.g. the entire '<a href="...">...</a>' tag of a HTML link.
244
- * '#offset' - the offset within $content at which the first character of the link tag was found.
245
- * '#link_text' - the link's anchor text, if any. May contain HTML tags.
246
- *
247
- * Any attributes of the link tag will also be included in the returned array as attr_name => attr_value
248
- * pairs. This function will also automatically decode any HTML entities found in attribute values.
249
- *
250
- * @see blcParser::map()
251
- *
252
- * @param string $content A text string to parse for links.
253
- * @param callback $callback Callback function to apply to all found links.
254
- * @param mixed $extra If the optional $extra param. is supplied, it will be passed as the second parameter to the function $callback.
255
- * @return array An array of all detected links after applying $callback to each of them.
256
- */
257
- function map($content, $callback, $extra = null){
258
- $results = array();
259
-
260
- //Find all links
261
- $links = blcUtility::extract_tags($content, 'a', false, true);
262
-
263
- //Iterate over the links and apply $callback to each
264
- foreach($links as $link){
265
-
266
- //Massage the found link into a form required for the callback function
267
- $param = $link['attributes'];
268
- $param = array_merge(
269
- $param,
270
- array(
271
- '#raw' => $link['full_tag'],
272
- '#offset' => $link['offset'],
273
- '#link_text' => $link['contents'],
274
- 'href' => isset($link['attributes']['href'])?$link['attributes']['href']:'',
275
- )
276
- );
277
-
278
- //Prepare arguments for the callback
279
- $params = array($param);
280
- if ( isset($extra) ){
281
- $params[] = $extra;
282
- }
283
-
284
- //Execute & store :)
285
- $results[] = call_user_func_array($callback, $params);
286
- }
287
-
288
- return $results;
289
- }
290
-
291
- /**
292
- * Modify all HTML links found in a string using a callback function.
293
- *
294
- * The callback function should return either an associative array or a string. If
295
- * a string is returned, the parser will replace the current link with the contents
296
- * of that string. If an array is returned, the current link will be modified/rebuilt
297
- * by substituting the new values for the old ones.
298
- *
299
- * htmlentities() will be automatically applied to attribute values (but not to #link_text).
300
- *
301
- * @see blcParser::multi_edit()
302
- *
303
- * @param string $content A text string containing the links to edit.
304
- * @param callback $callback Callback function used to modify the links.
305
- * @param mixed $extra If supplied, $extra will be passed as the second parameter to the function $callback.
306
- * @return string The modified input string.
307
- */
308
- function multi_edit($content, $callback, $extra = null){
309
- //Just reuse map() + a little helper func. to apply the callback to all links and get modified links
310
- $modified_links = $this->map($content, array(&$this, 'execute_edit_callback'), array($callback, $extra));
311
-
312
- //Replace each old link with the modified one
313
- $offset = 0;
314
- foreach($modified_links as $link){
315
- if ( isset($link['#new_raw']) ){
316
- $new_html = $link['#new_raw'];
317
- } else {
318
- //Assemble the new link tag
319
- $new_html = '<a';
320
- foreach ( $link as $name => $value ){
321
-
322
- //Skip special keys like '#raw' and '#offset'
323
- if ( substr($name, 0, 1) == '#' ){
324
- continue;
325
- }
326
-
327
- $new_html .= sprintf(' %s="%s"', $name, esc_attr( $value ));
328
- }
329
- $new_html .= '>' . $link['#link_text'] . '</a>';
330
- }
331
-
332
- $content = substr_replace($content, $new_html, $link['#offset'] + $offset, strlen($link['#raw']));
333
- //Update the replacement offset
334
- $offset += ( strlen($new_html) - strlen($link['#raw']) );
335
- }
336
-
337
- return $content;
338
- }
339
-
340
- /**
341
- * Helper function for blcHtmlLink::multi_edit()
342
- * Applies the specified callback function to each link and merges
343
- * the result with the current link attributes. If the callback returns
344
- * a replacement HTML tag instead, it will be stored in the '#new_raw'
345
- * key of the return array.
346
- *
347
- * @access protected
348
- *
349
- * @param array $link
350
- * @param array $info The callback function and the extra argument to pass to that function (if any).
351
- * @return array
352
- */
353
- function execute_edit_callback($link, $info){
354
- list($callback, $extra) = $info;
355
-
356
- //Prepare arguments for the callback
357
- $params = array($link);
358
- if ( isset($extra) ){
359
- $params[] = $extra;
360
- }
361
-
362
- $new_link = call_user_func_array($callback, $params);
363
-
364
- if ( is_array($new_link) ){
365
- $link = array_merge($link, $new_link);
366
- } elseif (is_string($new_link)) {
367
- $link['#new_raw'] = $new_link;
368
- }
369
-
370
- return $link;
371
- }
372
  }
1
+ <?php
2
+
3
+ /*
4
+ Plugin Name: HTML links
5
+ Description: Example : <code>&lt;a href="http://example.com/"&gt;link text&lt;/a&gt;</code>
6
+ Version: 1.0
7
+ Author: Janis Elsts
8
+
9
+ ModuleID: link
10
+ ModuleCategory: parser
11
+ ModuleClassName: blcHTMLLink
12
+ ModuleContext: on-demand
13
+ ModuleLazyInit: true
14
+
15
+ ModulePriority: 1000
16
+ */
17
+
18
+ class blcHTMLLink extends blcParser {
19
+ var $supported_formats = array('html');
20
+
21
+ /**
22
+ * Parse a string for HTML links - <a href="URL">anchor text</a>
23
+ *
24
+ * @param string $content The text to parse.
25
+ * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
26
+ * @param string $default_link_text
27
+ * @return array An array of new blcLinkInstance objects. The objects will include info about the links found, but not about the corresponding container entity.
28
+ */
29
+ function parse($content, $base_url = '', $default_link_text = ''){
30
+ $content = apply_filters( 'blc-parser-html-link-content', $content );
31
+
32
+ //remove all <code></code> blocks first
33
+ $content = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $content);
34
+
35
+ //Find links
36
+ $params = array(
37
+ 'base_url' => $base_url,
38
+ 'default_link_text' => $default_link_text,
39
+ );
40
+ $instances = $this->map($content, array($this, 'parser_callback'), $params);
41
+
42
+ //The parser callback returns NULL when it finds an invalid link. Filter out those nulls
43
+ //from the list of instances.
44
+ $instances = array_filter($instances);
45
+
46
+ return $instances;
47
+ }
48
+
49
+ /**
50
+ * blcHTMLLink::parser_callback()
51
+ *
52
+ * @access private
53
+ *
54
+ * @param array $link
55
+ * @param array $params
56
+ * @return blcLinkInstance|null
57
+ */
58
+ function parser_callback($link, $params){
59
+ global $blclog;
60
+ $base_url = $params['base_url'];
61
+
62
+ $url = $raw_url = $link['href'];
63
+ $url = trim($url);
64
+ //$blclog->debug(__CLASS__ .':' . __FUNCTION__ . ' Found a link, raw URL = "' . $raw_url . '"');
65
+
66
+ //Sometimes links may contain shortcodes. Execute them.
67
+ $url = do_shortcode($url);
68
+
69
+ //Skip empty URLs
70
+ if ( empty($url) ){
71
+ $blclog->warn(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (empty URL)');
72
+ return null;
73
+ };
74
+
75
+ //Attempt to parse the URL
76
+ $parts = @parse_url($url);
77
+ if(!$parts) {
78
+ $blclog->warn(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (parse_url failed)', $url);
79
+ return null; //Skip invalid URLs
80
+ };
81
+
82
+ if ( !isset($parts['scheme']) ){
83
+ //No scheme - likely a relative URL. Turn it into an absolute one.
84
+ //TODO: Also log the original URL and base URL.
85
+ $url = $this->relative2absolute($url, $base_url); //$base_url comes from $params
86
+ $blclog->info(__CLASS__ .':' . __FUNCTION__ . ' Convert relative URL to absolute. Absolute URL = "' . $url . '"');
87
+ }
88
+
89
+ //Skip invalid links (again)
90
+ if ( !$url || (strlen($url)<6) ) {
91
+ $blclog->info(__CLASS__ .':' . __FUNCTION__ . ' Skipping the link (invalid/short URL)', $url);
92
+ return null;
93
+ }
94
+
95
+ //Remove left-to-right marks. See: https://en.wikipedia.org/wiki/Left-to-right_mark
96
+ $ltrm = json_decode('"\u200E"');
97
+ $url = str_replace($ltrm, '', $url);
98
+
99
+ $text = $link['#link_text'];
100
+
101
+ //The URL is okay, create and populate a new link instance.
102
+ $instance = new blcLinkInstance();
103
+
104
+ $instance->set_parser($this);
105
+ $instance->raw_url = $raw_url;
106
+ $instance->link_text = $text;
107
+
108
+ $link_obj = new blcLink($url); //Creates or loads the link
109
+ $instance->set_link($link_obj);
110
+
111
+ return $instance;
112
+ }
113
+
114
+ /**
115
+ * Change all links that have a certain URL to a new URL.
116
+ *
117
+ * @param string $content Look for links in this string.
118
+ * @param string $new_url Change the links to this URL.
119
+ * @param string $old_url The URL to look for.
120
+ * @param string $old_raw_url The raw, not-normalized URL of the links to look for. Optional.
121
+ * @param string $new_text New link text. Optional.
122
+ *
123
+ * @return array|WP_Error If successful, the return value will be an associative array with two
124
+ * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
125
+ * for the modified links. In most cases, the returned raw_url will be equal to the new_url.
126
+ */
127
+ function edit($content, $new_url, $old_url, $old_raw_url, $new_text = null){
128
+ if ( empty($old_raw_url) ){
129
+ $old_raw_url = $old_url;
130
+ }
131
+
132
+ //Save the old & new URLs for use in the edit callback.
133
+ $args = array(
134
+ 'old_url' => $old_raw_url,
135
+ 'new_url' => $new_url,
136
+ 'new_text' => $new_text,
137
+ );
138
+
139
+ //Find all links and replace those that match $old_url.
140
+ $content = $this->multi_edit($content, array(&$this, 'edit_callback'), $args);
141
+
142
+ $result = array(
143
+ 'content' => $content,
144
+ 'raw_url' => $new_url,
145
+ );
146
+ if ( isset($new_text) ) {
147
+ $result['link_text'] = $new_text;
148
+ }
149
+ return $result;
150
+ }
151
+
152
+ function edit_callback($link, $params){
153
+ if ($link['href'] == $params['old_url']){
154
+ $modified = array(
155
+ 'href' => $params['new_url'],
156
+ );
157
+ if ( isset($params['new_text']) ) {
158
+ $modified['#link_text'] = $params['new_text'];
159
+ }
160
+ return $modified;
161
+ } else {
162
+ return $link['#raw'];
163
+ }
164
+ }
165
+
166
+ public function is_link_text_editable() {
167
+ return true;
168
+ }
169
+
170
+ public function is_url_editable() {
171
+ return true;
172
+ }
173
+
174
+ /**
175
+ * Remove all links that have a certain URL, leaving anchor text intact.
176
+ *
177
+ * @param string $content Look for links in this string.
178
+ * @param string $url The URL to look for.
179
+ * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
180
+ * @return string Input string with all matching links removed.
181
+ */
182
+ function unlink($content, $url, $raw_url){
183
+ if ( empty($raw_url) ){
184
+ $raw_url = $url;
185
+ }
186
+
187
+ $args = array(
188
+ 'old_url' => $raw_url,
189
+ );
190
+
191
+ //Find all links and remove those that match $raw_url.
192
+ $content = $this->multi_edit($content, array(&$this, 'unlink_callback'), $args);
193
+
194
+ return $content;
195
+ }
196
+
197
+ /**
198
+ * blcHTMLLink::unlink_callback()
199
+ *
200
+ * @access private
201
+ *
202
+ * @param array $link
203
+ * @param array $params
204
+ * @return string
205
+ */
206
+ function unlink_callback($link, $params){
207
+ //Skip links that don't match the specified URL
208
+ if ($link['href'] != $params['old_url']){
209
+ return $link['#raw'];
210
+ }
211
+
212
+ $config = blc_get_configuration();
213
+ if ( $config->options['mark_removed_links'] ){
214
+ //Leave only the anchor text + the removed_link CSS class
215
+ return sprintf(
216
+ '<span class="removed_link" title="%s">%s</span>',
217
+ esc_attr($link['href']),
218
+ $link['#link_text']
219
+ );
220
+ } else {
221
+ //Just the anchor text
222
+ return $link['#link_text'];
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Get the link text for printing in the "Broken Links" table.
228
+ * Sub-classes should override this method and display the link text in a way appropriate for the link type.
229
+ *
230
+ * @param blcLinkInstance $instance
231
+ * @param string $context
232
+ * @return string HTML
233
+ */
234
+ function ui_get_link_text($instance, $context = 'display'){
235
+ return strip_tags($instance->link_text);
236
+ }
237
+
238
+ /**
239
+ * Apply a callback function to all HTML links found in a string and return the results.
240
+ *
241
+ * The link data array will contain at least these keys :
242
+ * 'href' - the URL of the link (with htmlentitydecode() already applied).
243
+ * '#raw' - the raw link code, e.g. the entire '<a href="...">...</a>' tag of a HTML link.
244
+ * '#offset' - the offset within $content at which the first character of the link tag was found.
245
+ * '#link_text' - the link's anchor text, if any. May contain HTML tags.
246
+ *
247
+ * Any attributes of the link tag will also be included in the returned array as attr_name => attr_value
248
+ * pairs. This function will also automatically decode any HTML entities found in attribute values.
249
+ *
250
+ * @see blcParser::map()
251
+ *
252
+ * @param string $content A text string to parse for links.
253
+ * @param callback $callback Callback function to apply to all found links.
254
+ * @param mixed $extra If the optional $extra param. is supplied, it will be passed as the second parameter to the function $callback.
255
+ * @return array An array of all detected links after applying $callback to each of them.
256
+ */
257
+ function map($content, $callback, $extra = null){
258
+ $results = array();
259
+
260
+ //Find all links
261
+ $links = blcUtility::extract_tags($content, 'a', false, true);
262
+
263
+ //Iterate over the links and apply $callback to each
264
+ foreach($links as $link){
265
+
266
+ //Massage the found link into a form required for the callback function
267
+ $param = $link['attributes'];
268
+ $param = array_merge(
269
+ $param,
270
+ array(
271
+ '#raw' => $link['full_tag'],
272
+ '#offset' => $link['offset'],
273
+ '#link_text' => $link['contents'],
274
+ 'href' => isset($link['attributes']['href'])?$link['attributes']['href']:'',
275
+ )
276
+ );
277
+
278
+ //Prepare arguments for the callback
279
+ $params = array($param);
280
+ if ( isset($extra) ){
281
+ $params[] = $extra;
282
+ }
283
+
284
+ //Execute & store :)
285
+ $results[] = call_user_func_array($callback, $params);
286
+ }
287
+
288
+ return $results;
289
+ }
290
+
291
+ /**
292
+ * Modify all HTML links found in a string using a callback function.
293
+ *
294
+ * The callback function should return either an associative array or a string. If
295
+ * a string is returned, the parser will replace the current link with the contents
296
+ * of that string. If an array is returned, the current link will be modified/rebuilt
297
+ * by substituting the new values for the old ones.
298
+ *
299
+ * htmlentities() will be automatically applied to attribute values (but not to #link_text).
300
+ *
301
+ * @see blcParser::multi_edit()
302
+ *
303
+ * @param string $content A text string containing the links to edit.
304
+ * @param callback $callback Callback function used to modify the links.
305
+ * @param mixed $extra If supplied, $extra will be passed as the second parameter to the function $callback.
306
+ * @return string The modified input string.
307
+ */
308
+ function multi_edit($content, $callback, $extra = null){
309
+ //Just reuse map() + a little helper func. to apply the callback to all links and get modified links
310
+ $modified_links = $this->map($content, array(&$this, 'execute_edit_callback'), array($callback, $extra));
311
+
312
+ //Replace each old link with the modified one
313
+ $offset = 0;
314
+ foreach($modified_links as $link){
315
+ if ( isset($link['#new_raw']) ){
316
+ $new_html = $link['#new_raw'];
317
+ } else {
318
+ //Assemble the new link tag
319
+ $new_html = '<a';
320
+ foreach ( $link as $name => $value ){
321
+
322
+ //Skip special keys like '#raw' and '#offset'
323
+ if ( substr($name, 0, 1) == '#' ){
324
+ continue;
325
+ }
326
+
327
+ $new_html .= sprintf(' %s="%s"', $name, esc_attr( $value ));
328
+ }
329
+ $new_html .= '>' . $link['#link_text'] . '</a>';
330
+ }
331
+
332
+ $content = substr_replace($content, $new_html, $link['#offset'] + $offset, strlen($link['#raw']));
333
+ //Update the replacement offset
334
+ $offset += ( strlen($new_html) - strlen($link['#raw']) );
335
+ }
336
+
337
+ return $content;
338
+ }
339
+
340
+ /**
341
+ * Helper function for blcHtmlLink::multi_edit()
342
+ * Applies the specified callback function to each link and merges
343
+ * the result with the current link attributes. If the callback returns
344
+ * a replacement HTML tag instead, it will be stored in the '#new_raw'
345
+ * key of the return array.
346
+ *
347
+ * @access protected
348
+ *
349
+ * @param array $link
350
+ * @param array $info The callback function and the extra argument to pass to that function (if any).
351
+ * @return array
352
+ */
353
+ function execute_edit_callback($link, $info){
354
+ list($callback, $extra) = $info;
355
+
356
+ //Prepare arguments for the callback
357
+ $params = array($link);
358
+ if ( isset($extra) ){
359
+ $params[] = $extra;
360
+ }
361
+
362
+ $new_link = call_user_func_array($callback, $params);
363
+
364
+ if ( is_array($new_link) ){
365
+ $link = array_merge($link, $new_link);
366
+ } elseif (is_string($new_link)) {
367
+ $link['#new_raw'] = $new_link;
368
+ }
369
+
370
+ return $link;
371
+ }
372
  }
modules/parsers/image.php CHANGED
@@ -1,200 +1,200 @@
1
- <?php
2
- /*
3
- Plugin Name: HTML images
4
- Description: e.g. <code>&lt;img src="http://example.com/fluffy.jpg"&gt;</code>
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleID: image
9
- ModuleCategory: parser
10
- ModuleClassName: blcHTMLImage
11
- ModuleContext: on-demand
12
- ModuleLazyInit: true
13
-
14
- ModulePriority: 900
15
- */
16
-
17
- //TODO: Update image parser to use the same HTML tag parsing routine as the HTML link parser.
18
- class blcHTMLImage extends blcParser {
19
- var $supported_formats = array('html');
20
-
21
- // \1 \2 \3 URL \4
22
- var $img_pattern = '/(<img[\s]+[^>]*src\s*=\s*)([\"\'])([^>]+?)\2([^<>]*>)/i';
23
-
24
- /** @var string Used in link editing callbacks. */
25
- private $old_url = '';
26
- /** @var string */
27
- private $new_url = '';
28
-
29
- /**
30
- * Parse a string for HTML images - <img src="URL">
31
- *
32
- * @param string $content The text to parse.
33
- * @param string $base_url The base URL to use for normalizing relative URLs. If omitted, the blog's root URL will be used.
34
- * @param string $default_link_text
35
- * @return array An array of new blcLinkInstance objects. The objects will include info about the links found, but not about the corresponding container entity.
36
- */
37
- function parse($content, $base_url = '', $default_link_text = ''){
38
- global $blclog;
39
-
40
- $charset = get_bloginfo('charset');
41
- if ( strtoupper($charset) === 'UTF8' ) {
42
- $charset = 'UTF-8';
43
- }
44
- $blclog->info('Blog charset is "' . $charset . '"');
45
-
46
- $instances = array();
47
-
48
- //remove all <code></code> blocks first
49
- $content = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $content);
50
-
51
- //Find images
52
- if(preg_match_all($this->img_pattern, $content, $matches, PREG_SET_ORDER)){
53
- foreach($matches as $link){
54
- $url = $raw_url = $link[3];
55
- //FB::log($url, "Found image");
56
- $blclog->info('Found image. SRC attribute: "' . $raw_url . '"');
57
-
58
- //Decode &amp; and other entities
59
- $url = html_entity_decode($url, ENT_QUOTES, $charset);
60
- $blclog->info('Decoded image URL: "' . $url . '"');
61
- $url = trim($url);
62
- $blclog->info('Trimmed image URL: "' . $url . '"');
63
-
64
- //Allow shortcodes in image URLs.
65
- $url = do_shortcode($url);
66
-
67
- //Attempt to parse the URL
68
- $parts = @parse_url($url);
69
- if(!$parts) {
70
- continue; //Skip invalid URLs
71
- };
72
-
73
- if ( !isset($parts['scheme']) ){
74
- //No scheme - likely a relative URL. Turn it into an absolute one.
75
- $relativeUrl = $url;
76
- $url = $this->relative2absolute($url, $base_url);
77
-
78
- $blclog->info(sprintf(
79
- '%s:%s Resolving relative URL. Relative URL = "%s", base URL = "%s", result = "%s"',
80
- __CLASS__,
81
- __FUNCTION__,
82
- $relativeUrl,
83
- $base_url,
84
- $url
85
- ));
86
- }
87
-
88
- //Skip invalid URLs (again)
89
- if ( !$url || (strlen($url)<6) ) {
90
- continue;
91
- }
92
-
93
- $blclog->info('Final URL: "' . $url . '"');
94
- //The URL is okay, create and populate a new link instance.
95
- $instance = new blcLinkInstance();
96
-
97
- $instance->set_parser($this);
98
- $instance->raw_url = $raw_url;
99
- $instance->link_text = '';
100
-
101
- $link_obj = new blcLink($url); //Creates or loads the link
102
- $instance->set_link($link_obj);
103
-
104
- $instances[] = $instance;
105
- }
106
- };
107
-
108
- return $instances;
109
- }
110
-
111
- /**
112
- * Change all images that have a certain source URL to a new URL.
113
- *
114
- * @param string $content Look for images in this string.
115
- * @param string $new_url Change the images to this URL.
116
- * @param string $old_url The URL to look for.
117
- * @param string $old_raw_url The raw, not-normalized URL of the links to look for. Optional.
118
- *
119
- * @return array|WP_Error If successful, the return value will be an associative array with two
120
- * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
121
- * for the modified images. In most cases, the returned raw_url will be equal to the new_url.
122
- */
123
- function edit($content, $new_url, $old_url, $old_raw_url){
124
- if ( empty($old_raw_url) ){
125
- $old_raw_url = $old_url;
126
- }
127
- //Save the old & new URLs for use in the regex callback.
128
- $this->old_url = $old_raw_url;
129
- $this->new_url = htmlentities($new_url);
130
-
131
- //Find all images and replace those that match $old_url.
132
- $content = preg_replace_callback($this->img_pattern, array(&$this, 'edit_callback'), $content);
133
-
134
- return array(
135
- 'content' => $content,
136
- 'raw_url' => $this->new_url,
137
- );
138
- }
139
-
140
- function edit_callback($matches){
141
- $url = $matches[3];
142
- if ($url == $this->old_url){
143
- return $matches[1].'"'.$this->new_url.'"'.$matches[4];
144
- } else {
145
- return $matches[0];
146
- }
147
- }
148
-
149
- /**
150
- * Remove all images that have a certain URL.
151
- *
152
- * @param string $content Look for images in this string.
153
- * @param string $url The URL to look for.
154
- * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
155
- * @return string Input string with all matching images removed.
156
- */
157
- function unlink($content, $url, $raw_url){
158
- if ( empty($raw_url) ){
159
- $raw_url = $url;
160
- }
161
- $this->old_url = $raw_url; //used by the callback
162
- $content = preg_replace_callback($this->img_pattern, array(&$this, 'unlink_callback'), $content);
163
- return $content;
164
- }
165
-
166
- function unlink_callback($matches){
167
- $url = $matches[3];
168
-
169
- //Does the URL match?
170
- if ($url == $this->old_url){
171
- return ''; //Completely remove the IMG tag
172
- } else {
173
- return $matches[0]; //return the image unchanged
174
- }
175
- }
176
-
177
- /**
178
- * Get the link text for printing in the "Broken Links" table.
179
- * Sub-classes should override this method and display the link text in a way appropriate for the link type.
180
- *
181
- * @param blcLinkInstance $instance
182
- * @param string $context
183
- * @return string HTML
184
- */
185
- function ui_get_link_text($instance, $context = 'display'){
186
- $text = __('Image', 'broken-link-checker');
187
-
188
- $image = sprintf(
189
- '<img src="%s" class="blc-small-image" alt="%2$s" title="%2$s"> ',
190
- esc_attr(plugins_url('/images/font-awesome/font-awesome-picture.png', BLC_PLUGIN_FILE)),
191
- esc_attr($text)
192
- );
193
-
194
- if ( $context != 'email' ){
195
- $text = $image . $text;
196
- }
197
-
198
- return $text;
199
- }
200
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: HTML images
4
+ Description: e.g. <code>&lt;img src="http://example.com/fluffy.jpg"&gt;</code>
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleID: image
9
+ ModuleCategory: parser
10
+ ModuleClassName: blcHTMLImage
11
+ ModuleContext: on-demand
12
+ ModuleLazyInit: true
13
+
14
+ ModulePriority: 900
15
+ */
16
+
17
+ //TODO: Update image parser to use the same HTML tag parsing routine as the HTML link parser.
18
+ class blcHTMLImage extends blcParser {
19
+ var $supported_formats = array('html');
20
+
21
+ // \1 \2 \3 URL \4
22
+ var $img_pattern = '/(<img[\s]+[^>]*src\s*=\s*)([\"\'])([^>]+?)\2([^<>]*>)/i';
23
+
24
+ /** @var string Used in link editing callbacks. */
25
+ private $old_url = '';
26
+ /** @var string */
27
+ private $new_url = '';
28
+
29
+ /**
30
+ * Parse a string for HTML images - <img src="URL">
31
+ *
32
+ * @param string $content The text to parse.
33
+ * @param string $base_url The base URL to use for normalizing relative URLs. If omitted, the blog's root URL will be used.
34
+ * @param string $default_link_text
35
+ * @return array An array of new blcLinkInstance objects. The objects will include info about the links found, but not about the corresponding container entity.
36
+ */
37
+ function parse($content, $base_url = '', $default_link_text = ''){
38
+ global $blclog;
39
+
40
+ $charset = get_bloginfo('charset');
41
+ if ( strtoupper($charset) === 'UTF8' ) {
42
+ $charset = 'UTF-8';
43
+ }
44
+ $blclog->info('Blog charset is "' . $charset . '"');
45
+
46
+ $instances = array();
47
+
48
+ //remove all <code></code> blocks first
49
+ $content = preg_replace('/<code[^>]*>.+?<\/code>/si', ' ', $content);
50
+
51
+ //Find images
52
+ if(preg_match_all($this->img_pattern, $content, $matches, PREG_SET_ORDER)){
53
+ foreach($matches as $link){
54
+ $url = $raw_url = $link[3];
55
+ //FB::log($url, "Found image");
56
+ $blclog->info('Found image. SRC attribute: "' . $raw_url . '"');
57
+
58
+ //Decode &amp; and other entities
59
+ $url = html_entity_decode($url, ENT_QUOTES, $charset);
60
+ $blclog->info('Decoded image URL: "' . $url . '"');
61
+ $url = trim($url);
62
+ $blclog->info('Trimmed image URL: "' . $url . '"');
63
+
64
+ //Allow shortcodes in image URLs.
65
+ $url = do_shortcode($url);
66
+
67
+ //Attempt to parse the URL
68
+ $parts = @parse_url($url);
69
+ if(!$parts) {
70
+ continue; //Skip invalid URLs
71
+ };
72
+
73
+ if ( !isset($parts['scheme']) ){
74
+ //No scheme - likely a relative URL. Turn it into an absolute one.
75
+ $relativeUrl = $url;
76
+ $url = $this->relative2absolute($url, $base_url);
77
+
78
+ $blclog->info(sprintf(
79
+ '%s:%s Resolving relative URL. Relative URL = "%s", base URL = "%s", result = "%s"',
80
+ __CLASS__,
81
+ __FUNCTION__,
82
+ $relativeUrl,
83
+ $base_url,
84
+ $url
85
+ ));
86
+ }
87
+
88
+ //Skip invalid URLs (again)
89
+ if ( !$url || (strlen($url)<6) ) {
90
+ continue;
91
+ }
92
+
93
+ $blclog->info('Final URL: "' . $url . '"');
94
+ //The URL is okay, create and populate a new link instance.
95
+ $instance = new blcLinkInstance();
96
+
97
+ $instance->set_parser($this);
98
+ $instance->raw_url = $raw_url;
99
+ $instance->link_text = '';
100
+
101
+ $link_obj = new blcLink($url); //Creates or loads the link
102
+ $instance->set_link($link_obj);
103
+
104
+ $instances[] = $instance;
105
+ }
106
+ };
107
+
108
+ return $instances;
109
+ }
110
+
111
+ /**
112
+ * Change all images that have a certain source URL to a new URL.
113
+ *
114
+ * @param string $content Look for images in this string.
115
+ * @param string $new_url Change the images to this URL.
116
+ * @param string $old_url The URL to look for.
117
+ * @param string $old_raw_url The raw, not-normalized URL of the links to look for. Optional.
118
+ *
119
+ * @return array|WP_Error If successful, the return value will be an associative array with two
120
+ * keys : 'content' - the modified content, and 'raw_url' - the new raw, non-normalized URL used
121
+ * for the modified images. In most cases, the returned raw_url will be equal to the new_url.
122
+ */
123
+ function edit($content, $new_url, $old_url, $old_raw_url){
124
+ if ( empty($old_raw_url) ){
125
+ $old_raw_url = $old_url;
126
+ }
127
+ //Save the old & new URLs for use in the regex callback.
128
+ $this->old_url = $old_raw_url;
129
+ $this->new_url = htmlentities($new_url);
130
+
131
+ //Find all images and replace those that match $old_url.
132
+ $content = preg_replace_callback($this->img_pattern, array(&$this, 'edit_callback'), $content);
133
+
134
+ return array(
135
+ 'content' => $content,
136
+ 'raw_url' => $this->new_url,
137
+ );
138
+ }
139
+
140
+ function edit_callback($matches){
141
+ $url = $matches[3];
142
+ if ($url == $this->old_url){
143
+ return $matches[1].'"'.$this->new_url.'"'.$matches[4];
144
+ } else {
145
+ return $matches[0];
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Remove all images that have a certain URL.
151
+ *
152
+ * @param string $content Look for images in this string.
153
+ * @param string $url The URL to look for.
154
+ * @param string $raw_url The raw, non-normalized version of the URL to look for. Optional.
155
+ * @return string Input string with all matching images removed.
156
+ */
157
+ function unlink($content, $url, $raw_url){
158
+ if ( empty($raw_url) ){
159
+ $raw_url = $url;
160
+ }
161
+ $this->old_url = $raw_url; //used by the callback
162
+ $content = preg_replace_callback($this->img_pattern, array(&$this, 'unlink_callback'), $content);
163
+ return $content;
164
+ }
165
+
166
+ function unlink_callback($matches){
167
+ $url = $matches[3];
168
+
169
+ //Does the URL match?
170
+ if ($url == $this->old_url){
171
+ return ''; //Completely remove the IMG tag
172
+ } else {
173
+ return $matches[0]; //return the image unchanged
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Get the link text for printing in the "Broken Links" table.
179
+ * Sub-classes should override this method and display the link text in a way appropriate for the link type.
180
+ *
181
+ * @param blcLinkInstance $instance
182
+ * @param string $context
183
+ * @return string HTML
184
+ */
185
+ function ui_get_link_text($instance, $context = 'display'){
186
+ $text = __('Image', 'broken-link-checker');
187
+
188
+ $image = sprintf(
189
+ '<img src="%s" class="blc-small-image" alt="%2$s" title="%2$s"> ',
190
+ esc_attr(plugins_url('/images/font-awesome/font-awesome-picture.png', BLC_PLUGIN_FILE)),
191
+ esc_attr($text)
192
+ );
193
+
194
+ if ( $context != 'email' ){
195
+ $text = $image . $text;
196
+ }
197
+
198
+ return $text;
199
+ }
200
+ }
modules/parsers/metadata.php CHANGED
@@ -1,133 +1,133 @@
1
- <?php
2
- /*
3
- Plugin Name: Metadata
4
- Description: Parses metadata (AKA custom fields)
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleID: metadata
9
- ModuleCategory: parser
10
- ModuleClassName: blcMetadataParser
11
- ModuleContext: on-demand
12
- ModuleLazyInit: true
13
- ModuleAlwaysActive: true
14
- ModuleHidden: true
15
- */
16
-
17
- class blcMetadataParser extends blcParser {
18
- var $supported_formats = array('metadata');
19
- var $supported_containers = array();
20
-
21
- /**
22
- * Parse a metadata value.
23
- *
24
- * @param string|array $content Metadata value(s).
25
- * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
26
- * @param string $default_link_text
27
- * @return array An array of new blcLinkInstance objects.
28
- */
29
- function parse($content, $base_url = '', $default_link_text = ''){
30
- $instances = array();
31
-
32
- if ( !is_array($content) ){
33
- $content = array($content);
34
- }
35
-
36
- foreach($content as $value){
37
- //The complete contents of the meta field are stored in raw_url.
38
- //This is useful for editing/unlinking, when one may need to
39
- //distinguish between multiple fields with the same name.
40
- $raw_url = $value;
41
-
42
- //If this is a multiline metadata field take only the first line (workaround for the 'enclosure' field).
43
- $lines = explode("\n", $value);
44
- $url = trim(reset($lines));
45
-
46
- //Attempt to parse the URL
47
- $parts = @parse_url($url);
48
- if(!$parts) {
49
- return $instances; //Ignore invalid URLs
50
- };
51
-
52
- if ( !isset($parts['scheme']) ){
53
- //No scheme - likely a relative URL. Turn it into an absolute one.
54
- $url = $this->relative2absolute($url, $base_url);
55
-
56
- //Skip invalid URLs (again)
57
- if ( !$url || (strlen($url)<6) ) {
58
- return $instances;
59
- }
60
- }
61
-
62
- //The URL is okay, create and populate a new link instance.
63
- $instance = new blcLinkInstance();
64
-
65
- $instance->set_parser($this);
66
- $instance->raw_url = $raw_url;
67
- $instance->link_text = $default_link_text;
68
-
69
- $link_obj = new blcLink($url); //Creates or loads the link
70
- $instance->set_link($link_obj);
71
-
72
- $instances[] = $instance;
73
- }
74
-
75
- return $instances;
76
- }
77
-
78
- /**
79
- * Change the URL in a metadata field to another one.
80
- *
81
- * This is tricky because there can be multiple metadata fields with the same name
82
- * but different values. So we ignore $content (which might be an array of multiple
83
- * metadata values) and use the old raw_url that we stored when parsing the field(s)
84
- * instead.
85
- *
86
- * @see blcMetadataParser::parse()
87
- *
88
- * @param string $content Ignored.
89
- * @param string $new_url The new URL.
90
- * @param string $old_url Ignored.
91
- * @param string $old_raw_url The current meta value.
92
- *
93
- * @return array|WP_Error
94
- */
95
- function edit($content, $new_url, $old_url, $old_raw_url){
96
- //For multiline fields (like 'enclosure') we only want to change the first line.
97
- $lines = explode("\n", $old_raw_url);
98
- array_shift($lines); //Discard the old first line
99
- array_unshift($lines, $new_url); //Insert the new URL in its place.
100
- $content = implode("\n", $lines);
101
-
102
- return array(
103
- 'content' => $content,
104
- 'raw_url' => $new_url,
105
- );
106
- }
107
-
108
- /**
109
- * Get the link text for printing in the "Broken Links" table.
110
- *
111
- * @param blcLinkInstance $instance
112
- * @param string $context
113
- * @return string HTML
114
- */
115
- function ui_get_link_text($instance, $context = 'display'){
116
- $image_html = sprintf(
117
- '<img src="%s" class="blc-small-image" title="%2$s" alt="%2$s"> ',
118
- esc_attr( plugins_url('/images/font-awesome/font-awesome-code.png', BLC_PLUGIN_FILE) ),
119
- __('Custom field', 'broken-link-checker')
120
- );
121
-
122
- $field_html = sprintf(
123
- '<code>%s</code>',
124
- $instance->container_field
125
- );
126
-
127
- if ( $context != 'email' ){
128
- $field_html = $image_html . $field_html;
129
- }
130
-
131
- return $field_html;
132
- }
133
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: Metadata
4
+ Description: Parses metadata (AKA custom fields)
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleID: metadata
9
+ ModuleCategory: parser
10
+ ModuleClassName: blcMetadataParser
11
+ ModuleContext: on-demand
12
+ ModuleLazyInit: true
13
+ ModuleAlwaysActive: true
14
+ ModuleHidden: true
15
+ */
16
+
17
+ class blcMetadataParser extends blcParser {
18
+ var $supported_formats = array('metadata');
19
+ var $supported_containers = array();
20
+
21
+ /**
22
+ * Parse a metadata value.
23
+ *
24
+ * @param string|array $content Metadata value(s).
25
+ * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
26
+ * @param string $default_link_text
27
+ * @return array An array of new blcLinkInstance objects.
28
+ */
29
+ function parse($content, $base_url = '', $default_link_text = ''){
30
+ $instances = array();
31
+
32
+ if ( !is_array($content) ){
33
+ $content = array($content);
34
+ }
35
+
36
+ foreach($content as $value){
37
+ //The complete contents of the meta field are stored in raw_url.
38
+ //This is useful for editing/unlinking, when one may need to
39
+ //distinguish between multiple fields with the same name.
40
+ $raw_url = $value;
41
+
42
+ //If this is a multiline metadata field take only the first line (workaround for the 'enclosure' field).
43
+ $lines = explode("\n", $value);
44
+ $url = trim(reset($lines));
45
+
46
+ //Attempt to parse the URL
47
+ $parts = @parse_url($url);
48
+ if(!$parts) {
49
+ return $instances; //Ignore invalid URLs
50
+ };
51
+
52
+ if ( !isset($parts['scheme']) ){
53
+ //No scheme - likely a relative URL. Turn it into an absolute one.
54
+ $url = $this->relative2absolute($url, $base_url);
55
+
56
+ //Skip invalid URLs (again)
57
+ if ( !$url || (strlen($url)<6) ) {
58
+ return $instances;
59
+ }
60
+ }
61
+
62
+ //The URL is okay, create and populate a new link instance.
63
+ $instance = new blcLinkInstance();
64
+
65
+ $instance->set_parser($this);
66
+ $instance->raw_url = $raw_url;
67
+ $instance->link_text = $default_link_text;
68
+
69
+ $link_obj = new blcLink($url); //Creates or loads the link
70
+ $instance->set_link($link_obj);
71
+
72
+ $instances[] = $instance;
73
+ }
74
+
75
+ return $instances;
76
+ }
77
+
78
+ /**
79
+ * Change the URL in a metadata field to another one.
80
+ *
81
+ * This is tricky because there can be multiple metadata fields with the same name
82
+ * but different values. So we ignore $content (which might be an array of multiple
83
+ * metadata values) and use the old raw_url that we stored when parsing the field(s)
84
+ * instead.
85
+ *
86
+ * @see blcMetadataParser::parse()
87
+ *
88
+ * @param string $content Ignored.
89
+ * @param string $new_url The new URL.
90
+ * @param string $old_url Ignored.
91
+ * @param string $old_raw_url The current meta value.
92
+ *
93
+ * @return array|WP_Error
94
+ */
95
+ function edit($content, $new_url, $old_url, $old_raw_url){
96
+ //For multiline fields (like 'enclosure') we only want to change the first line.
97
+ $lines = explode("\n", $old_raw_url);
98
+ array_shift($lines); //Discard the old first line
99
+ array_unshift($lines, $new_url); //Insert the new URL in its place.
100
+ $content = implode("\n", $lines);
101
+
102
+ return array(
103
+ 'content' => $content,
104
+ 'raw_url' => $new_url,
105
+ );
106
+ }
107
+
108
+ /**
109
+ * Get the link text for printing in the "Broken Links" table.
110
+ *
111
+ * @param blcLinkInstance $instance
112
+ * @param string $context
113
+ * @return string HTML
114
+ */
115
+ function ui_get_link_text($instance, $context = 'display'){
116
+ $image_html = sprintf(
117
+ '<img src="%s" class="blc-small-image" title="%2$s" alt="%2$s"> ',
118
+ esc_attr( plugins_url('/images/font-awesome/font-awesome-code.png', BLC_PLUGIN_FILE) ),
119
+ __('Custom field', 'broken-link-checker')
120
+ );
121
+
122
+ $field_html = sprintf(
123
+ '<code>%s</code>',
124
+ $instance->container_field
125
+ );
126
+
127
+ if ( $context != 'email' ){
128
+ $field_html = $image_html . $field_html;
129
+ }
130
+
131
+ return $field_html;
132
+ }
133
+ }
modules/parsers/url_field.php CHANGED
@@ -1,96 +1,96 @@
1
- <?php
2
- /*
3
- Plugin Name: URL fields
4
- Description: Parses data fields that contain a single, plaintext URL.
5
- Version: 1.0
6
- Author: Janis Elsts
7
-
8
- ModuleID: url_field
9
- ModuleCategory: parser
10
- ModuleClassName: blcUrlField
11
- ModuleContext: on-demand
12
- ModuleLazyInit: true
13
- ModuleAlwaysActive: true
14
- ModuleHidden: true
15
- */
16
-
17
- /**
18
- * A "parser" for data fields that contain a single, plaintext URL.
19
- *
20
- * Intended for parsing stuff like bookmarks and comment author links.
21
- *
22
- * @package Broken Link Checker
23
- * @access public
24
- */
25
- class blcUrlField extends blcParser {
26
- var $supported_formats = array('url_field');
27
-
28
- /**
29
- * "Parse" an URL into an instance.
30
- *
31
- * @param string $content The entire content is expected to be a single plaintext URL.
32
- * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
33
- * @param string $default_link_text
34
- * @return array An array of new blcLinkInstance objects.
35
- */
36
- function parse($content, $base_url = '', $default_link_text = ''){
37
- $instances = array();
38
-
39
- $url = $raw_url = trim($content);
40
-
41
- //Attempt to parse the URL
42
- $parts = @parse_url($url);
43
- if(!$parts) {
44
- return $instances; //Ignore invalid URLs
45
- };
46
-
47
- if ( !isset($parts['scheme']) ){
48
- //No sheme - likely a relative URL. Turn it into an absolute one.
49
- $url = $this->relative2absolute($url, $base_url);
50
-
51
- //Skip invalid URLs (again)
52
- if ( !$url || (strlen($url)<6) ) {
53
- return $instances;
54
- }
55
- }
56
-
57
- //The URL is okay, create and populate a new link instance.
58
- $instance = new blcLinkInstance();
59
-
60
- $instance->set_parser($this);
61
- $instance->raw_url = $raw_url;
62
- $instance->link_text = $default_link_text;
63
-
64
- $link_obj = new blcLink($url); //Creates or loads the link
65
- $instance->set_link($link_obj);
66
-
67
- $instances[] = $instance;
68
-
69
- return $instances;
70
- }
71
-
72
- /**
73
- * Change one URL to another (just returns the new URL).
74
- *
75
- * @param string $content The old URL.
76
- * @param string $new_url The new URL.
77
- * @param string $old_url Ignored.
78
- * @param string $old_raw_url Ignored.
79
- *
80
- * @return array|WP_Error
81
- */
82
- function edit($content, $new_url, $old_url, $old_raw_url){
83
- return array(
84
- 'content' => $new_url,
85
- 'raw_url' => $new_url,
86
- );
87
- }
88
-
89
- /**
90
- * For URL fields, "unlinking" simply means blanking the field.
91
- * (However, invididual link containers may implement a different logic for those fields.)
92
- */
93
- function unlink($content, $url, $raw_url){
94
- return '';
95
- }
96
- }
1
+ <?php
2
+ /*
3
+ Plugin Name: URL fields
4
+ Description: Parses data fields that contain a single, plaintext URL.
5
+ Version: 1.0
6
+ Author: Janis Elsts
7
+
8
+ ModuleID: url_field
9
+ ModuleCategory: parser
10
+ ModuleClassName: blcUrlField
11
+ ModuleContext: on-demand
12
+ ModuleLazyInit: true
13
+ ModuleAlwaysActive: true
14
+ ModuleHidden: true
15
+ */
16
+
17
+ /**
18
+ * A "parser" for data fields that contain a single, plaintext URL.
19
+ *
20
+ * Intended for parsing stuff like bookmarks and comment author links.
21
+ *
22
+ * @package Broken Link Checker
23
+ * @access public
24
+ */
25
+ class blcUrlField extends blcParser {
26
+ var $supported_formats = array('url_field');
27
+
28
+ /**
29
+ * "Parse" an URL into an instance.
30
+ *
31
+ * @param string $content The entire content is expected to be a single plaintext URL.
32
+ * @param string $base_url The base URL to use for normalizing relative URLs. If ommitted, the blog's root URL will be used.
33
+ * @param string $default_link_text
34
+ * @return array An array of new blcLinkInstance objects.
35
+ */
36
+ function parse($content, $base_url = '', $default_link_text = ''){
37
+ $instances = array();
38
+
39
+ $url = $raw_url = trim($content);
40
+
41
+ //Attempt to parse the URL
42
+ $parts = @parse_url($url);
43
+ if(!$parts) {
44
+ return $instances; //Ignore invalid URLs
45
+ };
46
+
47
+ if ( !isset($parts['scheme']) ){
48
+ //No sheme - likely a relative URL. Turn it into an absolute one.
49
+ $url = $this->relative2absolute($url, $base_url);
50
+
51
+ //Skip invalid URLs (again)
52
+ if ( !$url || (strlen($url)<6) ) {
53
+ return $instances;
54
+ }
55
+ }
56
+
57
+ //The URL is okay, create and populate a new link instance.
58
+ $instance = new blcLinkInstance();
59
+
60
+ $instance->set_parser($this);
61
+ $instance->raw_url = $raw_url;
62
+ $instance->link_text = $default_link_text;
63
+
64
+ $link_obj = new blcLink($url); //Creates or loads the link
65
+ $instance->set_link($link_obj);
66
+
67
+ $instances[] = $instance;
68
+
69
+ return $instances;
70
+ }
71
+
72
+ /**
73
+ * Change one URL to another (just returns the new URL).
74
+ *
75
+ * @param string $content The old URL.
76
+ * @param string $new_url The new URL.
77
+ * @param string $old_url Ignored.
78
+ * @param string $old_raw_url Ignored.
79
+ *
80
+ * @return array|WP_Error
81
+ */
82
+ function edit($content, $new_url, $old_url, $old_raw_url){
83
+ return array(
84
+ 'content' => $new_url,
85
+ 'raw_url' => $new_url,
86
+ );
87
+ }
88
+
89
+ /**
90
+ * For URL fields, "unlinking" simply means blanking the field.
91
+ * (However, invididual link containers may implement a different logic for those fields.)
92
+ */
93
+ function unlink($content, $url, $raw_url){
94
+ return '';
95
+ }
96
+ }
php52_lint.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ echo "Checking PHP 5.2 syntax..."
3
+ for filename in $(find ./ -maxdepth 100 -name "*.php"); do
4
+ RESULT=$(php52 -l "$filename")
5
+ if ! $(echo "$RESULT" | grep -q 'No syntax errors detected in'); then
6
+ echo "Syntax error found in file: $filename"
7
+ echo "$RESULT"
8
+ fi
9
+ done
10
+
11
+ echo "Done!"
readme.txt CHANGED
@@ -1,71 +1,121 @@
1
- === Broken Link Checker ===
2
- Contributors: managewp
3
- Donate link:
4
- Tags: links, broken, maintenance, blogroll, custom fields, admin, comments, posts
 
 
5
  Requires at least: 3.2
6
- Tested up to: 5.1
7
- Stable tag: 1.11.8
 
 
8
 
9
- This plugin will check your posts, comments and other content for broken links and missing images, and notify you if any are found.
10
 
11
  == Description ==
12
- This plugin will monitor your blog looking for broken links and let you know if any are found.
13
 
14
- **Features**
15
 
16
- * Monitors links in your posts, pages, comments, the blogroll, and custom fields (optional).
17
- * Detects links that don't work, missing images and redirects.
18
- * Notifies you either via the Dashboard or by email.
19
- * Makes broken links display differently in posts (optional).
20
- * Prevents search engines from following broken links (optional).
21
- * You can search and filter links by URL, anchor text and so on.
22
- * Links can be edited directly from the plugin's page, without manually updating each post.
23
- * Highly configurable.
24
 
25
- **Basic Usage**
26
 
27
- Once installed, the plugin will begin parsing your posts, bookmarks (AKA blogroll) and other content and looking for links. Depending on the size of your site this can take from a few minutes up to an hour or more. When parsing is complete, the plugin will start checking each link to see if it works. Again, how long this takes depends on how big your site is and how many links there are. You can monitor the progress and tweak various link checking options in *Settings -> Link Checker*.
28
 
29
- The broken links, if any are found, will show up in a new tab of the WP admin panel - *Tools -> Broken Links*. A notification will also appear in the "Broken Link Checker" widget on the Dashboard. To save display space, you can keep the widget closed and configure it to expand automatically when problematic links are detected. E-mail notifications need to be enabled separately (in *Settings -> Link Checker*).
 
 
 
 
 
 
 
30
 
31
- The "Broken Links" tab will by default display a list of broken links that have been detected so far. However, you can use the links on that page to view redirects or see a listing of all links - working or not - instead. You can also create new link filters by performing a search and clicking the "Create Custom Filter" button. For example, this can be used to create a filter that only shows comment links.
32
 
33
- There are several actions associated with each link. They show up when you move your mouse over to one of the links listed the aforementioned tab -
34
 
35
- * "Edit URL" lets you change the URL of that link. If the link is present in more than one place (e.g. both in a post and in the blogroll), all occurrences of that URL will be changed.
36
- * "Unlink" removes the link but leaves the link text intact.
37
- * "Not broken" lets you manually mark a "broken" link as working. This is useful if you know it was incorrectly detected as broken due to a network glitch or a bug. The marked link will still be checked periodically, but the plugin won't consider it broken unless it gets a new result.
38
- * "Dismiss" hides the link from the "Broken Links" and "Redirects" views. It will still be checked as normal and get the normal link styles (e.g. a strike-through effect for broken links), but won't be reported again unless its status changes. Useful if you want to acknowledge a link as broken/redirected and just leave as it is.
39
 
40
- You can also click on the contents of the "Status" or "Link Text" columns to get more info about the status of each link.
41
 
42
- **Other Credits**
43
 
44
- This plugin uses some icons from the [Font Awesome icon font](http://fortawesome.github.io/Font-Awesome/). Font Awesome is licensed under SIL OFL 1.1.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- **Contribute**
47
 
48
- Broken Link Checker is now on [GitHub](https://github.com/ManageWP/broken-link-checker). Pull Requests welcome.
49
 
50
- == Installation ==
51
 
52
- To do a new installation of the plugin, please follow these steps
53
 
54
- 1. Download the broken-link-checker.zip file to your computer.
55
- 1. Unzip the file
56
- 1. Upload `broken-link-checker` folder to the `/wp-content/plugins/` directory
57
- 1. Activate the plugin through the 'Plugins' menu in WordPress
58
 
59
- To enable/disable various features and tweak the plugin's configuration go to *Settings -> Link Checker*.
60
 
61
- To upgrade your installation
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- 1. Deactivate the plugin
64
- 1. Retrieve and upload the new files (do steps 1. - 3. from "new installation" instructions)
65
- 1. Reactivate the plugin. Your settings will be retained from the previous version.
66
 
67
  == Changelog ==
68
 
 
 
 
 
69
  = 1.11.7 =
70
  * Fixed a PHP 7.2 compatibility issue
71
 
@@ -817,3 +867,18 @@ Adds an option to send post authors notifications about broken links in their po
817
 
818
  = 0.9.4.2 =
819
  Fixes a major PHP4 compatibility problem introduced in version 0.9.4 and adds a notification bubble with the current broken link count to the "Broken Links" menu.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === Broken Link Checker – Find and Fix Dead Links ===
2
+ Plugin Name: Broken Link Checker – Find and Fix Dead Links
3
+ Author: WPMU DEV
4
+ Author URI: https://premium.wpmudev.org/
5
+ Contributors: wpmudev
6
+ Tags: broken link checker, fix broken links, free broken link checker, broken link finder, dead link finder, website 404 checker
7
  Requires at least: 3.2
8
+ Tested up to: 5.2.4
9
+ Stable tag: 1.11.9
10
+ Requires PHP: 5.3
11
+ License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
12
 
13
+ Scan, find and fix dead links with Broken Link Checker because 404’s and broken links are bad for your users and bad for SEO.
14
 
15
  == Description ==
16
+ *Is your site being penalized because of old broken links? Broken Link Checker scans every link on your website and tells you if the link has changed, is broken or no longer exists so you can fix it.*
17
 
18
+ Broken links cause users to leave your site faster, slow down search bots, lead to lowering where you show on search pages and can hurt your Google ranking.
19
 
20
+ With +700,000 active installs, Broken Link Checker is the most popular free link monitor for WordPress. If you are searching for an easy way to find and fix broken links in WordPress, Broken Link Checker will scan your site, notify you when a broken link is found and make suggestions for fixing your links. Simple and powerful.
 
 
 
 
 
 
 
21
 
 
22
 
23
+ ### Features
24
 
25
+ - Monitor - Set automated scans for your posts, pages, comments, blogroll and custom fields.
26
+ - Detect - Find links that don’t work, missing images and redirects.
27
+ - Report - Get notified when links are broken in the built-in Dashboard widget and through email.
28
+ - Highlight - Configure posts to display broken links with a custom style.
29
+ - Prevention - Stop search engines from following broken links.
30
+ - Filter - search and filter links by URL, anchor text and more.
31
+ - Quick Edit - Save time by editing links directly from the settings page, no need to manually visit each post.
32
+ - Schedule - Set how often links are scanned and limit resource usage with highly customizable settings.
33
 
 
34
 
35
+ ### Find Broken Links Anywhere
36
 
37
+ Your site collects thousands of links quickly from pages and posts to images, comments and custom fields. It’s great for ranking and navigation, but things get moved which leads to 404s, dead links and “page not found” messages. How do you stay on top of it all? Broken Link Checker crawls your site and notifies you when a broken link is found. Save hundreds of hours with automation.
 
 
 
38
 
39
+ ### Fix All Your Links in One Place
40
 
41
+ Fix links right from inside the Broken Link Checker fully filterable link list. No need to jump from page to post, editing and repeating. Sort by link text, URL, status and where links are located. Think of all the time you’ll save maintaining a clean blog. Update, edit, or remove the link, quickly recheck and move on. It’s that fast.
42
 
43
+ **Options include:**
44
+ - Edit URL - change the URL of that link. If the link is present in more than one place (e.g. both in a post and in the blogroll), all occurrences of that URL will be changed.
45
+ - Unlink - removes the link but leaves the link text intact.
46
+ - Not broken - manually mark a “broken” link as working. This is useful if you know it was incorrectly detected as broken due to a network glitch or a bug. The marked link will still be checked periodically, but the plugin won’t consider it broken unless it gets a new result.
47
+ - Dismiss - hides the link from the “Broken Links” and “Redirects” views. It will still be checked as normal and get the normal link styles (e.g. a strikethrough effect for broken links), but won’t be reported again unless the status changes. Useful if you want to acknowledge a link as broken/redirected and just leave as it is.
48
+
49
+ ### Email and Dashboard Notifications
50
+
51
+ Get notifications when a dead link is found in the dashboard, have them emailed to your inbox or notify your authors when a link is broken. Broken Link Checker monitors your site in the background with scheduled scans automating link maintenance.
52
+
53
+ ### Link Tweaks and Custom Styling
54
+
55
+ Visually communicate with users when a link is broken or if a link has been removed. Add a strikethrough, use a different font or change the color. Plus, use the “Stop search engines from following broken links” option to help protect your site from getting penalized.
56
+
57
+ ### Integrates With Your Favorite WordPress Plugins
58
+
59
+ Not only does Broken Link Checker work with the Gutenberg, the new default block editor in WordPress, but it’s also built to detect custom fields, blocks, and plugins including:
60
+
61
+ - [Advanced Custom Fields (ACF)](https://wordpress.org/plugins/advanced-custom-fields/)
62
+ - [Forminator Forms, Polls, and Quizzes](https://wordpress.org/plugins/forminator/)
63
+ - Custom Fields
64
+ - YouTube Videos
65
+ - Vimeo Videos
66
+ - Google Video Embeds
67
+ - DailyMotion Videos
68
+ - Image Links
69
+ - HTML Images
70
+ - Many, many more...
71
+
72
+ ### What Do People Say About Broken Link Checker?
73
+
74
+ ★★★★★
75
+ Excellent, very accurate detection. Great for editing bulk links after a server migration. Highly recommended utility for devs. - [dmac](https://wordpress.org/support/users/darrenmcentee/)
76
+
77
+ ★★★★★
78
+ Huge time saver! I can’t imagine trying to do a regular link audit without a tool like this. One of my must-have plugins on the websites I manage. - [Andrew Ledwith](https://wordpress.org/support/users/jaledwith/)
79
+
80
+ ★★★★★
81
+ Not only did it find all the errors (and redirects), but it also allowed me to repair the errors from the plugin directly. Really, really efficient! - [haayman](https://wordpress.org/support/users/haayman/)
82
+
83
+
84
+ == Frequently Asked Questions ==
85
 
86
+ = I Heard Broken Link Checker is bad for performance. Is that True? =
87
 
88
+ Performing a link scan requires crawlers to follow every link on every page, post, comment, image, video, and so on… you get the point. This does put a load on your server. That said, Broken Link Checker includes all the settings you need to perform scans on your schedule. Managed correctly, Broken Link Checker will have little impact on your resources.
89
 
90
+ = Why is WPMU DEV taking over Broken Link Checker? Is it still safe? =
91
 
92
+ ManageWP has passed the torch to WPMU DEV for continued maintenance and ongoing development of the free Broken Link Checker plugin. WPMU DEV was an obvious choice because of their past WordPress contributions and history of maintaining free plugins in the repository like [Smush](https://wordpress.org/plugins/wp-smushit/) image optimization with over +1 million active installs, [Hummingbird](https://wordpress.org/plugins/search/Hummingbird/), [SmartCrawl](https://wordpress.org/plugins/smartcrawl-seo/), [Hustle](https://wordpress.org/plugins/wordpress-popup/), [Defender](https://wordpress.org/plugins/defender-security/) and [Forminator](https://wordpress.org/plugins/forminator/).
93
 
94
+ = Is there a Pro version of Broken Link Checker? =
 
 
 
95
 
96
+ While there is currently not a Pro version of Broken Link Checker, Pro users should check out [Link Monitor](https://managewp.com/features/link-monitor) by ManageWP. Link Monitor includes additional features and is lighter on your website resources.
97
 
98
+ = Will Broken Link Checker Remain Free? =
99
+
100
+ Yes, WPMU DEV has many free products and believes in giving back to the WordPress project by building and maintaining valuable free products. The plan is to keep all existing features freely available to everyone.
101
+
102
+ = Why automate broken link scans? =
103
+
104
+ Automating a process like link management not only saves time but ensures a valuable step is not skipped when maintaining your blog or website.
105
+
106
+
107
+ == Screenshots ==
108
+
109
+ 1. Find and manage broken links across your site easily from the WordPress dashboard.
110
+ 2. Control what link types you want to scan.
111
 
 
 
 
112
 
113
  == Changelog ==
114
 
115
+ = 1.11.9 =
116
+ * Fixed Reflected XSS ( props to Tobias Fink for the report, ref: https://github.com/sbaresearch/advisories/tree/public/2019/SBA-ADV-20190913-02_WordPress_Plugin_Broken_Link_Checker )
117
+ * Fixed param escaping to avoid possible XSS attack.
118
+
119
  = 1.11.7 =
120
  * Fixed a PHP 7.2 compatibility issue
121
 
867
 
868
  = 0.9.4.2 =
869
  Fixes a major PHP4 compatibility problem introduced in version 0.9.4 and adds a notification bubble with the current broken link count to the "Broken Links" menu.
870
+
871
+ == About Us ==
872
+ WPMU DEV is a premium supplier of quality WordPress plugins, services, hosting and support. Learn more here:
873
+ [https://premium.wpmudev.org/](https://premium.wpmudev.org/?utm_source=wordpress.org&utm_medium=readme&utm_campaign=broken-link-checker-readme&utm_content=wpmu_dev_link)
874
+
875
+ Don't forget to stay up to date on everything WordPress from the Internet's number one resource:
876
+ [WPMU DEV Blog](https://premium.wpmudev.org/blog/?utm_source=wordpress.org&utm_medium=readme&utm_campaign=broken-link-checker-readme&utm_content=wpmu_dev_blog_link)
877
+
878
+ Hey, one more thing... we hope you [enjoy our free offerings](http://profiles.wordpress.org/WPMUDEV/) as much as we've loved making them for you!
879
+
880
+ == Contact and Credits ==
881
+
882
+ Other contributors include the team at [ManageWP](https://managewp.com/)
883
+
884
+ This plugin uses some icons from the [Font Awesome icon font](http://fortawesome.github.io/Font-Awesome/). Font Awesome is licensed under SIL OFL 1.1.
uninstall.php CHANGED
File without changes