63 linhas
2,3 KiB
PHP
63 linhas
2,3 KiB
PHP
<?php
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Reads from the API with a short cache (5 minutes by default), so moving between tabs does not call the API every time.
|
|
* "Refresh" and every action forget the cache.
|
|
*/
|
|
class INTERWEB_AO_ACCOUNT_Data
|
|
{
|
|
/** @return array|WP_Error array(data, meta) */
|
|
public static function get($path, array $query = array(), $ttl = null)
|
|
{
|
|
$ttl = $ttl === null ? max(60, (int) INTERWEB_AO_ACCOUNT_Settings::get('cache_seconds')) : (int) $ttl;
|
|
$key = 'interweb_ao_account_d_' . md5(INTERWEB_AO_ACCOUNT_Brands::current_id() . '|' . $path . '|' . wp_json_encode($query) . '|' . INTERWEB_AO_ACCOUNT_I18n::lang());
|
|
if ($ttl > 0) {
|
|
$hit = get_transient($key);
|
|
if (is_array($hit)) {
|
|
return $hit;
|
|
}
|
|
}
|
|
$res = INTERWEB_AO_ACCOUNT_Api::request('GET', $path, null, array('query' => $query, 'timeout' => 20));
|
|
if (is_wp_error($res)) {
|
|
return $res;
|
|
}
|
|
$out = array('data' => $res['data'], 'meta' => is_array($res['meta']) ? $res['meta'] : array());
|
|
if ($ttl > 0) {
|
|
set_transient($key, $out, $ttl);
|
|
}
|
|
return $out;
|
|
}
|
|
|
|
/** A list with up to $max rows (pages of 100). @return array|WP_Error */
|
|
public static function rows($path, array $query = array(), $max = 300)
|
|
{
|
|
$rows = array();
|
|
for ($page = 1; $page <= (int) ceil($max / 100); $page++) {
|
|
$res = self::get($path, array_merge($query, array('page' => $page, 'per_page' => 100)));
|
|
if (is_wp_error($res)) {
|
|
return $page === 1 ? $res : $rows;
|
|
}
|
|
foreach ((array) $res['data'] as $r) {
|
|
$rows[] = $r;
|
|
}
|
|
$pages = isset($res['meta']['total_pages']) ? (int) $res['meta']['total_pages'] : 1;
|
|
if ($page >= $pages) {
|
|
break;
|
|
}
|
|
}
|
|
return $rows;
|
|
}
|
|
|
|
public static function forget()
|
|
{
|
|
global $wpdb;
|
|
$wpdb->query($wpdb->prepare(
|
|
"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
|
|
$wpdb->esc_like('_transient_interweb_ao_account_d_') . '%',
|
|
$wpdb->esc_like('_transient_timeout_interweb_ao_account_d_') . '%'
|
|
));
|
|
}
|
|
}
|