-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-taste-dive.php
306 lines (268 loc) · 8.25 KB
/
class-taste-dive.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
<?php
/**
* TasteDive main class
*
* @package Yugensoft\TasteDive
*/
namespace Yugensoft\TasteDive;
use Exception;
use WP_Error;
defined( 'ABSPATH' ) || exit;
/**
* Class TasteDive
*
* Controller-esque main class
*/
final class TasteDive {
const DEFAULT_RECOMMENDATIONS_LIMIT = 5;
const DEFAULT_CHAR_LIMIT = 0;
/**
* TasteDive constructor.
*
* @throws Exception Instantiation guard.
*/
public function __construct() {
throw new Exception( 'No instantiation.' );
}
/**
* Registers hooks and adds actions upon plugin being loaded
*/
public static function init_hooks() {
register_activation_hook( TASTE_DIVE_PLUGIN_FILE, array( TasteDiveDb::class, 'db_install' ) );
register_uninstall_hook( TASTE_DIVE_PLUGIN_FILE, array( TasteDiveDb::class, 'db_uninstall' ) );
add_action( 'plugins_loaded', array( TasteDiveDb::class, 'db_update' ) );
add_action( 'init', array( __CLASS__, 'init' ) );
add_action(
'admin_menu',
function () {
add_options_page(
'TasteDive Settings',
'TasteDive',
'manage_options',
'taste-dive-settings',
function () {
echo self::render( 'settings' );
}
);
}
);
add_action( 'admin_init', array( __CLASS__, 'admin_init' ) );
add_action(
'wp_enqueue_scripts',
function () {
wp_enqueue_style( 'taste_dive', plugin_dir_url( __FILE__ ) . 'assets/css/taste_dive.css', array(), TASTE_DIVE_PLUGIN_VERSION );
wp_enqueue_style( 'fontawesome5', 'https://use.fontawesome.com/releases/v5.2.0/css/all.css', array(), TASTE_DIVE_PLUGIN_VERSION );
}
);
}
/**
* Runs on action: init
*/
public static function init() {
add_shortcode( 'tastedive', array( __CLASS__, 'shortcode' ) );
}
/**
* Runs on action: admin_init
*/
public static function admin_init() {
register_setting(
'taste_dive',
'taste_dive_settings',
function ( $input ) {
return $input;
}
);
add_settings_section(
'taste-dive-settings',
'',
function () {},
'taste-dive-settings'
);
$settings = array(
array(
'key' => 'api_key',
'title' => 'API key',
'default' => '',
),
array(
'key' => 'cache_timeout',
'title' => 'Cache timeout<br><small>(minutes, 0 for no cache)</small>',
'default' => TasteDiveDb::CACHE_TIMEOUT_DEFAULT,
),
array(
'key' => 'default_limit',
'title' => 'Default number of recommendations',
'default' => self::DEFAULT_RECOMMENDATIONS_LIMIT,
),
array(
'key' => 'char_limit',
'title' => 'Character limit for descriptions<br><small>(0 for no limit)</small>',
'default' => self::DEFAULT_CHAR_LIMIT,
),
);
$options = get_option( 'taste_dive_settings' );
foreach ( $settings as $setting ) {
add_settings_field(
$setting['key'],
$setting['title'],
function () use ( $setting, $options ) {
$value = isset( $options[ $setting['key'] ] ) ? $options[ $setting['key'] ] : $setting['default'];
echo "<input type='text' id='{$setting['key']}' name='taste_dive_settings[{$setting['key']}]' value='$value' size='40' />";
},
'taste-dive-settings',
'taste-dive-settings'
);
}
}
/**
* Render the [tastedive] shortcode.
* Accepts attributes:
* search - Media title
* type - Media type (e.g. 'movie') [optional]
* limit - How many recommendations to show [optional]
*
* @param array $attrs Tag attributes.
* @param null $content Content enclosed by tags.
* @param string $tag Tag identifier.
*
* @return string
*/
public static function shortcode( $attrs, $content = null, $tag = '' ) {
$attrs = array_change_key_case( (array) $attrs, CASE_LOWER );
// Gather attributes.
$search = self::array_multi_search_with_default( $attrs, array( 'search', 'q' ), false );
$type = self::array_multi_search_with_default( $attrs, array( 'type' ), null );
$limit = self::array_multi_search_with_default(
$attrs,
array(
'count',
'limit',
),
self::DEFAULT_RECOMMENDATIONS_LIMIT
);
// Check for missing required attributes.
if ( false === $search ) {
return self::shortcode_error( new WP_Error( 'search_attr', "No 'search' attribute set." ) );
}
// General settings.
$settings = get_option( 'taste_dive_settings' );
$char_limit = isset( $settings['char_limit'] ) ? $settings['char_limit'] : self::DEFAULT_CHAR_LIMIT;
$recommendations = self::get_recommendations(
$search,
$type,
$limit,
1,
$char_limit
);
if ( is_wp_error( $recommendations ) ) {
return self::shortcode_error( $recommendations );
}
return self::render(
'recommendations',
array(
'search' => $attrs['search'],
'info' => $recommendations['Info'][0],
'recommendations' => $recommendations['Results'],
)
);
}
/**
* Retrieve recommendations from the TasteDive API, or from the cache if possible.
*
* @param string $q Search query.
* @param string|null $type Type of recommendations to return (e.g. 'movie').
* @param int $limit Number of recommendations to return.
* @param int $info Whether to add extended information.
* @param int $char_limit Character limit for descriptions (or 0 for no limit).
*
* @return array|mixed|object|WP_Error Recommendations or error
*/
public static function get_recommendations(
$q,
$type = null,
$limit = self::DEFAULT_RECOMMENDATIONS_LIMIT,
$info = 1,
$char_limit = self::DEFAULT_CHAR_LIMIT
) {
$settings = get_option( 'taste_dive_settings' );
if ( ! isset( $settings['api_key'] ) || empty( $settings['api_key'] ) ) {
return new WP_Error( 'api_key', 'No API key.' );
}
$k = $settings['api_key'];
$q_enc = rawurlencode( $q );
// Check for cache.
$key = "{$q_enc}_{$type}_{$info}_{$limit}_{$char_limit}";
$cache = TasteDiveDb::get_cache( $key );
if ( $cache ) {
return json_decode( $cache['value'], true )['Similar'];
}
// Create endpoint uri.
$query = array(
'k' => $k,
'q' => $q_enc,
'info' => $info,
'limit' => $limit,
);
if ( $type ) {
$query['type'] = $type;
}
$taste_uri = 'https://tastedive.com/api/similar?' . build_query( $query );
// Get data from endpoint.
$data = wp_remote_get( $taste_uri );
if ( $data instanceof WP_Error ) {
return new WP_Error( 'get_failed', 'Failed to access TasteDive API.' );
}
$data = json_decode( $data['body'], true );
if ( empty( $data['Similar']['Results'] ) ) {
return new WP_Error( 'get_failed', "No results found for: $q" );
}
foreach ( $data['Similar']['Results'] as &$item ) {
$item['image'] = WikiImage::get( $item );
if ( $char_limit ) {
$ellipses = strlen( $item['wTeaser'] ) > $char_limit ? '…' : '';
$item['wTeaser'] = substr( $item['wTeaser'], 0, $char_limit ) . $ellipses;
}
}
// Save to cache.
TasteDiveDb::set_cache( $key, $data );
return $data['Similar'];
}
/**
* Render 'view' files
*
* @param string $view Name of view.
* @param array $data Variables to be passed to view.
*
* @return string Rendered view
*/
public static function render( $view, array $data = array() ) {
extract( $data );
ob_start();
include( "view/{$view}.php" );
return ob_get_clean();
}
/**
* Inform the user of an error rendering the shortcode
*
* @param WP_Error $error Shortcode error.
*
* @return string Error description
*/
public static function shortcode_error( WP_Error $error ) {
return '<p>TasteDive shortcode error: ' . $error->get_error_message() . '</p>';
}
/**
* Get the first element of an array, with one of a set of given keys, that is not empty;
* or the default if none are found.
*
* @param array $array Input array.
* @param array $keys Keys to search for.
* @param mixed $default Value to return if none of the keys are found.
*
* @return mixed Found value or default
*/
public static function array_multi_search_with_default( array $array, array $keys, $default ) {
$a = array_intersect_key( $array, array_flip( $keys ) );
return empty( $a ) ? $default : array_values( $a )[0];
}
}