forked from documentcloud/wordpress-documentcloud
/
documentcloud.php
381 lines (323 loc) · 16 KB
/
documentcloud.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
/***
* Plugin Name: DocumentCloud
* Plugin URI: https://www.documentcloud.org/
* Description: Embed DocumentCloud resources in WordPress content.
* Version: 0.4.0
* Authors: Chris Amico, Justin Reese
* License: GPLv2
***/
/*
Copyright 2011 National Public Radio, Inc.
Copyright 2015 DocumentCloud, Investigative Reporters & Editors
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Die if this isn't being called from within WordPress.
defined( 'ABSPATH' ) or die();
class WP_DocumentCloud {
const CACHING_ENABLED = true,
DEFAULT_EMBED_FULL_WIDTH = 940,
OEMBED_RESOURCE_DOMAIN = 'www.documentcloud.org',
OEMBED_PROVIDER = 'https://www.documentcloud.org/api/oembed.{format}',
DOCUMENT_PATTERN = '^(?P<protocol>https?):\/\/www\.documentcloud\.org\/documents\/(?P<document_slug>[0-9]+-[a-z0-9-]+)';
function __construct() {
add_action('admin_init', array(&$this, 'check_dc_plugin_conflict'));
add_action('init', array(&$this, 'register_dc_oembed_provider'));
// Only called when `[documentcloud]` shortcode is used
add_shortcode('documentcloud', array(&$this, 'process_dc_shortcode'));
// Called just before oEmbed endpoint is hit
add_filter('oembed_fetch_url', array(&$this, 'prepare_oembed_fetch'), 10, 3);
// Setup admin settings
add_action('admin_menu', array(&$this, 'add_options_page'));
add_action('admin_init', array(&$this, 'settings_init'));
// Store metadata upon post save
add_action('save_post', array(&$this, 'save'));
}
function check_dc_plugin_conflict() {
if (is_plugin_active('navis-documentcloud/navis-documentcloud.php')) {
add_action( 'admin_notices', array(&$this, 'dc_conflict_admin_notice'));
}
}
function dc_conflict_admin_notice() {
?>
<div class="error">
<p><?php _e( '<b>Warning!</b> You have two conflicting DocumentCloud plugins activated. Please deactivate Navis DocumentCloud, which has been replaced by <a target="_blank" href="https://wordpress.org/plugins/documentcloud/">DocumentCloud</a>.', 'documentcloud-plugin-conflict' ); ?></p>
</div>
<?php
}
// Register ourselves as an oEmbed provider. WordPress does NOT cURL the
// resource to inspect it for an oEmbed link tag; we have to tell it what
// our oEmbed endpoint looks like.
function register_dc_oembed_provider() {
/*
Hello developer. If you wish to test this plugin against your
local installation of DocumentCloud (with its own testing
domain), set the OEMBED_PROVIDER and OEMBED_RESOURCE_DOMAIN
constants above to your local testing domain. You'll also want
to uncomment the next line to let WordPress connect to local
domains.
*/
// add_filter( 'http_request_host_is_external', '__return_true');
wp_oembed_add_provider("http://" . WP_DocumentCloud::OEMBED_RESOURCE_DOMAIN . "/documents/*", WP_DocumentCloud::OEMBED_PROVIDER);
wp_oembed_add_provider("https://" . WP_DocumentCloud::OEMBED_RESOURCE_DOMAIN . "/documents/*", WP_DocumentCloud::OEMBED_PROVIDER);
}
function get_default_sizes() {
$wp_embed_defaults = wp_embed_defaults();
$height = intval(get_option('documentcloud_default_height', $wp_embed_defaults['height']));
$width = intval(get_option('documentcloud_default_width', $wp_embed_defaults['width']));
$full_width = intval(get_option('documentcloud_full_width', WP_DocumentCloud::DEFAULT_EMBED_FULL_WIDTH));
return array (
'height' => $height,
'width' => $width,
'full_width' => $full_width,
);
}
// TODO: Add admin options to adjust all defaults.
function get_default_atts() {
$default_sizes = $this->get_default_sizes();
return array(
'url' => null,
'container' => null,
'notes' => null,
'responsive_offset' => null,
'default_page' => null,
'default_note' => null,
'zoom' => null,
'search' => null,
'responsive' => 'true',
// The following defaults match the existing plugin, except
// `height/width` are prefixed `max*` per the oEmbed spec.
// You can still use `height/width` for backwards
// compatibility, but they'll be mapped to `max*`.
// Precedence (lower number == higher priority):
// 1. `width` on shortcode
// 2. `maxwidth` on shortcode
// 3. Settings > DocumentCloud > "Default embed width"
// 4. `wp_embed_defaults()['width']`
'maxheight' => $default_sizes['height'],
'maxwidth' => $default_sizes['width'],
'format' => 'normal',
'sidebar' => 'false',
'text' => 'true',
'pdf' => 'true',
);
}
function prepare_oembed_fetch($provider, $url, $args) {
// Clean and prepare arguments
foreach ($args as $key => $value) {
switch ($key) {
case 'format':
case 'height':
case 'width':
case 'discover':
// Don't pass these attributes to the provider
break;
default:
// Without this check, `add_query_arg()` will treat values
// that are actually ID selectors, like `container=#foo`,
// as URL fragments and throw them at the end of the URL.
if (strpos($value, '#') === 0) {
$value = urlencode($value);
}
$provider = add_query_arg( $key, $value, $provider );
break;
}
}
// Some resources (like notes) have multiple possible
// user-facing URLs. We recompose them into a single form.
$url = $this->clean_dc_url($url);
$provider = add_query_arg( 'url', urlencode($url), $provider );
return $provider;
}
function process_dc_shortcode($atts) {
$default_sizes = $this->get_default_sizes();
$default_atts = $this->get_default_atts();
// Smooshes together passed-in shortcode attrs with defaults
// and filters to only those we accept.
$filtered_atts = shortcode_atts($default_atts, $atts);
// Either the `url` or `id` attributes are required, but `id`
// is only supported for backwards compatibility. If it's used,
// we force this to embed a document. I.e., `id` can't be used
// for embedding notes, pages, or other non-document resources.
if (!$atts['url']) {
if (!$atts['id']) {
return '';
}
else {
$url = $filtered_atts['url'] = "https://" . WP_DocumentCloud::OEMBED_RESOURCE_DOMAIN . "/documents/{$atts['id']}.html";
}
}
// `height/width` beat `maxheight/maxwidth`; see full precedence list in `get_default_atts()`.
if (isset($atts['height'])) {
$filtered_atts['maxheight'] = $atts['height'];
}
if (isset($atts['width'])) {
$filtered_atts['maxwidth'] = $atts['width'];
}
// `responsive` defaults true, but our responsive layout
// ignores width declarations. If a user indicates a width and
// hasn't otherwise specifically indicated `responsive='true'`,
// it's safe to assume they expect us to respect the width, so
// we disable the responsive flag.
if ((isset($atts['width']) || isset($atts['maxwidth'])) && (string) $atts['responsive'] != 'true') {
$filtered_atts['responsive'] = 'false';
}
// If the format is set to wide, it blows away all other width
// settings.
if ($filtered_atts['format'] == 'wide') {
$filtered_atts['maxwidth'] = $default_sizes['full_width'];
}
// For the benefit of some templates, notify template that
// we're requesting an asset wider than the default size.
global $post;
$is_wide = intval($filtered_atts['maxwidth']) > $default_sizes['width'];
if (WP_DocumentCloud::CACHING_ENABLED) {
// This lets WordPress cache the result of the oEmbed call.
// Thanks to http://bit.ly/1HykA0U for this pattern.
global $wp_embed;
$url = $filtered_atts['url'] = $this->clean_dc_url($atts['url']);
return $wp_embed->shortcode($filtered_atts, $url);
} else {
return wp_oembed_get($atts['url'], $filtered_atts);
}
}
function parse_dc_url($url) {
$patterns = array(
// Document
'{' . WP_DocumentCloud::DOCUMENT_PATTERN . '\.html$}',
// Pages and page variants
'{' . WP_DocumentCloud::DOCUMENT_PATTERN . '.html#document\/p(?P<page_number>[0-9]+)$}',
'{' . WP_DocumentCloud::DOCUMENT_PATTERN . '\/pages\/(?P<page_number>[0-9]+)\.(html|js)$}',
// Notes and note variants
'{' . WP_DocumentCloud::DOCUMENT_PATTERN . '\/annotations\/(?P<note_id>[0-9]+)\.(html|js)$}',
'{' . WP_DocumentCloud::DOCUMENT_PATTERN . '.html#document\/p([0-9]+)/a(?P<note_id>[0-9]+)$}',
'{' . WP_DocumentCloud::DOCUMENT_PATTERN . '.html#annotation\/a(?P<note_id>[0-9]+)$}',
);
$elements = array();
foreach ($patterns as $pattern) {
$perfect_match = preg_match($pattern, $url, $elements);
if ($perfect_match) {
break;
}
}
return $elements;
}
function clean_dc_url($url) {
$elements = $this->parse_dc_url($url);
if (isset($elements['document_slug'])) {
$url = "{$elements['protocol']}://" . WP_DocumentCloud::OEMBED_RESOURCE_DOMAIN . "/documents/{$elements['document_slug']}";
if (isset($elements['page_number'])) {
$url .= "/pages/{$elements['page_number']}";
}
else if (isset($elements['note_id'])) {
$url .= "/annotations/{$elements['note_id']}";
}
$url .= '.html';
}
return $url;
}
// Setup settings for plugin
function add_options_page() {
if (current_user_can('manage_options')) {
add_options_page('DocumentCloud', 'DocumentCloud', 'manage_options',
'documentcloud', array(&$this, 'render_options_page'));
}
}
function render_options_page() { ?>
<h2>DocumentCloud Options</h2>
<form action="options.php" method="post">
<p>Any widths set here will only take effect if you set <code>responsive="false"</code> on an embed.</p>
<?php settings_fields('documentcloud'); ?>
<?php do_settings_sections('documentcloud'); ?>
<p><input class="button-primary" name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" /></p>
</form>
<?php
}
function settings_init() {
if (current_user_can('manage_options')) {
add_settings_section('documentcloud', '',
array(&$this, 'settings_section'), 'documentcloud');
add_settings_field('documentcloud_default_height', 'Default embed height (px)',
array(&$this, 'default_height_field'), 'documentcloud', 'documentcloud');
register_setting('documentcloud', 'documentcloud_default_height');
add_settings_field('documentcloud_default_width', 'Default embed width (px)',
array(&$this, 'default_width_field'), 'documentcloud', 'documentcloud');
register_setting('documentcloud', 'documentcloud_default_width');
add_settings_field('documentcloud_full_width', 'Full-width embed width (px)',
array(&$this, 'full_width_field'), 'documentcloud', 'documentcloud');
register_setting('documentcloud', 'documentcloud_full_width');
}
}
function default_height_field() {
$default_sizes = $this->get_default_sizes();
echo '<input type="text" value="' . esc_html($default_sizes['height']) . '" name="documentcloud_default_height" />';
}
function default_width_field() {
$default_sizes = $this->get_default_sizes();
echo '<input type="text" value="' . esc_html($default_sizes['width']) . '" name="documentcloud_default_width" />';
}
function full_width_field() {
$default_sizes = $this->get_default_sizes();
echo '<input type="text" value="' . esc_html($default_sizes['full_width']) . '" name="documentcloud_full_width" />';
}
function settings_section() {}
function save($post_id) {
// tell the post if we're carrying a wide load
if (current_user_can('edit_posts')) {
$post = get_post($post_id);
// avoid autosave
if (!in_array($post->post_status, array(
'publish', 'draft', 'private', 'future', 'pending'
))
) { return; }
$default_sizes = $this->get_default_sizes();
$default_atts = $this->get_default_atts();
$wide_assets = get_post_meta($post_id, 'wide_assets', true);
$matches = array();
preg_match_all('/'.get_shortcode_regex().'/', $post->post_content, $matches);
$tags = $matches[2];
$args = $matches[3];
foreach($tags as $i => $tag) {
if ($tag == "documentcloud") {
$parsed_atts = shortcode_parse_atts($args[$i]);
$atts = shortcode_atts($default_atts, $parsed_atts);
// get a doc id to keep array keys consistent
if (isset($atts['url'])) {
$elements = $this->parse_dc_url($atts['url']);
if (isset($elements['document_slug'])) {
$meta_key = $elements['document_slug'];
if (isset($elements['page_number'])) {
$meta_key .= "-p{$elements['page_number']}";
}
else if (isset($elements['note_id'])) {
$meta_key .= "-a{$elements['note_id']}";
}
}
} else if (isset($atts['id'])) {
$meta_key = $atts['id'];
}
// if no id, don't bother storing because it's wrong
if (isset($meta_key)) {
$width = intval(isset($parsed_atts['width']) ? $parsed_atts['width'] : $atts['maxwidth']);
if ($atts['format'] == "wide" || $width > $default_sizes['width']) {
$wide_assets[$meta_key] = true;
} else {
$wide_assets[$meta_key] = false;
}
}
}
}
update_post_meta($post_id, 'wide_assets', $wide_assets);
}
}
}
new WP_DocumentCloud;