Files
beep/includes/class-quotes.php
T

103 lines
3.5 KiB
PHP

<?php
/**
* Beep Quote Posts
*/
if (!defined('ABSPATH')) exit;
class Beep_Quotes {
const QUOTED_META = 'beep_quoted_post_id';
/**
* Quote a beep. Stores the quoted post ID in the new beep's meta.
*/
public static function create_quote($new_post_id, $quoted_post_id) {
$quoted = get_post($quoted_post_id);
if (!$quoted || $quoted->post_type !== Beep_CPT::POST_TYPE) {
return new WP_Error('invalid_quoted', 'Cannot quote that beep.');
}
update_post_meta($new_post_id, self::QUOTED_META, (int) $quoted_post_id);
return true;
}
/**
* Get the quoted post ID for a beep.
*/
public static function get_quoted_post_id($post_id) {
return (int) get_post_meta($post_id, self::QUOTED_META, true);
}
/**
* Get the quoted post data for rendering.
*/
public static function get_quoted_post($post_id) {
$quoted_id = self::get_quoted_post_id($post_id);
if (!$quoted_id) return null;
$post = get_post($quoted_id);
if (!$post || $post->post_status !== 'publish') return null;
$author_id = $post->post_author;
$author = get_userdata($author_id);
$avatar = get_user_meta($author_id, 'beep_avatar', true);
if (!$avatar) {
$avatar = 'https://www.gravatar.com/avatar/' . md5(strtolower($author->user_email ?? '')) . '?s=48&d=mp';
}
$content = preg_replace('/\[beep:\d+\]/', '', $post->post_content);
return [
'id' => $post->ID,
'content' => $content,
'time_ago'=> self::time_ago(strtotime($post->post_date)),
'author' => [
'id' => $author_id,
'name' => $author->display_name ?? 'Unknown',
'username' => $author->user_login ?? '',
'avatar' => $avatar,
],
];
}
/**
* Render the quoted beep HTML (the embedded original beep).
*/
public static function render_quoted_post($post_id) {
$quoted = self::get_quoted_post($post_id);
if (!$quoted) return '';
$author = $quoted['author'];
$avatar = esc_url($author['avatar']);
$name = esc_html($author['name']);
$handle = esc_html('@' . $author['username']);
$content = make_clickable(wp_kses_post($quoted['content']));
$time = esc_html($quoted['time_ago']);
$qid = esc_attr($quoted['id']);
return '<div class="beep-quoted-post" data-quoted-id="' . $qid . '">' .
'<div class="beep-quoted-avatar">' .
'<img src="' . $avatar . '" alt="' . $name . '" width="36" height="36">' .
'</div>' .
'<div class="beep-quoted-body">' .
'<div class="beep-quoted-meta">' .
'<span class="beep-quoted-name">' . $name . '</span>' .
'<span class="beep-quoted-handle">' . $handle . '</span>' .
'<span class="beep-quoted-dot">·</span>' .
'<span class="beep-quoted-time">' . $time . '</span>' .
'</div>' .
'<div class="beep-quoted-text">' . $content . '</div>' .
'</div></div>';
}
private static function time_ago($timestamp) {
$diff = time() - $timestamp;
if ($diff < 0) $diff = 0;
if ($diff < 60) return $diff . 's';
if ($diff < 3600) return floor($diff / 60) . 'm';
if ($diff < 86400) return floor($diff / 3600) . 'h';
if ($diff < 604800) return floor($diff / 86400) . 'd';
return gmdate('M j', $timestamp);
}
}