get_header( 'x_api_key' ); if ( ! empty( $header_key ) ) { $apikey = is_string( $header_key ) ? trim( $header_key ) : ''; } elseif ( isset( $request['apikey'] ) ) { $apikey = is_string( $request['apikey'] ) ? trim( $request['apikey'] ) : ''; } else { $response = new WP_REST_Response( "error, apikey not set" ); $response->set_status( 400 ); return $response; } $settings = get_option( 'monok_settings_option_name' ); $savedApiKey = isset( $settings['api_keys_0'] ) ? trim( $settings['api_keys_0'] ) : ''; if ( ! is_string($savedApiKey) || ! is_string($apikey) || strlen($savedApiKey) < 8 || strlen($apikey) < 8 || ! hash_equals($savedApiKey, $apikey) ) { $response = new WP_REST_Response( "error, apikey not valid" ); $response->set_status( 400 ); return $response; } return null; } function monok_no_cache_headers( $r ) { $r->header( 'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0, private' ); $r->header( 'Pragma', 'no-cache' ); $r->header( 'Expires', '0' ); $r->header( 'Surrogate-Control', 'no-store' ); $r->header( 'Vary', 'Accept-Encoding' ); return $r; } class MonokSettings { private $monok_settings_options; public function __construct() { add_action( 'admin_menu', array( $this, 'monok_settings_add_plugin_page' ) ); add_action( 'admin_init', array( $this, 'monok_settings_page_init' ) ); } public function monok_settings_add_plugin_page() { add_options_page( 'Monok Settings', // page_title 'Monok Settings', // menu_title 'manage_options', // capability 'monok-settings', // menu_slug array( $this, 'monok_settings_create_admin_page' ) // function ); } public function monok_settings_create_admin_page() { $this->monok_settings_options = get_option( 'monok_settings_option_name' ); ?>

Monok Settings

Connect your Monok account to receive articles as drafts or published posts. Saving your API key while this plugin is active allows Monok to read site metadata and deliver articles. Publication confirmations send article text, titles, image URLs and canonical URLs to app.monok.com. A Monok account is required; service charges may apply.

4 ? str_repeat( '•', strlen( $existing ) - 4 ) . substr( $existing, -4 ) : $existing; if ( $submitted !== $mask && strlen( $submitted ) >= 8 && strpos( $submitted, '•' ) === false ) { $sanitary_values['api_keys_0'] = $submitted; } else { $sanitary_values['api_keys_0'] = $existing; } } if ( isset( $input['photo_caption_visibility_1'] ) ) { $sanitary_values['photo_caption_visibility_1'] = $input['photo_caption_visibility_1'] === 'Enabled' ? 'Enabled' : 'Disabled'; } if ( isset( $input['js_scripts'] ) ) { $sanitary_values['js_scripts'] = $input['js_scripts'] === 'Enabled' ? 'Enabled' : 'Disabled'; } return $sanitary_values; } public function monok_settings_section_info() { } public function api_keys_0_callback() { $saved = isset( $this->monok_settings_options['api_keys_0'] ) ? $this->monok_settings_options['api_keys_0'] : ''; $masked = strlen( $saved ) > 4 ? str_repeat( '•', strlen( $saved ) - 4 ) . substr( $saved, -4 ) : $saved; printf( '

Paste a new key to rotate. Leave unchanged to keep the current one.

', esc_attr( $masked ), esc_attr( $saved ), esc_attr( $masked ) ); } public function js_scripts_callback() { ?> ]+\[\/caption]/i', '', $text); } return $text; } function monok_sync_set_photo_url($text, $photoUrl){ if ( is_string($photoUrl)) { $text = preg_replace('/ 15, 'redirection' => 2, 'limit_response_size' => 15 * 1024 * 1024 + 1, ) ); if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) { throw new Exception( 'Unable to download featured image' ); } $image_data = wp_remote_retrieve_body( $response ); $filename_hashed = hash('md5', $image_url) . $extention; // echo $filename_hashed; $filename = basename($image_url); } $image_size = @getimagesizefromstring( $image_data ); if ( strlen( $image_data ) > 15 * 1024 * 1024 || ! $image_size || ! in_array( $image_size[2], array( IMAGETYPE_JPEG, IMAGETYPE_PNG ), true ) || $image_size[0] * $image_size[1] > 40000000 ) { throw new Exception( 'Invalid or oversized featured image' ); } $file = $upload_dir['basedir'] . '/' . $filename_hashed; if(wp_mkdir_p($upload_dir['path'])){ $file = $upload_dir['path'] . '/' . $filename_hashed; } // check image size in pixels $imgsizeKb = strlen($image_data)/1024; if(!$thumb_image_data){ $imgsize = getimagesizefromstring($image_data); $total_pixels = $imgsize[0] * $imgsize[1]; $jpeg_quality = ($total_pixels * -0.000006) + 100; // evaluate how much jpeg compression we need $jpeg_quality = floor($jpeg_quality); $jpeg_quality = $jpeg_quality > 75 ? 75 : ($jpeg_quality < 10 ? 10 : $jpeg_quality); // create image obj from our image_data string (works on both downloaded and base64 decoded) $image_data = imagecreatefromstring($image_data); // compress image and save as JPEG, ($imagejpegres not used but maybe later to check if something failed) $imagejpegres = imagejpeg($image_data, $file, $jpeg_quality); $mime_type = "image/jpeg"; }else{ //TODO: fix mime type so gif and png that are less than 60kb can be stored correctly //tested with mimetype intact in base64, got corrupt image. file_put_contents($file, $image_data); } // $wp_filetype = wp_check_filetype($file, null ); $attachment = array( 'post_mime_type' => $mime_type, // 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); $res1= wp_update_attachment_metadata( $attach_id, $attach_data ); $res2 = set_post_thumbnail( $post_id, $attach_id ); $featured_url = wp_get_attachment_url( $attach_id ); update_post_meta( $attach_id, '_wp_attachment_image_alt', $alt ); return $featured_url; } function monok_sync_linkback($post){ if ( ! monok_service_enabled() ) return; $host = 'https://app.monok.com'; $monokId = $post->monokId; if($monokId){ $protocols = array( 'http://', 'https://', 'http://www.', 'https://www.', 'www.' ,'/'); $siteUrl = site_url(); $domain = str_replace( $protocols, '', $siteUrl ); // Get API key from settings $monok_settings_options = get_option( 'monok_settings_option_name' ); $apikey = isset($monok_settings_options['api_keys_0']) ? $monok_settings_options['api_keys_0'] : ''; $body = array( 'puff' => array( 'title' => $post->post_title, 'article' => wp_strip_all_tags($post->post_content), ), 'thumbnail' => get_the_post_thumbnail_url($post), 'url'=>get_permalink($post), 'postId'=>$post->ID, 'source'=>$domain, 'siteUrl'=>$siteUrl, 'id' => $monokId, 'userId' => $domain.'-WP' ); $response = wp_remote_post( $host.'/api/v1/linkback', array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 2, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array( 'X-API-Key' => $apikey ), 'body' => $body, 'cookies' => array() ) ); if ( is_wp_error( $response ) ) { // $error_message = $response->get_error_message(); // echo "Something went wrong: $error_message"; } else { // echo 'Response:
';
            // print_r( $response );
            // echo '
'; } } } function monok_sync_on_all_status_transitions( $new_status, $old_status, $post ) { $host = 'https://app.monok.com'; //Publish (when end-user does it) if($new_status != $old_status && $new_status == 'publish' && $post->monokId){ monok_sync_linkback($post); } } function monok_sync_getPostObject($puff){ // Create post object $new_post = array( // 'ID' => $postID, 'post_title' => $puff->title, 'post_name' => $puff->slug, 'post_content' => $puff->content, // 'post_content' => monok_sync_getContent($puff, $postID), 'post_status' => 'draft', 'post_author' => monok_sync_getAuthor($puff), 'post_category' => monok_sync_getCategories($puff), 'post_type' => monok_sync_getPostType($puff), 'meta_input' => array_merge(array( 'monokId' => $puff->id ), monok_sync_getMetaTags($puff, false)) ); return $new_post; } /** Import delivery-only JPEG data URLs before content is persisted by WordPress. */ function monok_store_body_images( $content, $post_id ) { if ( stripos( $content, 'data:' ) === false ) return $content; if ( ! class_exists( 'WP_HTML_Tag_Processor' ) ) { throw new Exception( 'Inline images require the WordPress HTML Tag Processor' ); } $processor = new WP_HTML_Tag_Processor( $content ); $pending = array(); $total = 0; while ( $processor->next_tag( 'IMG' ) ) { $src = $processor->get_attribute( 'src' ); if ( ! is_string( $src ) || stripos( $src, 'data:' ) !== 0 ) continue; if ( count( $pending ) >= 50 ) throw new Exception( 'Too many article images' ); if ( strlen( $src ) > 21 * 1024 * 1024 || ! preg_match( '~^data:image/(?:jpeg|jpg);base64,([A-Za-z0-9+/]+={0,2})$~i', $src, $match ) ) { throw new Exception( 'Invalid JPEG body image' ); } $bytes = base64_decode( $match[1], true ); if ( $bytes === false || strlen( $bytes ) > 15 * 1024 * 1024 ) throw new Exception( 'Article image is too large or invalid' ); $size = @getimagesizefromstring( $bytes ); if ( ! $size || $size[2] !== IMAGETYPE_JPEG || $size[0] * $size[1] > 40000000 ) throw new Exception( 'Invalid JPEG body image' ); $total += strlen( $bytes ); if ( $total > 15 * 1024 * 1024 ) throw new Exception( 'Article images exceed the size limit' ); $pending[] = array( 'bytes' => $bytes, 'hash' => hash( 'sha256', $bytes ), 'description' => (string) $processor->get_attribute( 'alt' ), 'copyright' => (string) $processor->get_attribute( 'data-monok-copyright' ), ); } // Validate all images before writing any media or modifying the article. $urls = array(); foreach ( $pending as $image ) { $hash = $image['hash']; if ( isset( $urls[$hash] ) ) continue; $existing = get_posts( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'numberposts' => 1, 'meta_key' => '_monok_body_image_hash', 'meta_value' => $hash, 'fields' => 'ids', ) ); $attachment_id = $existing ? $existing[0] : 0; if ( ! $attachment_id ) { $upload = wp_upload_bits( 'monok-body-' . $hash . '.jpg', null, $image['bytes'] ); if ( ! empty( $upload['error'] ) ) throw new Exception( 'Unable to store article image' ); $attachment_id = wp_insert_attachment( array( 'post_mime_type' => 'image/jpeg', 'post_title' => sanitize_text_field( $image['description'] ), 'post_excerpt' => sanitize_text_field( $image['copyright'] ), 'post_content' => '', 'post_status' => 'inherit', ), $upload['file'], $post_id, true ); if ( is_wp_error( $attachment_id ) ) { wp_delete_file( $upload['file'] ); throw new Exception( 'Unable to create article image attachment' ); } update_post_meta( $attachment_id, '_monok_body_image_hash', $hash ); } update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $image['description'] ) ); update_post_meta( $attachment_id, '_monok_image_copyright', sanitize_text_field( $image['copyright'] ) ); require_once ABSPATH . 'wp-admin/includes/image.php'; if ( ! wp_get_attachment_metadata( $attachment_id ) ) { $metadata = wp_generate_attachment_metadata( $attachment_id, get_attached_file( $attachment_id ) ); if ( ! $metadata ) throw new Exception( 'Unable to process article image attachment' ); wp_update_attachment_metadata( $attachment_id, $metadata ); } $url = wp_get_attachment_url( $attachment_id ); if ( ! $url ) throw new Exception( 'Article image URL is unavailable' ); $urls[$hash] = $url; } $processor = new WP_HTML_Tag_Processor( $content ); $index = 0; while ( $processor->next_tag( 'IMG' ) ) { $src = $processor->get_attribute( 'src' ); if ( ! is_string( $src ) || stripos( $src, 'data:' ) !== 0 ) continue; $image = $pending[$index++]; $processor->set_attribute( 'src', $urls[$image['hash']] ); $processor->remove_attribute( 'srcset' ); } return $processor->get_updated_html(); } function monok_sync_getContent($puff, $postID){ $content = monok_store_body_images( $puff->content, $postID ); $thumbImageData = $puff->thumbImageData; //Upload photo if ($puff->thumbnail || $thumbImageData) { $alt = $puff->thumbAlt ? $puff->thumbAlt : ($puff->thumbImageDescription ? $puff->thumbImageDescription : $puff->title); $photoUrl = monok_sync_Generate_Featured_Image($puff->thumbnail, $postID, $thumbImageData, $alt); $content = monok_sync_set_photo_url($content, $photoUrl); } $content = monok_sync_set_photo_caption_visibility($content); return wp_kses_post( $content ); } function monok_sync_getAuthor($puff) { $authors = get_users(array( 'orderby' => 'display_name' )); if (count($authors) === 0) { return null; } // Step 1: Find by author ID foreach ($authors as $author) { if ($author->ID === $puff->author->id) { return $author->ID; } } // Step 2: Find by author name (case insensitive) $puffAuthorNameLower = strtolower($puff->author->name); foreach ($authors as $author) { if (strtolower($author->display_name) === $puffAuthorNameLower) { return $author->ID; } } // Step 3: Sort authors by roles to determine priority usort($authors, function($a, $b) { $rolePriority = [ 'editor' => 1, 'author' => 2, 'contributor' => 3, 'default' => 4 ]; $aRole = isset($a->roles[0]) ? $a->roles[0] : 'default'; $bRole = isset($b->roles[0]) ? $b->roles[0] : 'default'; return $rolePriority[$aRole] <=> $rolePriority[$bRole]; }); // Step 4: Return the first author in the sorted list return reset($authors)->ID; } function monok_sync_getTags($puff) { // First, check if the puff->tags array contains "create tags" (case-insensitive) if (isset($puff->tags) && is_array($puff->tags)) { foreach ($puff->tags as $tag) { if (strtolower($tag) === 'create tags') { // If found, delegate tag generation to the categories-based function return monok_sync_getCategoryTags($puff); } } } // Initialize an array to hold matching tag IDs $matching_tag_ids = array(); // Check if puff has tags if (isset($puff->tags) && is_array($puff->tags)) { // Get available tags $available_tags = get_terms(array( 'taxonomy' => 'post_tag', 'hide_empty' => false, )); // Convert all available tag names to lowercase for case-insensitive comparison $available_tag_map = array(); foreach ($available_tags as $tag) { $available_tag_map[strtolower($tag->name)] = $tag->term_id; } // Loop through each puff tag foreach ($puff->tags as $puff_tag) { // Convert the puff tag to lowercase $puff_tag_lower = strtolower($puff_tag); // Check if the puff tag matches any available tag if (isset($available_tag_map[$puff_tag_lower])) { $matching_tag_ids[] = $available_tag_map[$puff_tag_lower]; } } } return $matching_tag_ids; } function monok_sync_getCategoryTags($puff) { $matching_tag_ids = array(); // Retrieve available tags as before $available_tags = get_terms(array( 'taxonomy' => 'post_tag', 'hide_empty' => false, )); // Create a lookup map of lowercase tag names to term IDs $available_tag_map = array(); foreach ($available_tags as $tag) { $available_tag_map[strtolower($tag->name)] = $tag->term_id; } // Check if puff has categories and iterate through them if (isset($puff->categories) && is_array($puff->categories)) { foreach ($puff->categories as $category) { // Ensure the category object has a name field if (isset($category->name) && $category->name) { $cat_name_lower = strtolower($category->name); if (isset($available_tag_map[$cat_name_lower])) { $matching_tag_ids[] = $available_tag_map[$cat_name_lower]; } } } } // If no matching tags were found from categories... if (empty($matching_tag_ids)) { // ...and if there is at least one category, create a new tag using the first category's name if (isset($puff->categories[0]) && !empty($puff->categories[0]->name)) { $new_tag_name = $puff->categories[0]->name; $result = wp_insert_term($new_tag_name, 'post_tag'); if (!is_wp_error($result)) { $matching_tag_ids[] = $result['term_id']; } } } else { // If one or more matching tags were found, limit the array to a maximum of 5 tags $matching_tag_ids = array_slice($matching_tag_ids, 0, 5); } return $matching_tag_ids; } function monok_sync_getPostType($puff) { // Check if puff has a type if (isset($puff->type)) { // Get available post types $available_post_types = get_post_types(array('public' => true), 'names'); // Convert the puff type to lowercase for case-insensitive comparison $puff_type = strtolower($puff->type); // Check if the puff type matches any available post type foreach ($available_post_types as $post_type) { if (strtolower($post_type) === $puff_type) { return $post_type; } } } // If no match is found, use the default post type $monok_settings_options = get_option('monok_settings_option_name'); $default_post_type = isset($monok_settings_options['default_post_type_0']) ? $monok_settings_options['default_post_type_0'] : 'post'; return $default_post_type; } function monok_sync_getCategories($puff){ $monok_settings_options = get_option( 'monok_settings_option_name' ); $default_category = isset($monok_settings_options['default_category_0']) ? $monok_settings_options['default_category_0'] : ''; $catArg = array("hide_empty" => 0); $siteCategories = get_categories($catArg); $post_categories = array(); //Match by section if(isset($puff->sections)){ foreach($puff->sections as $section) { foreach($siteCategories as $siteCategory) { $siteCategoryName = trim(html_entity_decode($siteCategory->name)); if (strcasecmp(trim($section), $siteCategoryName) === 0) { array_push($post_categories, $siteCategory->term_id); } } } } //otherwise by category list if(count($post_categories)===0){ foreach($puff->categories as $puffcategory) { if($puffcategory->weight > 1){ foreach($siteCategories as $siteCategory) { $siteCategoryName = html_entity_decode($siteCategory->name); if(preg_match("/{$siteCategoryName}/i", $puffcategory->name)){ array_push($post_categories, $siteCategory->term_id); } } } } } //otherwise by default category name if(count($post_categories)===0){ foreach($siteCategories as $siteCategory) { $siteCategoryName = $siteCategory->name; if(preg_match("/{$siteCategoryName}/i", $default_category)){ array_push($post_categories, $siteCategory->term_id); break; } } } return $post_categories; } function monok_sync_getMetaTags($puff, $onlyIfEmpty) { // Ensure is_plugin_active() is available if ( !function_exists('is_plugin_active') ) { require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); } // Get keywords: prefer specific keywords, fallback to category names $post_keywords = array(); if (isset($puff->keywords)) { $post_keywords = $puff->keywords; } else { foreach ($puff->categories as $category) { array_push($post_keywords, $category->name); } } // Use short title if available; fallback to full title $shortTitle = isset($puff->shortTitle) ? $puff->shortTitle : $puff->title; // Get the description; try explicit description, else use first sentence of text if (isset($puff->description)) { $description = $puff->description; } else { // Break on a period or newline $description = reset(preg_split("/[\.\n]/u", wp_strip_all_tags($puff->text))); } // Prepare meta values for both Yoast and Rank Math $metaTags = array( '_yoast_wpseo_title' => $shortTitle, '_yoast_wpseo_focuskw' => implode(' ', array_slice($post_keywords, 0, 3)), '_yoast_wpseo_metadesc' => $description, 'rank_math_title' => $shortTitle, 'rank_math_focus_keyword' => implode(' ', array_slice($post_keywords, 0, 3)), 'rank_math_description' => $description ); // If onlyIfEmpty is true and $puff has an ID, check for existing meta values if ($onlyIfEmpty && isset($puff->ID)) { foreach ($metaTags as $key => $value) { $existing = get_post_meta($puff->ID, $key, true); // Only update if the meta field does NOT exist, or is empty, or its trimmed length is less than 1 if (isset($existing) && strlen(trim($existing)) >= 1) { unset($metaTags[$key]); } } } // Now return only the meta tags for the active plugin if (function_exists('is_plugin_active') && is_plugin_active('wordpress-seo/wp-seo.php')) { // Yoast is active: use only Yoast keys return array_intersect_key($metaTags, array_flip(array('_yoast_wpseo_title', '_yoast_wpseo_focuskw', '_yoast_wpseo_metadesc'))); } elseif (function_exists('is_plugin_active') && is_plugin_active('seo-by-rank-math/rank-math.php')) { // Rank Math is active: use only Rank Math keys return array_intersect_key($metaTags, array_flip(array('rank_math_title', 'rank_math_focus_keyword', 'rank_math_description'))); } else { // Neither plugin is active, return both sets (fallback) return $metaTags; } } /** * Handles the GET request to filter posts. * * @param WP_REST_Request $request The REST request object. * @return WP_REST_Response JSON response with filtered posts. */ function monok_sync_custom_api_get_filtered_posts( $request ) { $auth_error = monok_validate_apikey( $request ); if ( $auth_error ) return $auth_error; // Retrieve and sanitize parameters. $params = $request->get_params(); $post_type = ! empty( $params['post_type'] ) ? sanitize_title( $params['post_type'] ) : 'post'; $section = ! empty( $params['section'] ) ? $params['section'] : ''; $tag = ! empty( $params['tag'] ) ? $params['tag'] : ''; $q = ! empty( $params['q'] ) ? sanitize_text_field( $params['q'] ) : ''; $amount = ! empty( $params['amount'] ) ? max( 1, min( 100, intval( $params['amount'] ) ) ) : 10; $page = ! empty( $params['page'] ) ? intval( $params['page'] ) : 1; // Validate post type exists. if ( ! post_type_exists( $post_type ) ) { return rest_ensure_response( array() ); } // Basic query arguments. $args = array( 'post_type' => $post_type, 'posts_per_page' => $amount, 'paged' => $page, 'post_status' => 'publish', ); // Apply search query if provided. if ( ! empty( $q ) ) { // Using the built-in 's' parameter for basic search. $args['s'] = $q; } // Apply category (section) filtering. if ( ! empty( $section ) ) { $section_slug = sanitize_title( $section ); $category = get_term_by( 'slug', $section_slug, 'category' ); if ( $category ) { $args['cat'] = $category->term_id; } else { return rest_ensure_response( array() ); } } // Apply tag filtering. if ( ! empty( $tag ) ) { $tag_slug = sanitize_title( $tag ); $tag_term = get_term_by( 'slug', $tag_slug, 'post_tag' ); if ( $tag_term ) { $args['tag'] = $tag_term->slug; } else { return rest_ensure_response( array() ); } } // Execute the query. $query = new WP_Query( $args ); $posts = array(); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $posts[] = array( 'canonical_url' => get_permalink(), 'post_id' => get_the_ID(), 'title' => get_the_title(), 'description' => get_the_excerpt(), ); } wp_reset_postdata(); } return rest_ensure_response( $posts ); } /** * Handles the update post request. * * @param WP_REST_Request $request The request object containing the post ID. * @return WP_Error|WP_REST_Response */ function monok_sync_update_post_by_id( $request ) { // Retrieve post ID from the request parameters. $post_id = (int) $request['p']; // return 1931; // Check if post ID is provided. if ( ! $post_id ) { return null; } // Try to get the post. $post = get_post( $post_id ); if ( ! $post ) { return null; } $puff = json_decode($request->get_body()); //Warning, wordpress/php merges body with url params (weird) $updated_content = monok_sync_getContent($puff, $post_id); // Prepare the post update arguments. $post_update = array( 'ID' => $post_id, 'post_content' => $updated_content, 'meta_input' => array_merge( array( 'monokId' => $puff->id ), monok_sync_getMetaTags($puff, true) ), ); // Update the post. $update_result = wp_update_post( $post_update, true ); // Check for errors during the update. if ( is_wp_error( $update_result ) ) { return null; }else{ monok_sync_linkback(get_post($post_id)); } // Return a successful response. return $post_id; } function monok_sync_on_rest_post_puff($request){ try { $host = 'https://app.monok.com'; $auth_error = monok_validate_apikey( $request ); if ( $auth_error ) return $auth_error; $apikey = get_option( 'monok_settings_option_name', array() )['api_keys_0']; $action = $request['action']; $postStatus = 'draft'; if(isset($request['publish']) || $action==='publish'){ $postStatus = 'publish'; }else if($action==='update'){ //Not a new article, update an existing $update_result = monok_sync_update_post_by_id($request); return $update_result; } $puff = json_decode($request->get_body()); // TODO: check that puff has everything we need // Check if this puff has already been pushed using monokid, save postid to the side $args = array( 'meta_key' => 'monokId', 'meta_value' => $puff->id, 'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit') ); $postID = null; $updating = false; $posts = get_posts($args); if(count($posts)>0){ $updating = true; $postID = $posts[0]->ID; } // remove after save changes // getPostObject will always return a draft $the_post = monok_sync_getPostObject($puff); if(!$postID){ // Filter #1 $the_post = apply_filters("monok_pre_insert", $the_post); // Insert the new draft post, return errors, and don't trigger hooks $initial_post = $the_post; $initial_post['post_content'] = ''; $postID = wp_insert_post($initial_post, true, false); } if (is_wp_error($postID)) { $response = new WP_REST_Response( $postID->get_error_message()); $response->set_status( 400 ); return $response; } $tags = monok_sync_getTags($puff); // Set the postID $the_post['ID'] = $postID; // Fix the content, and create a thumbnail $the_post['post_content'] = monok_sync_getContent($puff, $postID); // Set the post status $the_post['post_status'] = $postStatus; // Filter #2 $the_post = apply_filters("monok_pre_update", $the_post); // Update the post into the database wp_update_post( $the_post ); // If there are tags, assign them to the post if (!empty($tags)) { wp_set_post_terms($postID, $tags, 'post_tag'); } // Update language setting of post if PolyLang exists if (function_exists('pll_set_post_language')) { if(isset($puff->language)){ $langs = pll_the_languages(array('raw'=>1, 'hide_if_empty'=>0)); if (array_key_exists($puff->language, $langs)) { pll_set_post_language($postID, $puff->language); }else{ pll_set_post_language($postID, pll_default_language()); } }else{ pll_set_post_language($postID, pll_default_language()); } } // Action #1 do_action( "monok_post_update", $the_post ); // take back after save changes filters if($postStatus === 'publish' && $updating){ monok_sync_linkback(get_post($postID)); } $response = new WP_REST_Response( array( 'postId' => $postID, 'canonicalUrl' => get_permalink( $postID ), 'status' => $postStatus, 'service' => 'wordpress', 'thumbnail' => get_the_post_thumbnail_url( $postID, 'full' ) ?: null, 'monokId' => isset( $puff->id ) ? $puff->id : null, )); $response->set_status( 200 ); return $response; } catch (Exception $e) { $response = new WP_REST_Response( $e->getMessage() ); $response->set_status( 500 ); return $response; } } function monok_sync_on_rest_post_settings($request){ try { $host = 'https://app.monok.com'; $auth_error = monok_validate_apikey( $request ); if ( $auth_error ) return $auth_error; $apikey = get_option( 'monok_settings_option_name', array() )['api_keys_0']; $old_settings = get_option( 'monok_settings_option_name' ); $newSettings = json_decode($request->get_body()); $changed = false; if(isset($newSettings->key)){ if ( ! is_string( $newSettings->key ) || strlen( trim( $newSettings->key ) ) < 8 ) return new WP_REST_Response( 'Invalid API key', 400 ); $old_settings['api_keys_0'] = trim( $newSettings->key ); $changed = true; } if(isset($newSettings->js_scripts)){ $old_settings['js_scripts'] = $newSettings->js_scripts === 'Enabled' ? 'Enabled' : 'Disabled'; $changed = true; } if(isset($newSettings->photo_caption_visibility)){ $old_settings['photo_caption_visibility_1'] = $newSettings->photo_caption_visibility === 'Enabled' ? 'Enabled' : 'Disabled'; $changed = true; } if($changed == true){ update_option('monok_settings_option_name', $old_settings); } $response = new WP_REST_Response( "Settings changed" ); $response->set_status( 200 ); return $response; } catch (Exception $e) { $response = new WP_REST_Response( $e->getMessage() ); $response->set_status( 500 ); return $response; } } /** * Background: fetch article from Monok and call old post handler */ function monok_pull_and_post_article( $puff_id, $action, $apikey ) { $url = add_query_arg(array( 'puffId' => $puff_id, ), 'https://app.monok.com/api/v1/pull'); $res = wp_remote_get($url, array('timeout' => 15)); if (!is_wp_error($res) && wp_remote_retrieve_response_code($res) == 200) { $body = wp_remote_retrieve_body($res); if ($body && is_string($body)) { $req = new WP_REST_Request('POST', '/monok/v1/puff'); $req->set_param('apikey', $apikey); if (method_exists($req, 'set_body')) { $req->set_body($body); // raw JSON directly } $req->set_param('action', $action); monok_sync_on_rest_post_puff($req); } } } function monok_sync_on_rest_get_info($request){ // echo ""; try { $auth_error = monok_validate_apikey( $request ); if ( $auth_error ) return monok_no_cache_headers( $auth_error ); $apikey = get_option( 'monok_settings_option_name', array() )['api_keys_0']; //PASSED API CHECK //#################################################################################### //If this call is actually a ping to pull an article because post failed $puff_id = isset($request['puffId']) ? $request['puffId'] : null; if ($puff_id) { // queue work to run after WP finishes sending the REST response register_shutdown_function(function() use ($puff_id, $action, $apikey) { monok_pull_and_post_article($puff_id, $action, $apikey); }); // return a normal REST response (no ->send()) $response = new WP_REST_Response(['status' => 'accepted', 'puffId' => $puff_id], 202); return monok_no_cache_headers($response); } //#################################################################################### if( ! function_exists( 'get_plugin_data' ) ) { require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); } // Plugin Version $plugin_data = get_plugin_data( __FILE__ ); $plugin_version = $plugin_data['Version']; $old_settings['version'] = $plugin_version; // Site Name $site_name = get_bloginfo( 'name' ); $site_name = !is_string($site_name) || strlen($site_name) <1 ? get_bloginfo( 'name' ) : $site_name; $site_name = !is_string($site_name) || strlen($site_name) <1 ? bloginfo('name') : $site_name; $site_name = !is_string($site_name) || strlen($site_name) <1 ? wp_title() : $site_name; $site_name = !is_string($site_name) || strlen($site_name) <1 ? get_bloginfo( 'description' ) : $site_name; $old_settings['name'] = $site_name; // Logo url try { $old_settings['logo'] = wp_get_attachment_image_src(get_theme_mod( 'custom_logo' ), 'full' )[0]; } catch (Exception $e) { } // Site Categories $cat_filter = function($cat) { return html_entity_decode($cat->name); }; $catArg = array("hide_empty" => 0); $old_settings['categories'] = array_values( array_map($cat_filter, get_categories($catArg))); $post_types = get_post_types(array('public' => true), 'names'); $old_settings['post_types'] = array_values($post_types); // Site Tags $tag_filter = function($tag) { return $tag->name; }; $tags = get_terms(array( 'taxonomy' => 'post_tag', 'hide_empty' => false, )); $old_settings['tags'] = array_values(array_map($tag_filter, $tags)); // Get all languages (PolyLang) if(function_exists('pll_the_languages')){ $old_settings['languages'] = pll_the_languages(array('raw'=>1, 'hide_if_empty'=>0)); }else{ $old_settings['languages'] = array(); } // Get all Authors with detailed information $author_filter = function($author) { return array( 'name' => $author->display_name, 'profile' => get_user_meta($author->ID, 'description', true), 'id' => (string)$author->ID, 'avatar' => get_avatar_url($author->ID), 'roles' => $author->roles ); }; $authors = get_users(array( 'role__in' => array('Author', 'Administrator', 'Editor', 'Contributor'), // Fetch authors, administrators, and editors )); $old_settings['authors'] = array_values(array_map($author_filter, $authors)); // // Get all Pages // $args = array( // 'sort_order' => 'DESC', 'number' => 10 // ); // function pages_extractor($page){ // $page_arr = $page->to_array(); // unset($page_arr['post_content']); // return $page_arr; // // return array( // // 'title'=> $page=> // // ) // } // $all_pages = get_pages($args); // $all_pages = array_map('pages_extractor', $all_pages); // $old_settings['pages'] = $all_pages; $response = new WP_REST_Response($old_settings); $response->set_status( 200 ); return monok_no_cache_headers( $response ); } catch (Exception $e) { $response = new WP_REST_Response( $e->getMessage() ); $response->set_status( 500 ); return monok_no_cache_headers( $response ); } } function monok_sync_my_scripts() { $settings = get_option( 'monok_settings_option_name', array() ); if ( ! monok_service_enabled() || ( $settings['js_scripts'] ?? '' ) !== 'Enabled' ) return; wp_enqueue_script( 'monok-sync-social', plugins_url( 'social.js', __FILE__ ), array(), '3.9.2', true ); // Provider-managed scripts intentionally use their canonical URLs without a plugin version query. // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- X controls the script version. wp_enqueue_script( 'monok-sync-twitter', 'https://platform.twitter.com/widgets.js', array( 'monok-sync-social' ), null, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Instagram controls the script version. wp_enqueue_script( 'monok-sync-instagram', 'https://platform.instagram.com/en_US/embeds.js', array(), null, true ); } add_action( 'wp_head', 'monok_sync_my_scripts' ); add_action( 'transition_post_status', 'monok_sync_on_all_status_transitions', 10, 3); add_action( 'rest_api_init', function () { register_rest_route( 'monok/v1', '/puff', array( 'methods' => 'POST', 'callback' => 'monok_sync_on_rest_post_puff', 'permission_callback' => 'monok_rest_permission' ) ); register_rest_route( 'monok/v1', '/settings', array( 'methods' => 'POST', 'callback' => 'monok_sync_on_rest_post_settings', 'permission_callback' => 'monok_rest_permission' ) ); register_rest_route( 'monok/v1', '/info', array( 'methods' => 'GET', 'callback' => 'monok_sync_on_rest_get_info', 'permission_callback' => 'monok_rest_permission' ) ); register_rest_route( 'monok/v1', '/postfilter', array( 'methods' => 'GET', 'callback' => 'monok_sync_custom_api_get_filtered_posts', 'permission_callback' => 'monok_rest_permission', 'args' => array( 'apikey' => array( 'sanitize_callback' => 'sanitize_text_field', ), 'post_type' => array( 'sanitize_callback' => 'sanitize_text_field', ), 'section' => array( 'sanitize_callback' => 'sanitize_text_field', ), 'tag' => array( 'sanitize_callback' => 'sanitize_text_field', ), 'amount' => array( 'sanitize_callback' => 'absint', ), 'page' => array( 'sanitize_callback' => 'absint', ), ), ) ); } ); add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'monok_sync_nc_settings_link' ); function monok_sync_nc_settings_link( $links ) { // Build and escape the URL. $url = esc_url( add_query_arg( 'page', 'monok-settings', get_admin_url() . 'admin.php' ) ); // Create the link. $settings_link = "" . esc_html__( 'Settings', 'monok-sync' ) . ''; // Adds the link to the end of the array. array_push( $links, $settings_link ); return $links; }//end monok_sync_nc_settings_link() function monok_service_enabled() { $settings = get_option( 'monok_settings_option_name', array() ); return isset( $settings['api_keys_0'] ) && is_string( $settings['api_keys_0'] ) && strlen( trim( $settings['api_keys_0'] ) ) >= 8; } function monok_rest_permission( $request ) { $error = monok_validate_apikey( $request ); return $error ? new WP_Error( 'monok_unauthorized', 'Monok API key is invalid.', array( 'status' => 403 ) ) : true; }