| 1 | package Mojolicious::Plugin::Wordpress; | ||
| 2 | use Mojo::Base 'Mojolicious::Plugin'; | ||
| 3 | |||
| 4 | use Mojo::DOM; | ||
| 5 | use Mojo::UserAgent; | ||
| 6 | use Mojo::Util 'trim'; | ||
| 7 | |||
| 8 | use constant DEBUG => $ENV{MOJO_WORDPRESS_DEBUG} || 0; | ||
| 9 | |||
| 10 | our $VERSION = '0.03'; | ||
| 11 | |||
| 12 | has base_url => 'http://localhost/wp-json'; # Will become a Mojo::URL object | ||
| 13 | has meta_replacer => undef; | ||
| 14 | has post_processor => undef; | ||
| 15 | has ua => sub { Mojo::UserAgent->new->max_redirects(3) }; | ||
| 16 | has yoast_meta_key => 'yoast'; | ||
| 17 | |||
| 18 | sub register { | ||
| 19 | my ($self, $app, $config) = @_; | ||
| 20 | my $prefix = $config->{prefix} || 'wp'; | ||
| 21 | |||
| 22 | $self->{meta} = $self->_default_meta($app, $config->{meta} || {}); | ||
| 23 | $self->{prefix} = $prefix; | ||
| 24 | |||
| 25 | $self->$_($config->{$_}) for grep { $config->{$_} } qw(base_url post_processor yoast_meta_key ua); | ||
| 26 | $self->meta_replacer($config->{meta_replacer} || sub { $self->_default_meta_replacer(@_) }); | ||
| 27 | $self->base_url(Mojo::URL->new($self->base_url)) unless ref $self->base_url; | ||
| 28 | |||
| 29 | $app->helper("$prefix.meta_from" => sub { $self->_helper_meta_from(@_) }); | ||
| 30 | $app->helper("$prefix.rewrite_content" => sub { $self->_helper_rewrite_content(@_) }); | ||
| 31 | |||
| 32 | my $default_post_types = [qw(pages posts)]; | ||
| 33 | for my $type (@{$config->{post_types} || $default_post_types}) { | ||
| 34 | (my $singular = $type) =~ s!s$!!; | ||
| 35 | $app->helper("$prefix.get_${singular}_p" => sub { $self->_helper_get_post_p($type => @_) }); | ||
| 36 | $app->helper("$prefix.get_${type}_p" => sub { $self->_helper_get_posts_p($type => @_) }); | ||
| 37 | } | ||
| 38 | |||
| 39 | $self->_add_wp_assets_route($app, $config) if $config->{base_assets_url}; | ||
| 40 | } | ||
| 41 | |||
| 42 | sub _add_wp_assets_route { | ||
| 43 | my ($self, $app, $config) = @_; | ||
| 44 | my $base_url = Mojo::URL->new($config->{base_assets_url}); | ||
| 45 | |||
| 46 | $app->routes->get($config->{base_assets_route} || '/uploads/*proxy_path')->to( | ||
| 47 | base_assets_url => $base_url, | ||
| 48 | cb => sub { | ||
| 49 | my $c = shift; | ||
| 50 | my $url = $base_url->clone; | ||
| 51 | |||
| 52 | push @{$url->path}, split '/', $c->stash('proxy_path'); | ||
| 53 | $c->app->log->debug("[Wordpress] GET $url"); | ||
| 54 | |||
| 55 | return $self->ua->get_p($url)->then(sub { | ||
| 56 | my $proxy_tx = shift; | ||
| 57 | my $proxy_h = $proxy_tx->res->headers; | ||
| 58 | my $res_h = $c->res->headers; | ||
| 59 | |||
| 60 | $res_h->$_($proxy_h->$_) for qw(content_length content_type); | ||
| 61 | $res_h->cache_control($proxy_h->cache_control || 'max-age=86400'); | ||
| 62 | $res_h->etag($proxy_h->etag || Mojo::Util::md5_sum($proxy_tx->res->body)); | ||
| 63 | $res_h->last_modified($proxy_h->last_modified) if $proxy_h->last_modified; | ||
| 64 | $c->render(data => $proxy_tx->res->body); | ||
| 65 | }); | ||
| 66 | } | ||
| 67 | )->name("$self->{prefix}.assets"); | ||
| 68 | } | ||
| 69 | |||
| 70 | sub _arr { ref $_[0] eq 'ARRAY' ? $_[0] : [] } | ||
| 71 | |||
| 72 | sub _default_meta { | ||
| 73 | my ($self, $app, $meta) = @_; | ||
| 74 | |||
| 75 | # "powered_by" is just a dummy value to illustrate that custom %%variables%% | ||
| 76 | # are also supported. | ||
| 77 | return {powered_by => 'Mojolicious', sep => '-', sitename => $app->moniker, %$meta}; | ||
| 78 | } | ||
| 79 | |||
| 80 | sub _default_meta_replacer { | ||
| 81 | my ($self, $c, $str) = @_; | ||
| 82 | my ($meta, $prefix) = @$self{qw(meta prefix)}; | ||
| 83 | my $stash = $c->stash; | ||
| 84 | |||
| 85 | # %%title%% %%primary_category%% %%sep%% %%sitename%% %%whatever%%" | ||
| 86 | $str =~ s!%%(\w+)%%!{$stash->{"${prefix}_${1}"} || $meta->{$1} || "%%$1%%"}!ge; | ||
| 87 | $str; | ||
| 88 | } | ||
| 89 | |||
| 90 | sub _description { | ||
| 91 | my $dom = Mojo::DOM->new(shift->{content}{rendered} || ''); | ||
| 92 | my $text = trim($dom->all_text); | ||
| 93 | return 297 < length $text ? sprintf '%s...', substr $text, 0, 297 : $text; | ||
| 94 | } | ||
| 95 | |||
| 96 | sub _helper_meta_from { | ||
| 97 | my ($self, $c, $post) = @_; | ||
| 98 | return undef unless ref $post eq 'HASH'; | ||
| 99 | |||
| 100 | my ($yoast_key, %meta) = ($self->yoast_meta_key); | ||
| 101 | for my $key (keys %{$post->{x_metadata} || {}}, keys %{$post->{$yoast_key} || {}}) { | ||
| 102 | next unless my $val = $post->{x_metadata}{$key} || $post->{$yoast_key}{$key}; | ||
| 103 | my $meta_key = $key; | ||
| 104 | next unless $meta_key =~ s!^_?yoast_wpseo_!! or $post->{$yoast_key}{$key}; | ||
| 105 | $meta_key =~ s!-!_!g; | ||
| 106 | $meta{$meta_key} ||= $val; | ||
| 107 | } | ||
| 108 | |||
| 109 | $meta{description} | ||
| 110 | ||= delete $meta{metadesc} || $meta{opengraph_description} || $meta{twitter_description} || _description($post); | ||
| 111 | $meta{title} ||= $meta{opengraph_title} || $meta{twitter_title} || ''; | ||
| 112 | $meta{"opengraph_$_"} ||= $meta{"twitter_$_"} || $meta{$_} for qw(description title); | ||
| 113 | $meta{twitter_description} ||= $meta{opengraph_description}; | ||
| 114 | $meta{twitter_title} ||= $meta{opengraph_title} || $meta{title}; | ||
| 115 | |||
| 116 | if (my ($base_url, $url_for) = $self->_rewrite_asset_url_info($c)) { | ||
| 117 | for my $k (keys %meta) { | ||
| 118 | $meta{$k} =~ s!\b$base_url/?(\S+)!{$url_for->($1)->to_abs}!ge; | ||
| 119 | } | ||
| 120 | } | ||
| 121 | |||
| 122 | for my $key (keys %meta) { | ||
| 123 | my $prefixed = "$self->{prefix}_$key"; | ||
| 124 | $meta{$prefixed} = $self->meta_replacer->($c, delete $meta{$key} // ''); | ||
| 125 | delete $meta{$prefixed} unless length $meta{$prefixed}; | ||
| 126 | } | ||
| 127 | |||
| 128 | return \%meta; | ||
| 129 | } | ||
| 130 | |||
| 131 | sub _helper_get_post_p { | ||
| 132 | my ($self, $type, $c, $params) = @_; | ||
| 133 | $params = {slug => $params} unless ref $params; | ||
| 134 | |||
| 135 | my %query = %$params; | ||
| 136 | delete $params->{post_processor}; | ||
| 137 | |||
| 138 | my $processor = $params->{post_processor} || $self->post_processor; | ||
| 139 | return $self->_raw(get_p => "wp/v2/$type", \%query)->then(sub { | ||
| 140 | my $wp_res = shift->res; | ||
| 141 | my $post = _arr($wp_res->json)->[0]; | ||
| 142 | return $post && $processor ? $c->$processor($post) : $post; | ||
| 143 | }); | ||
| 144 | } | ||
| 145 | |||
| 146 | sub _helper_get_posts_p { | ||
| 147 | my ($self, $type, $c, $params) = @_; | ||
| 148 | |||
| 149 | my %query = %{$params || {}}; | ||
| 150 | delete $query{$_} for qw(all post_processor); | ||
| 151 | $query{page} = 1 if $params->{all}; | ||
| 152 | $query{per_page} = 100 if $params->{all} and !$query{per_page}; | ||
| 153 | |||
| 154 | my $processor = $params->{post_processor} || $self->post_processor; | ||
| 155 | my ($gather, @posts); | ||
| 156 | $gather = sub { | ||
| 157 | my $wp_res = shift->res; | ||
| 158 | |||
| 159 | for my $post (@{_arr($wp_res->json)}) { | ||
| 160 | push @posts, $processor ? $c->$processor($post) : $post; | ||
| 161 | } | ||
| 162 | |||
| 163 | # Done getting all posts | ||
| 164 | my $n_pages = $wp_res->headers->header('x-wp-totalpages') || 1; | ||
| 165 | return \@posts if !$params->{all} or $n_pages <= $query{page}; | ||
| 166 | |||
| 167 | # Fetch more | ||
| 168 | $query{page}++; | ||
| 169 | $self->_raw(get_p => 'wp/v2/posts', \%query)->then($gather); | ||
| 170 | }; | ||
| 171 | |||
| 172 | return $self->_raw(get_p => "wp/v2/$type", \%query)->then($gather); | ||
| 173 | } | ||
| 174 | |||
| 175 | sub _helper_rewrite_content { | ||
| 176 | my ($self, $c) = @_; | ||
| 177 | my $content = Mojo::DOM->new($_[2] // ''); | ||
| 178 | |||
| 179 | if (my ($base_url, $url_for) = $self->_rewrite_asset_url_info($c)) { | ||
| 180 | $content->find(qq([src^="$base_url"], [srcset*="$base_url"]))->each(sub { | ||
| 181 | for my $k (qw(src srcset)) { | ||
| 182 | $_[0]->{$k} =~ s!\b$base_url/?(\S+)!{$url_for->($1)}!ge if $_[0]->{$k}; | ||
| 183 | } | ||
| 184 | }); | ||
| 185 | } | ||
| 186 | |||
| 187 | $content->find('img')->each(sub { | ||
| 188 | delete $_[0]->{$_} for qw(height width); | ||
| 189 | }); | ||
| 190 | |||
| 191 | return $content; | ||
| 192 | } | ||
| 193 | |||
| 194 | sub _raw { | ||
| 195 | my ($self, $method, $path, $query, @data) = @_; | ||
| 196 | my $url = $self->base_url->clone; | ||
| 197 | |||
| 198 | # Want the query params sorted to improve caching | ||
| 199 | $url->query(ref $query eq 'ARRAY' ? $query : [map { ($_ => $query->{$_}) } sort keys %$query]); | ||
| 200 | push @{$url->path}, split '/', $path; | ||
| 201 | |||
| 202 | warn "[Wordpress] $method $url\n" if DEBUG; | ||
| 203 | return $self->ua->$method($url, @data); | ||
| 204 | } | ||
| 205 | |||
| 206 | sub _rewrite_asset_url_info { | ||
| 207 | my ($self, $c) = @_; | ||
| 208 | my $assets_route_name = "$self->{prefix}.assets"; | ||
| 209 | my $assets_route = $c->app->routes->lookup($assets_route_name) or return; | ||
| 210 | |||
| 211 | return ($assets_route->to->{base_assets_url}->to_string, | ||
| 212 | sub { $c->url_for($assets_route_name, {proxy_path => $_[0]}) }); | ||
| 213 | } | ||
| 214 | |||
| 215 | 1; | ||
| 216 | |||
| 217 | =encoding utf8 | ||
| 218 | |||
| 219 | =head1 NAME | ||
| 220 | |||
| 221 | Mojolicious::Plugin::Wordpress - Use Wordpress as a headless CMS | ||
| 222 | |||
| 223 | =head1 SYNOPSIS | ||
| 224 | |||
| 225 | use Mojolicious::Lite; | ||
| 226 | plugin wordpress => {base_url => "https://wordpress.example.com/wp-json"}; | ||
| 227 | |||
| 228 | get "/page/:slug" => sub { | ||
| 229 | my $c = shift->render_later; | ||
| 230 | $c->wp->get_page_p($c->stash("slug"))->then(sub { | ||
| 231 | my $page = shift; | ||
| 232 | $c->render(json => $page); | ||
| 233 | }); | ||
| 234 | }; | ||
| 235 | |||
| 236 | =head1 DESCRIPTION | ||
| 237 | |||
| 238 | L<Mojolicious::Plugin::Wordpress> is a plugin for getting data using the | ||
| 239 | Wordpress JSON API. | ||
| 240 | |||
| 241 | This plugin is currently EXPERIMENTAL. Let me know if you have any feedback at | ||
| 242 | L<https://github.com/jhthorsen/mojolicious-plugin-wordpress/issues>. | ||
| 243 | |||
| 244 | =head1 HELPERS | ||
| 245 | |||
| 246 | =head2 get_post_p | ||
| 247 | |||
| 248 | my $promise = $c->wp->get_post_p; | ||
| 249 | my $promise = $c->wp->get_post_p($slug); | ||
| 250 | my $promise = $c->wp->get_post_p(\%query); | ||
| 251 | |||
| 252 | This helper will be available, dependent on what you set L</post_types> to. It | ||
| 253 | will return a L<Mojo::Promise> that will get a C<$post> hash-ref or C<undef> in | ||
| 254 | the fullfillment callback. The C<$post> hash-ref will be exactly what was | ||
| 255 | returned through the API from Wordpress, or whatever the L</post_processor> has | ||
| 256 | changed it to. | ||
| 257 | |||
| 258 | =head2 get_posts_p | ||
| 259 | |||
| 260 | my $promise = $c->wp->get_posts_p; | ||
| 261 | my $promise = $c->wp->get_posts_p(\%query); | ||
| 262 | my $promise = $c->wp->get_posts_p({all => 1, post_processor => sub { ... }}); | ||
| 263 | |||
| 264 | This helper will be available, dependent on what you set L</post_types> to. It | ||
| 265 | will return a L<Mojo::Promise> that will get an array-ref of C<$post> hash refs | ||
| 266 | in the fullfillment callback. A C<$post> hash-ref will be exactly what was | ||
| 267 | returned through the API from Wordpress, or whatever the L</post_processor> has | ||
| 268 | changed it to. | ||
| 269 | |||
| 270 | =head2 meta_from | ||
| 271 | |||
| 272 | my $meta = $c->wp->meta_from(\%post); | ||
| 273 | |||
| 274 | This helper will extract meta information from the Wordpress post and return a | ||
| 275 | C<%hash> that looks something like this: | ||
| 276 | |||
| 277 | { | ||
| 278 | wp_canonical => "", | ||
| 279 | wp_title => "", | ||
| 280 | wp_metadesc => "", | ||
| 281 | wp_description => "", | ||
| 282 | wp_opengraph_title => "", | ||
| 283 | wp_opengraph_description => "", | ||
| 284 | wp_twitter_title => "", | ||
| 285 | wp_twitter_description => "", | ||
| 286 | ... | ||
| 287 | } | ||
| 288 | |||
| 289 | Note that some keys might be missing or some keys might be added, depending on | ||
| 290 | how the Wordpress server has been set up. | ||
| 291 | |||
| 292 | Suggested Wordpress plugins: L<https://wordpress.org/plugins/wordpress-seo/> | ||
| 293 | and L<https://github.com/jhthorsen/wp-api-yoast-meta>. | ||
| 294 | |||
| 295 | =head2 rewrite_content | ||
| 296 | |||
| 297 | $dom = $c->wp->rewrite_content($post->{content}{rendered}); | ||
| 298 | |||
| 299 | This helper will rewrite a piece of HTML from Wordpress with the following | ||
| 300 | rules: | ||
| 301 | |||
| 302 | =over 2 | ||
| 303 | |||
| 304 | =item * Asset URL | ||
| 305 | |||
| 306 | Will replace "src" and "srcset" on images with an URL to the local application, | ||
| 307 | if L</base_assets_url> is set in config or a "wp.assets" route could be found. | ||
| 308 | |||
| 309 | =item * Images | ||
| 310 | |||
| 311 | All "height" and "width" attributes will be removed from "img" tags. | ||
| 312 | |||
| 313 | =back | ||
| 314 | |||
| 315 | Note that more rules might be added in the future. | ||
| 316 | |||
| 317 | =head1 ATTRIBUTES | ||
| 318 | |||
| 319 | =head2 base_url | ||
| 320 | |||
| 321 | my $url = $wp->base_url; | ||
| 322 | my $wp = $wp->base_url("https://wordpress.example.com/wp-json"); | ||
| 323 | |||
| 324 | Holds the base URL to the Wordpress server API, including "/wp-json". | ||
| 325 | |||
| 326 | =head2 meta_replacer | ||
| 327 | |||
| 328 | my $cb = $wp->meta_replacer; | ||
| 329 | my $wp = $wp->meta_replacer(sub { my ($c, $str) = @_ }); | ||
| 330 | |||
| 331 | A callback used to search and replace meta data when calling L</meta_from>. | ||
| 332 | The default callback will search and replace all occurances of "%%some_key%%" | ||
| 333 | with C<wp_$some_key> from L<Mojolicious::Controller/stash>. | ||
| 334 | |||
| 335 | =head2 post_processor | ||
| 336 | |||
| 337 | my $cb = $wp->post_processor; | ||
| 338 | my $wp = $wp->post_processor(sub { my ($c, $post) = @_ }); | ||
| 339 | |||
| 340 | A code block that can be used to post process the JSON response from Wordpress. | ||
| 341 | |||
| 342 | =head2 ua | ||
| 343 | |||
| 344 | my $ua = $wp->ua; | ||
| 345 | my $wp = $wp->ua(Mojo::UserAgent->new); | ||
| 346 | |||
| 347 | Holds a L<Mojo::UserAgent> object that is used to get data from Wordpress. | ||
| 348 | |||
| 349 | =head2 yoast_meta_key | ||
| 350 | |||
| 351 | my $str = $wp->yaost_meta_key; | ||
| 352 | my $wp = $wp->yaost_meta_key("yoast"); | ||
| 353 | |||
| 354 | The key in the post JSON response that holds | ||
| 355 | L<Yoast|https://wordpress.org/plugins/wordpress-seo/> meta information. | ||
| 356 | |||
| 357 | This information is not enabled by default. To enable it through the API, you | ||
| 358 | can add this plugin: L<https://github.com/jhthorsen/wp-api-yoast-meta>. | ||
| 359 | |||
| 360 | =head1 METHODS | ||
| 361 | |||
| 362 | =head2 register | ||
| 363 | |||
| 364 | $wp->register($app, \%config); | ||
| 365 | $app->plugin(wordpress => \%config); | ||
| 366 | |||
| 367 | Used to register this plugin. C<%config> can have: | ||
| 368 | |||
| 369 | =over 2 | ||
| 370 | |||
| 371 | =item * base_assets_url | ||
| 372 | |||
| 373 | If C<base_assets_url> is set, then a new route will be added to your C<$app>, | ||
| 374 | that will proxy GET requests to your Wordpress backend. This can be useful, | ||
| 375 | if you want to mask/hide Wordpress URLs and rather let everything go through | ||
| 376 | your L<Mojolicious> application. | ||
| 377 | |||
| 378 | Example value: | ||
| 379 | |||
| 380 | {base_assets_url => 'https://wordpress.com/wp-content/uploads'} | ||
| 381 | |||
| 382 | The path added will either be defined by the C<base_assets_route> config | ||
| 383 | variable or default to "/uploads/*proxy_path", and the route will be named | ||
| 384 | "wp.assets". | ||
| 385 | |||
| 386 | =item * base_url | ||
| 387 | |||
| 388 | See L</base_url>. | ||
| 389 | |||
| 390 | =item * post_processor | ||
| 391 | |||
| 392 | See L</post_processor>. | ||
| 393 | |||
| 394 | =item * post_types | ||
| 395 | |||
| 396 | A list of post types available in the CMS. Defaults to: | ||
| 397 | |||
| 398 | ["pages", "posts"] | ||
| 399 | |||
| 400 | This list will generate helpers to fetch data from Wordpress. Example default | ||
| 401 | helpers are: | ||
| 402 | |||
| 403 | my $p = $c->wp->get_page_p(...); | ||
| 404 | my $p = $c->wp->get_pages_p(...); | ||
| 405 | my $p = $c->wp->get_post_p(...); | ||
| 406 | my $p = $c->wp->get_posts_p(...); | ||
| 407 | |||
| 408 | See L</get_post_p> and L</get_posts_p> for more information. | ||
| 409 | |||
| 410 | Suggested Wordpress plugin: | ||
| 411 | L<https://wordpress.org/plugins/custom-post-type-maker/> | ||
| 412 | |||
| 413 | =item * prefix | ||
| 414 | |||
| 415 | The prefix for the helpers. Defaults to "wp". | ||
| 416 | |||
| 417 | =item * ua | ||
| 418 | |||
| 419 | See L</ua>. | ||
| 420 | |||
| 421 | =item * yoast_meta_key | ||
| 422 | |||
| 423 | See L</yoast_meta_key>. | ||
| 424 | |||
| 425 | =back | ||
| 426 | |||
| 427 | =head1 AUTHOR | ||
| 428 | |||
| 429 | Jan Henning Thorsen | ||
| 430 | |||
| 431 | =head1 COPYRIGHT AND LICENSE | ||
| 432 | |||
| 433 | Copyright (C), Jan Henning Thorsen. | ||
| 434 | |||
| 435 | This program is free software, you can redistribute it and/or modify it under | ||
| 436 | the terms of the Artistic License version 2.0. | ||
| 437 | |||
| 438 | =cut |