function do_x_post_password_cb() { //snag from wp-login.php:386-393 require_once ABSPATH . 'wp-includes/class-phpass.php'; // By default, use the portable hash from phpass $wp_hasher = new PasswordHash(8, true); // 10 days setcookie('wp-postpass_' . COOKIEHASH, $wp_hasher->HashPassword(stripslashes($_POST['pass'])), time() + 864000, COOKIEPATH); //fake it so it's available in the loop below $_COOKIE['wp-postpass_' . COOKIEHASH] = $wp_hasher->HashPassword(stripslashes($_POST['pass'])); $q = new WP_Query("p={$_POST['pid']}"); if ($q->have_posts()) { while ($q->have_posts()) { $q->the_post(); // verifies password hash if (post_password_required()) { wp_send_json_error('Invalid password'); } // get post title ob_start(); the_title(sprintf('<a href="%s" rel="bookmark">', esc_url(get_permalink())), '</a>'); $title = ob_get_clean(); // get post content ob_start(); the_content(); $content = ob_get_clean(); } } wp_reset_postdata(); $return = array('title' => $title, 'content' => $content); wp_send_json_success($return); }
/** * Ajax handler for adding a term via Ajax. */ public static function wpml_save_term() { if (!wpml_is_action_authenticated('wpml_save_term')) { wp_send_json_error('Wrong Nonce'); } global $sitepress; $lang = filter_input(INPUT_POST, 'term_language_code', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $taxonomy = filter_input(INPUT_POST, 'taxonomy'); $slug = filter_input(INPUT_POST, 'slug'); $name = filter_input(INPUT_POST, 'name'); $trid = filter_input(INPUT_POST, 'trid', FILTER_SANITIZE_NUMBER_INT); $description = filter_input(INPUT_POST, 'description'); $new_term_object = false; if ($name !== "" && $taxonomy && $trid && $lang) { $args = array('taxonomy' => $taxonomy, 'lang_code' => $lang, 'term' => $name, 'trid' => $trid, 'overwrite' => true); if ($slug) { $args['slug'] = $slug; } if ($description) { $args['description'] = $description; } $res = WPML_Terms_Translations::create_new_term($args); if ($res && isset($res['term_taxonomy_id'])) { /* res holds the term taxonomy id, we return the whole term objects to the ajax call */ $new_term_object = get_term_by('term_taxonomy_id', (int) $res['term_taxonomy_id'], $taxonomy); $lang_details = $sitepress->get_element_language_details($new_term_object->term_taxonomy_id, 'tax_' . $new_term_object->taxonomy); $new_term_object->trid = $lang_details->trid; $new_term_object->language_code = $lang_details->language_code; WPML_Terms_Translations::icl_save_term_translation_action($taxonomy, $res); } } wp_send_json_success($new_term_object); }
function do_forgot_password_ajax() { if (isset($_POST['forgot_password_form_submitted']) && isset($_POST['forgot_password_form_nonce_field']) && wp_verify_nonce($_POST['forgot_password_form_nonce_field'], 'forgot_password_form_submitted')) { if (isset($_POST['username'])) { $username = sanitize_text_field($_REQUEST['username']); $user = get_user_by('login', $username); if (!$user) { $return = array('message' => "Sorry the username you provided is not registered"); wp_send_json_error($return); } else { // Send an email that the account has been created do_action('cloderia_user_reset_password', $username); $return = array('message' => "A new password has been sent to your email"); wp_send_json_success($return); } } else { $return = array('message' => "Please provide a valid username"); wp_send_json_error($return); } } else { $message = "Invalid form operation."; $return = array('message' => $message); wp_send_json_error($return); } }
public static function send_json_error($data, $send_non_200) { if ($send_non_200) { header('HTTP/1.0 400'); } wp_send_json_error($data); }
public function ajax_handler($data) { CS_Shortcode_Preserver::init(); if ($this->sandbox_the_content) { CS_Shortcode_Preserver::sandbox('cs_render_the_content'); } add_filter('cs_preserve_shortcodes_no_wrap', '__return_true'); $this->orchestrator = $this->plugin->component('Element_Orchestrator'); $this->orchestrator->load_elements(); $this->mk1 = new Cornerstone_Legacy_Renderer($this->plugin->component('Legacy_Elements')); global $post; if (!isset($data['post_id']) || !($post = get_post((int) $data['post_id']))) { wp_send_json_error(array('message' => 'post_id not set')); } setup_postdata($post); $this->enqueue_extractor = $this->plugin->loadComponent('Enqueue_Extractor'); $this->enqueue_extractor->start(); if (isset($data['raw_markup'])) { $this->raw_markup = (bool) $data['raw_markup']; } if (!isset($data['batch'])) { wp_send_json_error(array('message' => 'No element data recieved')); } $jobs = $this->batch($data['batch']); $scripts = $this->enqueue_extractor->get_scripts(); if (is_wp_error($jobs)) { wp_send_json_error(array('message' => $jobs->get_error_message())); } $result = array('jobs' => $jobs, 'scripts' => $scripts); //Suppress PHP error output unless debugging if (CS()->common()->isDebug()) { return wp_send_json_success($result); } return @wp_send_json_success($result); }
/** * Block direct cron execution as early as possible */ public function block_direct_cron() { if (false !== stripos($_SERVER['REQUEST_URI'], '/wp-cron.php') || false !== stripos($_SERVER['SCRIPT_NAME'], '/wp-cron.php')) { status_header(403); wp_send_json_error(new \WP_Error('forbidden', sprintf(__('Normal cron execution is blocked when the %s plugin is active.', 'automattic-cron-control'), 'Cron Control')), array('status' => 400)); } }
public function ajax_image_crop() { $res = false; if (!current_user_can('edit_posts') || empty($_REQUEST["nonce"]) || !wp_verify_nonce($_REQUEST["nonce"], 'pe_theme_image_crop')) { wp_send_json_error(); wp_die(0); } $id = $_REQUEST["id"]; $idx = $_REQUEST["idx"]; $size = $_REQUEST["size"]; list($w, $h) = explode("x", $size); $crop = $_REQUEST["crop"]; $orig = $_REQUEST["orig"]; $res = $this->master->image->crop($orig, $crop, $w, $h); if (!empty($res["cburl"])) { $res["idx"] = absint($idx); $meta = get_post_meta($id, PE_THEME_META, true); if (empty($meta)) { $meta = new StdClass(); $meta->thumbnails = new StdClass(); } $meta->thumbnails->thumbs[$size] = $crop; update_post_meta($id, PE_THEME_META, $this->update_attachment_metadata($meta, $id, null)); } wp_send_json_success($res); wp_die(0); }
/** * Parse the Cue shortcode for display within a TinyMCE view. * * @since 1.3.0 */ function cue_ajax_parse_shortcode() { global $wp_scripts; if (empty($_POST['shortcode'])) { wp_send_json_error(); } $shortcode = do_shortcode(wp_unslash($_POST['shortcode'])); if (empty($shortcode)) { wp_send_json_error(array('type' => 'no-items', 'message' => __('No items found.'))); } $head = ''; $styles = wpview_media_sandbox_styles(); foreach ($styles as $style) { $head .= '<link type="text/css" rel="stylesheet" href="' . $style . '">'; } $head .= '<link rel="stylesheet" href="' . CUE_URL . 'assets/css/cue.min.css' . '">'; $head .= '<style type="text/css">.cue-tracks { max-height: none;}</style>'; if (!empty($wp_scripts)) { $wp_scripts->done = array(); } ob_start(); echo $shortcode; wp_print_scripts('cue'); wp_send_json_success(array('head' => $head, 'body' => ob_get_clean())); }
/** * Saves star/unstar value for Flows on Recent Flows page * *@since 1.0.0 *@param Gets parameters form AJAX $_POST */ public function jo_save_flow_star() { global $wpdb; //get flow id $flow_id = (int) $_POST['flow_id']; //get if flow was starred and invert if (isset($_POST['is_starred'])) { //make sure value is 1 or null and invert value if ($_POST['is_starred'] == 1 || $_POST['is_starred'] == '1') { $is_starred = false; } elseif ($_POST['is_starred'] == null || $_POST['is_starred'] == false) { $is_starred = 1; } else { wp_send_json_error(array('jo_success' => false, 'message' => 'star value 1 or null')); } } else { $is_starred = false; } // Update the meta field in the database. $is_success = update_post_meta($flow_id, 'jumpoff_flow_flag', $is_starred); if ($is_success) { $message = 'UPDATED ' . $flow_id . ' jumpoff_flow_flag ' . $is_starred . ' | ' . $_POST['is_starred']; } else { $message = 'not updated ' . $flow_id . ' jumpoff_flow_flag ' . $is_starred . ' | ' . $_POST['is_starred']; } $starred = get_post_meta($flow_id, 'jumpoff_flow_flag', false); $starred = $starred[0]; wp_send_json_success(array('success' => $is_success, 'message' => $message, 'starred' => $starred, 'id' => $flow_id)); }
/** * List of simple error messages * * @param string $code * @return string json response with appropriate error code */ function apiErrors($code) { switch ($code) { case 'method': $data = array('messages' => 'GET is currently the only request method accepted, as of v1 of the API.', 'documentation' => '/api/v1/docs'); break; case 'resource': $data = array('messages' => 'The API requires a valid resource in order to return a response. Try looking for \'books\'', 'documentation' => '/api/v1/docs'); break; case 'version': $data = array('messages' => 'The version you\'re requesting is not supported. Current version of the API is v1', 'documentation' => '/api/v1/docs'); break; case 'format': $data = array('messages' => 'The format that is being requested is not supported. Try \'json\'', 'documentation' => '/api/v1/docs'); break; case 'empty': $data = array('messages' => 'There are no records that can be returned with the request that was made', 'documentation' => '/api/v1/docs'); break; case 'offset': $data = array('messages' => 'The offset is a larger value than the number of books available', 'documentation' => '/api/v1/docs'); break; default: $data = array('messages' => 'Something went wrong with your API request', 'documentation' => '/api/v1/docs'); } return wp_send_json_error($data); }
/** * Handles template redirect requests. Checks if endpoint is valid and if * user should be authenticated, routes request to proper handler function */ function api_endpoint_template_redirect() { global $wp_query; if (empty($wp_query->query_vars[static::$rewrite_endpoint])) { return; } //allows use of DOING_AJAX content just like admin-ajax requests define('DOING_AJAX', true); $api = explode('/', $wp_query->query_vars[static::$rewrite_endpoint]); $endpoint = array_shift($api); $admin = in_array($endpoint, static::$admin_endpoints); $is_function = function_exists($endpoint); $is_method = method_exists($this, $endpoint); if (!in_array($endpoint, static::$front_endpoints) && !$admin) { wp_send_json_error('Endpoint does not exist. Verify Endpoint exists. You may need to flush rewrites manually.'); } if (!$is_function && !$is_method) { wp_send_json_error('Endpoint function/method does not exist.'); } if ($admin && !$this->is_user_admin()) { wp_send_json_error('This is an Admin Endpoint. You must be logged in to access it.'); } if ($is_method) { call_user_func_array(array($this, $endpoint), $api); } if ($is_function) { call_user_func($endpoint, $api); } }
/** * Pass global $post object. * * @link https://github.com/iseulde/wp-front-end-editor/pull/228 */ function ajax_post() { require_once ABSPATH . '/wp-admin/includes/post.php'; if (!wp_verify_nonce($_POST['_wpnonce'], 'update-post_' . $_POST['post_ID'])) { wp_send_json_error(array('message' => __('You are not allowed to edit this item.'))); } $_POST['post_title'] = strip_tags($_POST['post_title']); $post_id = edit_post(); if (isset($_POST['save']) || isset($_POST['publish'])) { $status = get_post_status($post_id); if (isset($_POST['publish'])) { switch ($status) { case 'pending': $message = 8; break; case 'future': $message = 9; break; default: $message = 6; } } else { $message = 'draft' == $status ? 10 : 1; } } else { $message = 4; } // MOD by CAC global $post; // end MOD $post = get_post($post_id); wp_send_json_success(array('message' => $this->get_message($post, $message), 'post' => $post, 'processedPostContent' => apply_filters('the_content', $post->post_content))); }
/** * Ajax callback to get data for overview widget */ public function ajax_get_data() { if (!check_ajax_referer('get-data', false, false)) { wp_send_json_error(); } wp_send_json_success($this->get_data(intval($_GET['user']), strip_tags($_GET['from']), strip_tags($_GET['to']))); }
/** * Tries to install the plugin * * @access public */ public function install() { $this->check_capabilities(); $download = $_POST['download']; $license = $_POST['license']; $message = __('An Error Occured', 'maera'); $download_type = $this->_check_download($download); /** * Throw error of the product is not free and license it empty */ if (empty($download) || empty($license) && 'free' !== $download_type) { wp_send_json_error($message); } /** * Install the plugin if it's free */ if ('free' === $download_type) { $installed = $this->_install_plugin($download, ""); wp_send_json_success($installed); } /** * Check for license and then install if it's a valid licens */ if ($this->_check_license($license, $download)) { $installed = $this->_install_plugin($download, $license); wp_send_json_success($installed); } else { wp_send_json_error(__('Invalid License', 'maera')); } }
static function ajax_save() { if (!isset($_POST[Kanban_Utils::get_nonce()]) || !wp_verify_nonce($_POST[Kanban_Utils::get_nonce()], sprintf('%s-save', Kanban::get_instance()->settings->basename)) || !is_user_logged_in()) { wp_send_json_error(); } do_action(sprintf('%s_before_%s_ajax_save', Kanban::get_instance()->settings->basename, self::$slug)); $user_id_author = isset($_POST['user_id_author']) ? $_POST['user_id_author'] : get_current_user_id(); if (empty($_POST['user_id_worked'])) { $_POST['user_id_worked'] = $user_id_author; } try { $operator = substr($_POST['operator'], 0, 1) == '-' ? '-' : '+'; $val = sprintf('%s%s', $operator, abs(floatval($_POST['operator']))); } catch (Exception $e) { wp_send_json_error(array('message' => sprintf('Error saving %s', str_replace('_', ' ', self::$slug)))); } eval(sprintf('$hours = 0%s;', $val)); $data = array('task_id' => $_POST['task']['id'], 'worked_dt_gmt' => Kanban_Utils::mysql_now_gmt(), 'hours' => $hours, 'status_is' => $_POST['task']['status_id'], 'user_id_author' => $user_id_author, 'user_id_worked' => $_POST['user_id_worked']); $is_successful = self::_insert($data); do_action(sprintf('%s_after_%s_ajax_save', Kanban::get_instance()->settings->basename, self::$slug)); if (!empty($_POST['comment'])) { do_action(sprintf('%s_before_%s_ajax_comment_save', Kanban::get_instance()->settings->basename, self::$slug)); Kanban_Comment::add($_POST['comment'], 'system', $_POST['task']['id']); do_action(sprintf('%s_after_%s_ajax_comment_save', Kanban::get_instance()->settings->basename, self::$slug)); } if ($is_successful) { wp_send_json_success(array('message' => sprintf('%s saved', str_replace('_', ' ', self::$slug)))); } else { wp_send_json_error(array('message' => sprintf('Error saving %s', str_replace('_', ' ', self::$slug)))); } }
function create_duplicate($project_id) { //Get all data post type project, message, task_list, milestone $prev_pro_data = $this->fatch_projcet_data($project_id); $new_pro_arg = $this->fill_array($prev_pro_data[$project_id]); //create duplicate new project $new_pro_id = $this->insert_duplicate($new_pro_arg, $project_id); if (!$new_pro_id) { wp_send_json_error('Unknown Error', 'cpm'); } //remove project post type from data array unset($prev_pro_data[$project_id]); foreach ($prev_pro_data as $prev_post_id => $post_obj) { if ($post_obj->post_type == 'milestone') { $args = $this->fill_array($post_obj, $new_pro_id); //Insert message, task list and milestone $new_milestone_id[$post_obj->ID] = $this->insert_duplicate($args, $post_obj->ID); unset($prev_pro_data[$prev_post_id]); } } foreach ($prev_pro_data as $prev_post_id => $post_obj) { $args = $this->fill_array($post_obj, $new_pro_id); $new_milestone_id = isset($new_milestone_id) ? $new_milestone_id : array(); //Insert message, task list and milestone $id = $this->insert_duplicate($args, $post_obj->ID, $new_milestone_id); //If post type task list then fatch task and insert duplicate if ($post_obj->post_type == 'task_list') { $task = array('post_parent' => $post_obj->ID, 'post_type' => 'task', 'post_status' => 'publish', 'order' => 'ASC', 'orderby' => 'ID'); $task_data = get_children($task); $this->insert_duplicate_task($task_data, $id); } } return $new_pro_id; }
function get_posts_by_letter_rendered($first_letter = NULL, $limit = NULL) { global $wp_query; /** Validating parameters **/ $first_letter = (!$first_letter and isset($_POST['letter'])) ? $_POST['letter'] : $first_letter; $first_letter = (!$first_letter and !isset($_POST['letter'])) ? 'A' : $first_letter; $limit = ($limit === NULL and isset($_POST['limit'])) ? $_POST['limit'] : $limit; $limit = ($limit === NULL and !isset($_POST['limit'])) ? -1 : $limit; // $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $paged = detect_page_from_url(); $args = array('post_type' => 'realizadores', 'post_status' => 'publish', 'posts_per_page' => $limit, 'paged' => $paged, 'tax_query' => array(array('taxonomy' => 'letters', 'field' => 'name', 'terms' => $first_letter))); $query_to_render = new WP_Query($args); //Start recording echoed values $echoed = ''; ob_start(); global $post; ob_start(); echo "<h2>{$first_letter}</h2>"; if ($query_to_render->have_posts()) { while ($query_to_render->have_posts()) { $query_to_render->the_post(); setup_postdata($post); get_template_part('templates/feed', 'small-item'); } } wp_reset_postdata(); echo "<div class='end_of_letter' data-letter='{$first_letter}'></div>"; $echoed = ob_get_contents(); ob_end_clean(); if ($echoed !== '') { wp_send_json_success(json_encode($echoed)); } wp_send_json_error(); }
function x_demo_content_setup_ajax_callback() { // Uncomment to simulate a timeout // header("HTTP/1.0 408 Request Timeout"); die(); // // Get API data. // $errorMessage = __('We're sorry, the demo failed to finish importing.', '__x__'); if (!isset($_POST['demo'])) { wp_send_json_error(array('message' => $errorMessage, 'debug_message' => 'POST data missing demo.')); } $request = wp_remote_get($_POST['demo']); if (is_wp_error($request)) { wp_send_json_error(array('message' => $errorMessage, 'debug_message' => $request->get_error_message())); } // // API data. // $data = json_decode($request['body'], true); if (!is_array($data)) { wp_send_json_error(array('message' => $errorMessage, 'debug_message' => 'Requested demo is improperly formatted.')); } // // Run demo setup. // $error = false; ob_start(); include_once 'setup.php'; if ($error !== false) { wp_send_json_error(array('message' => $errorMessage, 'debug_message' => $error, 'buffer' => ob_get_clean())); } ob_clean(); wp_send_json_success(); }
public function ajax() { $apiArgs = isset($_GET["apiArgs"]) ? $_GET["apiArgs"] : array(); if (!$apiArgs) { wp_send_json_error(array("error" => "MISSING_APIARGS")); exit; } if (empty($apiArgs["since_id"]) || !is_numeric($apiArgs["since_id"])) { wp_send_json_error(array("error" => "MISSING_SINCE_ID")); exit; } // $since_id = isset( $_GET["since_id"] ) ? absint($_GET["since_id"]) : null; $logQueryArgs = $apiArgs; $logQuery = new SimpleHistoryLogQuery(); $answer = $logQuery->query($logQueryArgs); // Use our own repsonse array instead of $answer to keep size down $json_data = array(); $numNewRows = isset($answer["total_row_count"]) ? $answer["total_row_count"] : 0; $json_data["num_new_rows"] = $numNewRows; $json_data["num_mysql_queries"] = get_num_queries(); if ($numNewRows) { // We have new rows // Append strings $textRowsFound = sprintf(_n('1 new event', '%d new events', $numNewRows, 'simple-history'), $numNewRows); $json_data["strings"] = array("newRowsFound" => $textRowsFound); } wp_send_json_success($json_data); }
function icl_get_job_original_field_content() { global $iclTranslationManagement; if (!wpml_is_action_authenticated('icl_get_job_original_field_content')) { die('Wrong Nonce'); } $job_id = filter_input(INPUT_POST, 'tm_editor_job_id', FILTER_SANITIZE_NUMBER_INT); $field = filter_input(INPUT_POST, 'tm_editor_job_field'); $data = array(); $job = $job_id !== null && $field !== null ? $job = $iclTranslationManagement->get_translation_job($job_id) : null; $elements = $job && isset($job->elements) ? $job->elements : array(); foreach ($elements as $element) { $sanitized_type = sanitize_title($element->field_type); if ($field === 'icl_all_fields' || $sanitized_type === $field) { // if we find a field by that name we need to decode its contents according to its format $field_contents = TranslationManagement::decode_field_data($element->field_data, $element->field_format); if (is_scalar($field_contents)) { $field_contents = strpos($field_contents, "\n") !== false ? wpautop($field_contents) : $field_contents; $data[] = array('field_type' => $sanitized_type, 'field_data' => $field_contents); } } } if ((bool) $data !== false) { wp_send_json_success($data); } else { wp_send_json_error(0); } }
/** * Upload an image via plupload. * * @return */ function charitable_plupload_image_upload() { $post_id = (int) filter_input(INPUT_POST, 'post_id', FILTER_SANITIZE_NUMBER_INT); $field_id = (string) filter_input(INPUT_POST, 'field_id'); check_ajax_referer('charitable-upload-images-' . $field_id); $file = $_FILES['async-upload']; $file_attr = wp_handle_upload($file, array('test_form' => false)); if (isset($file_attr['error'])) { wp_send_json_error($file_attr); } $attachment = array('guid' => $file_attr['url'], 'post_mime_type' => $file_attr['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file['name'])), 'post_content' => '', 'post_status' => 'inherit'); /** * Insert the file as an attachment. */ $attachment_id = wp_insert_attachment($attachment, $file_attr['file'], $post_id); if (is_wp_error($attachment_id)) { wp_send_json_error(); } wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $file_attr['file'])); $size = (string) filter_input(INPUT_POST, 'size'); $max_uploads = (int) filter_input(INPUT_POST, 'max_uploads', FILTER_SANITIZE_NUMBER_INT); if (!$size) { $size = 'thumbnail'; } ob_start(); charitable_template('form-fields/picture-preview.php', array('image' => $attachment_id, 'field' => array('key' => $field_id, 'size' => $size, 'max_uploads' => $max_uploads))); wp_send_json_success(ob_get_clean()); }
public function hoo_api() { global $post; // /if the page contains the hoo-api shortcode send json and exit :} if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'hoo-api')) { $locations_repo = $this->entity_manager->getRepository('Hoo\\Model\\Location'); $json_response = array(); $date = isset($_GET['date']) ? new \DateTime($_GET['date']) : new \DateTime(date('Y-m-d')); if (isset($_GET['location_id'])) { $location = Location::get_location_by_id_or_shortname($_GET['location_id'], $this->entity_manager); if (!$location) { return wp_send_json_error('Not Found'); } $hours = $location->get_hours_for_date($date); $json_response['location'] = $location->to_api_response(); $json_response['location']['address'] = $location->address->to_api_response(); $json_response['hours'] = $hours ? $hours->to_api_response() : null; $json_response['weekly'] = $location->get_weekly_hours(); } else { $locations_repo = $this->entity_manager->getRepository('Hoo\\Model\\Location'); foreach ($locations_repo->findBy(array('is_visible' => true)) as $location) { $hours = $location->get_hours_for_date($date); $json_response[]['location'] = $location->to_api_response(); $json_response[]['location']['address'] = $location->address->to_api_response(); $json_response[]['hours'] = $hours ? $hours->to_api_response() : null; $json_response[]['weekly'] = $location->get_weekly_hours(); } } wp_send_json($json_response); exit; } }
function ajax_error($message = null, $data = array()) { if (!is_null($message)) { $data['message'] = $message; } wp_send_json_error($data); }
/** * Checks whether the given nonce is valid. If it isn't it sends a json error. */ public static function check_nonce($nonce, $nonce_title) { if (!wp_verify_nonce(htmlentities($nonce), $nonce_title)) { wp_send_json_error('Invalid nonce.'); } return true; }
/** * Save an image */ public function save_image() { check_ajax_referer(self::NONCE_SAVE_IMAGE, 'nonce'); $attachment_id = isset($_POST['attachment_id']) ? absint($_POST['attachment_id']) : false; if ($this->is_attachment($attachment_id)) { // faces if (isset($_POST['faces'])) { if ($_POST['faces']) { update_post_meta($attachment_id, 'faces', $_POST['faces']); } else { delete_post_meta($attachment_id, 'faces'); } } // hotspots if (isset($_POST['hotspots'])) { if ($_POST['hotspots']) { update_post_meta($attachment_id, 'hotspots', $_POST['hotspots']); } else { delete_post_meta($attachment_id, 'hotspots'); } } // regenerate thumbs $resized = MEAUH_Attachment::regenerate($attachment_id); if ($resized) { wp_send_json_success(array('resized' => $resized)); } } else { wp_send_json_error(); } }
function ajax_upgrade() { // options $options = acf_parse_args($_POST, array('version' => '', 'nonce' => '')); // validate if (!wp_verify_nonce($options['nonce'], 'acf_nonce')) { wp_send_json_error(); } // vars $path = acf_get_path("admin/updates/{$options['version']}.php"); // load version if (!file_exists($path)) { wp_send_json_error(); } // load any errors / feedback from update ob_start(); // include include $path; // get feedback $feedback = ob_get_clean(); // update successful update_option('acf_version', $options['version']); // check for relevant updates. If none are found, update this to the plugin version $updates = acf_get_updates(); if (empty($updates)) { update_option('acf_version', acf_get_setting('version')); } // return wp_send_json_success(array('feedback' => $feedback)); }
/** * * Process the infoz * @since 1.0 */ function user_info() { if (isset($_POST['action'])) { // bail out if this user isnt logged in if (!is_user_logged_in()) { return; } if (!wp_verify_nonce($_POST['nonce'], 'process-user-info')) { return; } $user_id = get_current_user_id(); if ($_POST['action'] == 'process_user_info') { $gender = isset($_POST['gender']) ? sanitize_text_field($_POST['gender']) : false; $age = isset($_POST['age']) ? sanitize_text_field($_POST['age']) : false; $education = isset($_POST['education']) ? sanitize_text_field($_POST['education']) : false; $employment = isset($_POST['employment']) ? sanitize_text_field($_POST['employment']) : false; $data = array('gender' => $gender, 'age' => $age, 'education' => $education, 'employment' => $employment); update_user_meta($user_id, 'user_info', $data); update_user_meta($user_id, 'user_info_completed', 1); do_action('user_info_updated', $user_id, $data); wp_send_json_success(); } else { wp_send_json_error(); } } else { wp_send_json_error(); } }
/** * Ajax handler to retrieve content from Resource space and add as attachment. */ function ajax_get_image() { $resource_id = intval($_POST['resource_id']); $parent_post_id = isset($_POST['post']) ? intval($_POST['post']) : 0; if (empty($resource_id)) { wp_send_json_error(esc_html__('Empty resource id', 'resourcespace')); } $url = PJ_RESOURCE_SPACE_DOMAIN . '/plugins/api_search/'; $key = PJ_RESOURCE_SPACE_KEY; $url = add_query_arg(array('key' => $key, 'search' => $resource_id, 'prettyfieldnames' => 1, 'previewsize' => 'pre', 'original' => true), $url); $request_args = array('headers' => array()); // Pass basic auth header if available. if (defined('PJ_RESOURCE_SPACE_AUTHL') && defined('PJ_RESOURCE_SPACE_AUTHP')) { $request_args['headers']['Authorization'] = 'Basic ' . base64_encode(PJ_RESOURCE_SPACE_AUTHL . ':' . PJ_RESOURCE_SPACE_AUTHP); } $response = wp_remote_get($url, $request_args); if (200 == wp_remote_retrieve_response_code($response)) { $data = json_decode(wp_remote_retrieve_body($response)); } else { wp_send_json_error(esc_html__('Unable to query API', 'resourcespace')); } if (count($data) < 1) { wp_send_json_error(esc_html__('Resource not found', 'resourcespace')); } // Request original URL. // $attachment_id = $this->sideload_image( $data[0]->original ); // Request preview size. $attachment_id = $this->sideload_image($data[0]->preview); if (is_wp_error($attachment_id)) { wp_send_json_error($attachment_id->get_error_message()); } else { wp_send_json_success(wp_prepare_attachment_for_js($attachment_id)); } exit; }
/** * Ajax callback function to search users that is used on exclude setting page * * @uses WP_User_Query WordPress User Query class. * @return void */ public static function get_users() { if (!defined('DOING_AJAX') || !current_user_can(WP_Stream_Admin::SETTINGS_CAP)) { return; } check_ajax_referer('stream_get_users', 'nonce'); $response = (object) array('status' => false, 'message' => esc_html__('There was an error in the request', 'stream')); $search = isset($_POST['find']) ? wp_unslash(trim($_POST['find'])) : ''; $request = (object) array('find' => $search); add_filter('user_search_columns', array(__CLASS__, 'add_display_name_search_columns'), 10, 3); $users = new WP_User_Query(array('search' => "*{$request->find}*", 'search_columns' => array('user_login', 'user_nicename', 'user_email', 'user_url'), 'orderby' => 'display_name', 'number' => WP_Stream_Admin::PRELOAD_AUTHORS_MAX)); remove_filter('user_search_columns', array(__CLASS__, 'add_display_name_search_columns'), 10); if (0 === $users->get_total()) { wp_send_json_error($response); } $response->status = true; $response->message = ''; $response->users = array(); require_once WP_STREAM_INC_DIR . 'class-wp-stream-author.php'; foreach ($users->results as $key => $user) { $author = new WP_Stream_Author($user->ID); $args = array('id' => $author->ID, 'text' => $author->display_name); $args['tooltip'] = esc_attr(sprintf(__("ID: %d\nUser: %s\nEmail: %s\nRole: %s", 'stream'), $author->id, $author->user_login, $author->user_email, ucwords($author->get_role()))); $args['icon'] = $author->get_avatar_src(32); $response->users[] = $args; } if (empty($search) || preg_match('/wp|cli|system|unknown/i', $search)) { $author = new WP_Stream_Author(0); $response->users[] = array('id' => $author->id, 'text' => $author->get_display_name(), 'icon' => $author->get_avatar_src(32), 'tooltip' => esc_html__('Actions performed by the system when a user is not logged in (e.g. auto site upgrader, or invoking WP-CLI without --user)', 'stream')); } wp_send_json_success($response); }
public function action($controller, $action = '', $id = '') { if (empty($controller)) { wp_send_json_error("Controller is not set"); } if (empty($action)) { $action = $this->http->method() == 'POST' ? 'save' : 'get'; } $singleController = inflector()->camelize(inflector()->singularize($controller) . '_controller'); $pluralController = inflector()->camelize(inflector()->pluralize($controller) . '_controller'); if (!class_exists($class = $this->app->getControllerName($singleController))) { if (!class_exists($class = $this->app->getControllerName($pluralController))) { wp_send_json_error("Controllers {$singleController} and {$pluralController} do not exist"); } else { $controller = $pluralController; } } else { $controller = $singleController; } if (!method_exists($class, $action)) { wp_send_json_error("Controller {$controller} does not have method {$action}", 400); } $this->app->call(array($this->app->make($class), 'beforeFilter')); $this->app->call(array($this->app->make($class), $action), compact('id')); }