/**
  * Updates Metadata to the Brightcove API
  *
  * @param array $sanitized_post_data This should be sanitized POST data.
  *
  * @return bool|WP_Error
  */
 public function update_bc_playlist($sanitized_post_data)
 {
     global $bc_accounts;
     if (!wp_verify_nonce($_POST['nonce'], '_bc_ajax_search_nonce')) {
         return false;
     }
     $playlist_id = BC_Utility::sanitize_id($sanitized_post_data['playlist_id']);
     $update_data = array('type' => 'EXPLICIT');
     if (array_key_exists('name', $sanitized_post_data) && '' !== $sanitized_post_data['name']) {
         $update_data['name'] = utf8_uri_encode(sanitize_text_field($sanitized_post_data['name']));
     }
     if (array_key_exists('playlist_videos', $sanitized_post_data) && !empty($sanitized_post_data['playlist_videos'])) {
         $update_data['video_ids'] = BC_Utility::sanitize_payload_item($sanitized_post_data['playlist_videos']);
     }
     $bc_accounts->set_current_account($sanitized_post_data['account']);
     $request = $this->cms_api->playlist_update($playlist_id, $update_data);
     $bc_accounts->restore_default_account();
     if (is_wp_error($request) || false === $request) {
         return false;
     }
     if (is_array($request) && isset($request['id'])) {
         return true;
     }
     return true;
 }
 public function subscribe_if_not_subscribed()
 {
     global $bc_accounts;
     $accounts = $bc_accounts->get_sanitized_all_accounts();
     $completed_accounts = array();
     foreach ($accounts as $account => $account_data) {
         // We may have multiple accounts for an account_id, prevent syncing that account more than once.
         if (!in_array($account_data['account_id'], $completed_accounts)) {
             $completed_accounts[] = $account_data['account_id'];
             $bc_accounts->set_current_account($account);
             $subscriptions = $this->cms_api->get_subscriptions();
             if (is_array($subscriptions)) {
                 foreach ($subscriptions as $subscription) {
                     if ($bc_accounts->get_account_id() === $subscription['service_account'] && isset($subscription['id']) && false !== strpos($subscription['endpoint'], get_admin_url())) {
                         $this->cms_api->remove_subscription($subscription['id']);
                     }
                 }
             }
             $subscription_status = $this->cms_api->add_subscription();
             if (is_wp_error($subscription_status)) {
                 $bc_accounts->restore_default_account();
                 return false;
             }
             if (isset($subscription_status['id']) && $subscription_status['service_account'] === $bc_accounts->get_account_id()) {
                 $subscription_id = BC_Utility::sanitize_subscription_id($subscription_status['id']);
                 update_option($this->get_option_key_for($bc_accounts->get_account_id()), $subscription_id);
             }
             $bc_accounts->restore_default_account();
         }
     }
 }
    /**
     * Renders the iFrame player from Brightcove based on passed parameters
     *
     * @param     $video_id
     * @param     $account_id
     * @param     $player_id
     * @param int $width
     * @param int $height
     *
     * @return string
     */
    public static function player($video_id, $account_id, $player_id, $width = 500, $height = 250)
    {
        // Sanitize and Verify
        $account_id = BC_Utility::sanitize_id($account_id);
        $player_id = 'default' == $player_id ? 'default' : BC_Utility::sanitize_id($player_id);
        $video_id = BC_Utility::sanitize_id($video_id);
        $height = (int) $height;
        $width = (int) $width;
        $html = '<div style="width: ' . $width . 'px; height: ' . $height . 'px">';
        $html .= '<style>
			.video-js {
			    height: 100%;
			    width: 100%;
			}
			.vjs-big-play-button {
				display: none;
			}
			</style>';
        $html .= '<!-- Start of Brightcove Player -->';
        $html .= sprintf('<video data-account="%s" data-player="%s" data-embed="default" data-video-id="%s" class="video-js" controls></video>', $account_id, $player_id, $video_id);
        $html .= sprintf('<script src="//players.brightcove.net/%s/%s_default/index.min.js"></script>', $account_id, $player_id);
        $html .= '<!-- End of Brightcove Player -->';
        $html .= '</div>';
        return $html;
    }
 /**
  * Uses the Brightcove oAuth API to retrieve and store an access key for use with requests. The token is stored as a transient
  * with an expiration time matching that which is returned from Brightcove. The call to the API is only performed if that transient
  * is invalid or expired. Return a WP_Error object for use in WordPress in the case of failure.
  *
  * @since  1.0.0
  *
  * @see    BC_Utility::get_cache_item()
  * @see    set_transient()
  * @see    BC_Utility::delete_cache_item()
  * @see    wp_remote_post()
  *
  * @param bool $force_new_token whether or not to obtain a new OAuth token
  * @param bool $retry           true to retry on failure or false
  *
  * @return string|WP_Error
  */
 public function _request_access_token($force_new_token = false, $retry = true)
 {
     $transient_name = $this->transient_name;
     $token = $force_new_token ? false : BC_Utility::get_cache_item($transient_name);
     if (!$token) {
         $endpoint = esc_url_raw(self::ENDPOINT_BASE . '/access_token?grant_type=client_credentials');
         $request = wp_remote_post($endpoint, $this->_http_headers);
         if ('400' == wp_remote_retrieve_response_code($request)) {
             // Just in case
             BC_Utility::delete_cache_item($transient_name);
             $oauth_error = new WP_Error('oauth_access_token_failure', sprintf(__('There is a problem with your Brightcove %1$s or %2$s', 'brightcove'), '<code>client_id</code>', '<code>client_secret</code>'));
             BC_Logging::log(sprintf('BC OAUTH ERROR: %s', $oauth_error->get_error_message()));
             return $oauth_error;
         }
         $body = wp_remote_retrieve_body($request);
         $data = json_decode($body);
         if (isset($data->access_token)) {
             $token = $data->access_token;
             BC_Utility::set_cache_item($transient_name, 'oauth', $token, $data->expires_in);
         } else {
             if (!$retry) {
                 return new WP_Error('oauth_access_token_response_failure', sprintf(esc_html__('oAuth API did not return us an access token', 'brightcove')));
             }
             return $this->_request_access_token($force_new_token, false);
         }
     }
     return $token;
 }
 /**
  * Ensure there is a playlist capable player available
  */
 public function validate_players()
 {
     global $pagenow, $plugin_page;
     // only on admin.php?page=page-brightcove-playlists
     if ($pagenow != 'admin.php' || $plugin_page != 'page-brightcove-playlists') {
         return;
     }
     $player_api = new BC_Player_Management_API();
     $players = $player_api->player_list_playlist_enabled();
     if (is_wp_error($players) || !is_array($players) || $players['item_count'] < 1) {
         BC_Utility::admin_notice_messages(array(array('message' => __('A specified Source does not have a playlist capable player <a href="https://studio.brightcove.com/products/videocloud/players/">configured</a>. Make sure there is at least one player with "Display Playlist" enabled.', 'brightcove'), 'type' => 'error')));
     }
 }
 /**
  * Generates the Brightcove Menus and non-menu admin pages
  */
 public function register_admin_menu()
 {
     global $submenu;
     if (BC_Utility::current_user_can_brightcove()) {
         add_menu_page(esc_html__('Brightcove', 'brightcove'), esc_html__('Brightcove', 'brightcove'), 'edit_posts', 'brightcove', array($this, 'render_settings_page'), plugins_url('images/menu-icon.svg', dirname(__DIR__)), 50);
         add_submenu_page('brightcove', esc_html__('Brightcove Videos', 'brightcove'), esc_html__('Videos', 'brightcove'), 'edit_posts', BC_Admin_Menu::get_videos_page_uri_component(), array($this, 'render_videos_page'));
         add_submenu_page('brightcove', esc_html__('Brightcove Playlists', 'brightcove'), esc_html__('Playlists', 'brightcove'), 'edit_posts', BC_Admin_Menu::get_playlists_page_uri_component(), array($this, 'render_playlists_page'));
         add_submenu_page('brightcove', esc_html__('Brightcove Settings', 'brightcove'), esc_html__('Settings', 'brightcove'), 'manage_options', 'brightcove-sources', array($this, 'render_settings_page'));
         // These have no parent menu slug so they don't appear in the menu
         add_submenu_page(null, esc_html__('Add Source', 'brightcove'), esc_html__('Add Source', 'brightcove'), 'manage_options', 'page-brightcove-edit-source', array($this, 'render_edit_source_page'));
         // Removes the Brightcove Submenu from the menu that WP automatically provides when registering a top level page
         array_shift($submenu['brightcove']);
     }
 }
 public function delete_source()
 {
     global $bc_accounts;
     if (!isset($_GET['_wpnonce'])) {
         return false;
     }
     if (!wp_verify_nonce($_GET['_wpnonce'], 'bc_delete_source_id_' . $_GET['account'])) {
         return false;
     }
     $delete_account = $bc_accounts->delete_account(sanitize_text_field($_GET['account']));
     if (is_wp_error($delete_account)) {
         BC_Utility::admin_notice_messages(array(array('message' => $delete_account->get_error_message(), 'type' => 'error')));
     }
     BC_Utility::admin_notice_messages(array(array('message' => esc_html__('Source Deleted', 'brightcove'), 'type' => 'updated')));
 }
 public static function bc_playlist($atts)
 {
     global $allowedtags, $bc_accounts;
     $defaults = array('playlist_id' => '', 'account_id' => '', 'height' => 250, 'width' => 500);
     $atts = shortcode_atts($defaults, $atts, 'bc_playlist');
     if (false === $atts['playlist_id']) {
         return false;
     }
     $players = get_option('_bc_player_playlist_ids_' . $atts['account_id']);
     if (!$players || !is_array($players)) {
         return '';
     }
     $player_key = apply_filters('brightcove_player_key', array_shift($players));
     $html = sprintf('<iframe style="width: ' . intval($atts['width']) . 'px; height: ' . intval($atts['height']) . 'px;" src="//players.brightcove.net/%1$s/%2$s_default/index.html?playlistId=%3$s" height="%4$s" width="%5$s" allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>', BC_Utility::sanitize_id($atts['account_id']), esc_attr($player_key), BC_Utility::sanitize_id($atts['playlist_id']), esc_attr($atts['height']), esc_attr($atts['width']));
     return $html;
 }
 public function update_profile()
 {
     global $bc_accounts;
     if (!isset($_POST['_bc_profile_nonce'])) {
         return false;
     }
     if (!wp_verify_nonce($_POST['_bc_profile_nonce'], 'bc_profile_nonce')) {
         return false;
     }
     $hash = BC_Utility::sanitize_payload_item($_POST['bc-user-default-source']);
     $user_id = BC_Utility::sanitize_id($_POST['user_id']);
     $accounts = $bc_accounts->get_sanitized_all_accounts();
     if (!isset($accounts[$hash])) {
         BC_Utility::admin_notice_messages(array(array('message' => esc_html__('The specified Source does not exist.', 'brightcove'), 'type' => 'error')));
         return false;
     }
     BC_Utility::update_user_meta($user_id, '_brightcove_default_account_' . get_current_blog_id(), $hash);
     return true;
 }
 /**
  * Updates Metadata to the Brightcove API
  *
  * @param array $sanitized_post_data This should be sanitized POST data.
  *
  * @return bool|WP_Error
  */
 public function update_bc_video($sanitized_post_data)
 {
     global $bc_accounts;
     $video_id = BC_Utility::sanitize_id($sanitized_post_data['video_id']);
     $update_data = array();
     if (array_key_exists('name', $sanitized_post_data) && '' !== $sanitized_post_data['name']) {
         $update_data['name'] = utf8_uri_encode(sanitize_text_field($sanitized_post_data['name']));
     }
     if (array_key_exists('description', $sanitized_post_data) && !empty($sanitized_post_data['description'])) {
         $update_data['description'] = BC_Utility::sanitize_payload_item($sanitized_post_data['description']);
     }
     if (array_key_exists('long_description', $sanitized_post_data) && !empty($sanitized_post_data['long_description'])) {
         $update_data['long_description'] = BC_Utility::sanitize_payload_item($sanitized_post_data['long_description']);
     }
     if (array_key_exists('tags', $sanitized_post_data) && !empty($sanitized_post_data['tags'])) {
         // Convert tags string to an array.
         $update_data['tags'] = array_map('trim', explode(',', $sanitized_post_data['tags']));
     }
     $bc_accounts->set_current_account($sanitized_post_data['account']);
     $request = $this->cms_api->video_update($video_id, $update_data);
     $bc_accounts->restore_default_account();
     /**
      * If we had any tags in the update, add them to the tags collection if we don't already track them.
      */
     if (array_key_exists('tags', $update_data) && is_array($update_data['tags']) && count($update_data['tags'])) {
         $existing_tags = $this->tags->get_tags();
         $new_tags = array_diff($update_data['tags'], $existing_tags);
         if (count($new_tags)) {
             $this->tags->add_tags($new_tags);
         }
     }
     if (is_wp_error($request) || false === $request) {
         return false;
     }
     return true;
 }
 /**
  * Cleanup on uninstall
  */
 public function uninstall()
 {
     BC_Utility::uninstall_plugin();
 }
 protected function is_valid_account($account_id, $client_id, $client_secret, $account_name, $check_access = true)
 {
     // Save current account as $old_account.
     $old_account = $this->current_account;
     $new_account = array('account_id' => $account_id, 'client_id' => $client_id, 'client_secret' => $client_secret, 'account_name' => $account_name);
     $new_account['hash'] = BC_Utility::get_hash_for_account($new_account);
     // Set new account as $account.
     $this->current_account = $new_account;
     $oauth = new BC_Oauth_API();
     // Obtain session token with oAuth.
     $valid_credentials = $oauth->is_valid_account_credentials();
     $errors = array();
     if (!$valid_credentials) {
         $errors[] = new WP_Error('account-invalid-credentials', esc_html__('Invalid account credentials', 'brightcove'));
     } else {
         if ($check_access) {
             $errors = array_merge($errors, $this->check_permissions_level());
         }
     }
     // Restore current account transient (if exists).
     $this->current_account = $old_account;
     return !empty($errors) ? $errors : true;
 }
/**
 * Deactivate the plugin
 * Uninstall routines should be in uninstall.php
 */
function brightcove_deactivate()
{
    BC_Utility::deactivate();
}
 public function sort_api_response($playlists)
 {
     foreach ($playlists as $key => $playlist) {
         $id = BC_Utility::sanitize_and_generate_meta_video_id($playlist['id']);
         $playlists[$id] = $playlist;
         unset($playlists[$key]);
     }
     ksort($playlists);
     return $playlists;
 }
 /**
  * Render Player
  *
  * Renders the  player from Brightcove based on passed parameters
  *
  * @since 1.0
  *
  * @param string  $type       "playlist" or "video".
  * @param  string $id         The brightcove player or video ID.
  * @param string  $account_id The Brightcove account ID.
  * @param string  $player_id  The brightcove player ID.
  * @param int     $width      The Width to display.
  * @param int     $height     The height to display.
  *
  * @return string The HTML code for the player
  */
 public static function player($type, $id, $account_id, $player_id = 'default', $width = 0, $height = 0)
 {
     // Sanitize and Verify.
     $account_id = BC_Utility::sanitize_id($account_id);
     $player_id = 'default' == $player_id ? 'default' : BC_Utility::sanitize_id($player_id);
     $id = BC_Utility::sanitize_id($id);
     $height = (int) $height;
     $width = (int) $width;
     $type = 'playlist' === $type ? 'playlist' : 'video';
     if ('playlist' === $type && 'default' === $player_id) {
         $player_api = new BC_Player_Management_API();
         $players = $player_api->player_list_playlist_enabled();
         if (is_wp_error($players) || !is_array($players) || $players['item_count'] < 1) {
             return '<div class="brightcove-player-warning">' . __('A specified Source does not have a playlist capable player <a href="https://studio.brightcove.com/products/videocloud/players/">configured</a>. Make sure there is at least one player with "Display Playlist" enabled.', 'brightcove') . '</div>';
         }
         $player_id = esc_attr($players['items'][0]['id']);
     }
     $html = '<!-- Start of Brightcove Player -->';
     if (0 === $width && 0 === $height) {
         $html .= '<div style="display: block; position: relative; max-width: 100%;"><div style="padding-top: 56.25%;">';
     }
     $html .= sprintf('<iframe src="//players.brightcove.net/%s/%s_default/index.html?%sId=%s" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="" style="width: %s; height: %s;%s"></iframe>', $account_id, $player_id, $type, $id, 0 === $width ? '100%' : $width . 'px', 0 === $height ? '100%' : $height . 'px', 0 === $width && 0 === $height ? 'position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px;' : '');
     if (0 === $width && 0 === $height) {
         $html .= '</div></div>';
     }
     $html .= '<!-- End of Brightcove Player -->';
     return $html;
 }
 /**
  * When an API call hits our server, automatically flush cached Brightcove information
  *
  * This method is meant to be invoked
  * - Whenever a Dynamic Ingest request completes
  * - Whenever a video is updated on the server
  */
 public static function flush_cache()
 {
     BC_Utility::delete_cache_item('*');
 }
 public static function bc_activation_admin_notices()
 {
     global $bc_accounts;
     if (count($bc_accounts->get_sanitized_all_accounts()) > 0) {
         delete_option('_brightcove_plugin_activated');
         return;
     }
     if (get_option('_brightcove_plugin_activated') !== false && current_user_can('manage_options') && get_current_screen()->base !== 'brightcove_page_brightcove-sources' && get_current_screen()->base !== 'brightcove_page_brightcove-edit-source' && get_current_screen()->base !== 'admin_page_page-brightcove-edit-source') {
         $notices[] = array('message' => sprintf('%s <a href="%s"><strong>%s</strong></a>', esc_html__('Please configure Brightcove settings from', 'brightcove'), esc_url(admin_url('admin.php?page=brightcove-sources')), esc_html__('here', 'brightcove')), 'type' => 'updated');
         BC_Utility::admin_notice_messages($notices);
     }
 }
 public function get_player_hash_by_id($player_id)
 {
     $player = $this->get_player_by_id($player_id);
     if (!$player) {
         return false;
     } else {
         return BC_Utility::get_hash_for_object($player);
     }
 }
 /**
  * We receive a post with JSON (nothing in $_POST)
  * $_GET['id'] must contain the video ID
  * $_GET['auth'] must contain the anti spoof hash.
  */
 public function ingest_callback()
 {
     $json = file_get_contents('php://input');
     $decoded = json_decode($json, true);
     if (!isset($decoded['entity']) || !isset($_GET['id']) || !isset($_GET['auth']) || "SUCCESS" !== $decoded['status']) {
         exit;
     }
     $video_id = BC_Utility::sanitize_and_generate_meta_video_id($_GET['id']);
     $valid_auth = BC_Utility::get_auth_key_for_id($video_id);
     if (BC_Utility::sanitize_and_generate_meta_video_id($decoded['entity']) !== $video_id) {
         // We get lots of callbacks so we want to make sure that it's not
         // one of the transcodes that has completed, but rather this video.
         exit;
     }
     if ($valid_auth !== $_GET['auth']) {
         // Someone was spoofing callbacks?
         exit;
     }
     BC_Utility::remove_pending_uploads($video_id);
     // @todo: Set video uploaded state as complete.
     $this->trigger_background_fetch();
     exit;
 }
 /**
  * Render video
  *
  * Shortcode handler for BC Video embeds
  *
  * @since 1.0
  *
  * @param array $atts Array of shortcode parameters.
  *
  * @return string HTML for displaying shortcode.
  */
 public static function bc_playlist($atts)
 {
     $defaults = array('player_id' => 'default', 'account_id' => '', 'playlist_id' => '', 'height' => 0, 'width' => 0);
     $atts = shortcode_atts($defaults, $atts, 'bc_playlist');
     return BC_Utility::player('playlist', $atts['playlist_id'], $atts['account_id'], $atts['player_id'], $atts['width'], $atts['height']);
 }
 protected function is_valid_account($account_id, $client_id, $client_secret, $account_name, $check_access = true)
 {
     // Save current account as $old_account.
     $old_account = $this->current_account;
     $new_account = array('account_id' => $account_id, 'client_id' => $client_id, 'client_secret' => $client_secret, 'account_name' => $account_name);
     $new_account['hash'] = BC_Utility::get_hash_for_account($new_account);
     // Set new account as $account.
     $this->current_account = $new_account;
     $oauth = new BC_Oauth_API();
     // Obtain session token with oAuth.
     $valid_credentials = $oauth->is_valid_account_credentials();
     $errors = array();
     if (!$valid_credentials) {
         $errors[] = new WP_Error('account-invalid-credentials', esc_html__('Invalid account credentials', 'brightcove'));
     } else {
         if ($check_access) {
             $permission_issues = $this->check_permissions_level();
             if (count($permission_issues) > 0) {
                 $errors[] = new WP_Error('account-permission-issue', esc_html__("Supplied account doesn't have the following permissions: ", 'brightcove') . implode(', ', $permission_issues) . '. ' . esc_html__('Please use an account that has these permissions.', 'brightcove'));
             }
         }
     }
     // Restore current account transient (if exists).
     $this->current_account = $old_account;
     return !empty($errors) ? $errors : true;
 }
 /**
  * Add in process videos to media query results.
  * Also clear in process videos if they are already returned by brightcove.
  *
  * @param array $videos List of videos.
  *
  * @return array Processed list of videos.
  */
 public function add_in_process_videos($videos)
 {
     $video_ids = wp_list_pluck($videos, 'id');
     $video_post_ids = $this->videos->get_in_progress_videos();
     foreach ($video_post_ids as $video_post_id) {
         $in_process_video_id = BC_Utility::get_sanitized_video_id($video_post_id);
         if (in_array($in_process_video_id, $video_ids)) {
             wp_delete_post($video_post_id, true);
         } else {
             $videos[] = get_post_meta($video_post_id, '_brightcove_video_object', true);
         }
     }
     return $videos;
 }
Exemplo n.º 23
0
 /**
  * Sends API requests to remote server
  *
  * Sends the request to the remote server using the appropriate method and
  * logs any errors in the event of failures.
  *
  * @param string  $url             the endpoint to connect to
  * @param string  $method          the http method to use
  * @param array   $data            array of further data to send to the server
  * @param boolean $force_new_token whether or not to force obtaining a new oAuth token
  *
  *
  * @return mixed the return data from the call of false if a failure occurred
  */
 protected function send_request($url, $method = 'GET', $data = array(), $force_new_token = false)
 {
     $method = strtoupper(sanitize_text_field($method));
     $allowed_methods = array('DELETE', 'GET', 'PATCH', 'POST', 'PUT', 'JSON_DELETE', 'JSON_POST');
     //only allow methods required by the brightcove APIs
     if (!in_array($method, $allowed_methods)) {
         return false;
     }
     $url = esc_url_raw($url);
     $transient_key = false;
     if ($method === "GET") {
         $hash = substr(BC_Utility::get_hash_for_object(array("url" => $url, "data" => $data)), 0, 20);
         $transient_key = "_bc_request_{$hash}";
         $cached_request = BC_Utility::get_cache_item($transient_key);
         if (false !== $cached_request) {
             return $cached_request;
         }
     }
     $auth_header = $this->get_authorization_header($force_new_token);
     if (is_wp_error($auth_header)) {
         return $auth_header;
     }
     add_filter('http_request_timeout', array($this, 'increase_http_timeout'));
     $headers = array('Authorization' => $auth_header);
     // All JSON_ methods are used to indicate that application/json is the content type
     if (false !== strpos($method, 'JSON')) {
         $headers['Content-type'] = 'application/json';
         $method = str_replace('JSON_', '', $method);
     } else {
         $headers['Content-type'] = 'application/x-www-form-urlencoded';
     }
     $args = array('headers' => $headers);
     switch ($method) {
         case 'GET':
             $request = $this->cached_get($url, $args);
             break;
         case 'POST':
             $args['body'] = wp_json_encode($data);
             $request = wp_remote_post($url, $args);
             break;
         default:
             $args['method'] = $method;
             $args['body'] = wp_json_encode($data);
             if (!empty($data)) {
                 $args['body'] = json_encode($data);
             }
             $request = wp_remote_request($url, $args);
             break;
     }
     if (401 === wp_remote_retrieve_response_code($request)) {
         if ("Unauthorized" === $request['response']['message']) {
             // Token may have expired, so before we give up, let's retry
             // the request with a fresh OAuth token.
             if (!$force_new_token) {
                 return $this->send_request($url, $method, $data, true);
             } else {
                 $this->errors[] = array('url' => $url, 'error' => new WP_Error('unauthorized-oauth', __('API says permission denied, check your client ID and client secret', 'brightcove')));
                 return false;
             }
         }
     }
     //log errors for further processing or return the body
     if (is_wp_error($request)) {
         $this->errors[] = array('url' => $url, 'error' => $request->get_error_message());
         BC_Logging::log(sprintf('WP_ERROR: %s', $request->get_error_message()));
         return false;
     }
     $body = json_decode(wp_remote_retrieve_body($request), true);
     $successful_response_codes = array(200, 201, 202, 204);
     if (!in_array(wp_remote_retrieve_response_code($request), $successful_response_codes)) {
         $message = esc_html__('An unspecified error has occurred.', 'brightcove');
         if (isset($body[0]) && isset($body[0]['error_code'])) {
             $message = $body[0]['error_code'];
         } elseif (isset($body['message'])) {
             $message = $body['message'];
         }
         $this->errors[] = array('url' => $url, 'error' => new WP_Error($request['response']['message'], $message));
         BC_Logging::log(sprintf('BC API ERROR: %s', $message));
         return false;
     }
     if ('204' == wp_remote_retrieve_response_code($request)) {
         return true;
     }
     if ($transient_key && $body && (!defined('WP_DEBUG') || false === WP_DEBUG)) {
         // Store body for 60s to prevent hammering the BC APIs.
         BC_Utility::set_cache_item($transient_key, 'api-request', $body, 60);
     }
     return $body;
 }
 /**
  * Upload a video for processing
  *
  * Sends the URL of a video's master copy to the Dynamic Ingest API for processing.
  *
  * @since 1.0.0
  *
  * @param string $video_id  the ID of the video we're adding the master to
  * @param string $video_url the url of the video stored locally
  * @param string $profile   the profile to use for processing
  * @param bool   $callback  true to specify a local callback url or false
  *
  * @return string|bool the id of the ingest request or false on failure
  */
 public function video_upload($video_id, $video_url, $profile = 'balanced-high-definition', $callback = true)
 {
     $data = array('profile' => sanitize_text_field($profile));
     $data['master'] = array('url' => esc_url_raw($video_url));
     if (true === $callback) {
         $auth = BC_Utility::get_auth_key_for_id($video_id);
         $data['callbacks'] = array(get_admin_url() . 'admin-ajax.php?action=bc_ingest&id=' . $video_id . '&auth=' . $auth);
     }
     return $this->send_request(esc_url_raw(self::DI_BASE_URL . $this->get_account_id() . '/videos/' . $video_id . '/ingest-requests'), 'POST', $data);
 }
 /**
  * Method to display source update or error messages
  *
  * @return bool
  */
 public function admin_notice_handler()
 {
     if (empty($this->notices)) {
         return false;
     }
     BC_Utility::admin_notice_messages($this->notices);
     return true;
 }
 public static function get_video_playlist_dates_for_display($type)
 {
     $all_dates = BC_Utility::get_video_playlist_dates($type);
     foreach ($all_dates as $id => $dates_for_id) {
         $new_id = $id === 'all' ? 'all' : BC_Utility::get_sanitized_video_id($id);
         // Strip ID_
         $labelled_dates = array();
         foreach ($dates_for_id as $yyyy_mm) {
             $date_object = new DateTime($yyyy_mm . '-01');
             $labelled_dates[] = array('code' => $yyyy_mm, 'value' => $date_object->format('F Y'));
         }
         unset($all_dates[$id]);
         // Has to proceed for $id === 'all'
         $all_dates[$new_id] = $labelled_dates;
     }
     return $all_dates;
 }
<?php

/**
 * Uninstall Brightcove
 *
 * Removes all Brightcove data stored by the plugin
 *
 * @since   1.0.0
 *
 * @package Brightcove_Video_Connect
 */
if (!defined('WP_UNINSTALL_PLUGIN') || !WP_UNINSTALL_PLUGIN) {
    exit;
}
BC_Utility::uninstall_plugin();
 public function brightcove_media_query()
 {
     if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], '_bc_ajax_search_nonce')) {
         wp_send_json_error();
     }
     $video_ids = false;
     // Used for the playlist edit.
     if (isset($_POST['videoIds'])) {
         if ('none' === $_POST['videoIds']) {
             wp_send_json_success(array());
             // Existing playlist with no video IDs.
         }
         $video_ids = array();
         // To handle the playlist of one video ID which is sent as a string instead of Array of 1 element.
         if (is_string($_POST['videoIds'])) {
             $video_ids[] = BC_Utility::sanitize_id($_POST['videoIds']);
         } else {
             foreach ($_POST['videoIds'] as $video_id) {
                 $video_ids[] = BC_Utility::sanitize_id($video_id);
             }
         }
     }
     $account_id = isset($_POST['account']) ? sanitize_text_field($_POST['account']) : 'all';
     if ('all' !== $account_id) {
         $account_id = BC_Utility::sanitize_id($_POST['account']);
     }
     $query = isset($_POST['search']) && '' !== $_POST['search'] ? sanitize_text_field($_POST['search']) : false;
     $tags = isset($_POST['tags']) && '' !== $_POST['tags'] ? array_map('absint', (array) $_POST['tags']) : false;
     $tag_name = isset($_POST['tagName']) && '' !== $_POST['tagName'] ? sanitize_text_field($_POST['tagName']) : false;
     $dates = isset($_POST['dates']) && 'all' !== $_POST['dates'] ? BC_Utility::sanitize_date($_POST['dates']) : false;
     $posts_per_page = isset($_POST['posts_per_page']) ? absint($_POST['posts_per_page']) : apply_filters('brightcove_max_posts_per_page', 100);
     $page = isset($_POST['page_number']) ? absint($_POST['page_number']) : 1;
     $type = isset($_POST['type']) ? sanitize_key($_POST['type']) : false;
     if (!$type || !in_array($type, array('videos', 'playlists'))) {
         wp_send_json_error(esc_html__('Invalid Search Type', 'brightcove'));
         exit;
         // Type can only be videos or playlists.
     }
     global $bc_accounts;
     if ('videos' === $type) {
         $query_terms = array();
         $query_string = '';
         if ($tag_name) {
             $query_terms[] = "tags:{$tag_name}";
             $query_string .= "tags:{$tag_name}";
         }
         if ($dates) {
             $query_terms[] = "updated_at:{$dates}-01..{$dates}-31";
             $query_string .= "updated_at:{$dates}-01..{$dates}-31";
         }
         if ($query) {
             array_unshift($query_terms, $query);
         }
         if ($video_ids) {
             // We send the video_ids sorted since we have them returned sorted by ID.
             // This way we get cache hits when playlist order, but not content have changed.
             $video_ids_sorted = $video_ids;
             sort($video_ids_sorted);
             $query_terms[] = "id:" . implode("+id:", $video_ids_sorted);
         }
         $query_string = implode("+", $query_terms);
         /**
          * For playlists, we specify the order in the query string as follows:
          * https://cms.api.brightcove.com/v1/accounts/<account_id>/videos?q=id:<video_id1>...+id:<video_idn>
          *
          * However it comes back to us sorted by video ID (smallest to largest, so afterwards we resort the dataset
          * by playlist sort order.
          */
         $bc_accounts->set_current_account_by_id($account_id);
         $results = $this->cms_api->video_list($posts_per_page, $posts_per_page * ($page - 1), $query_string, 'updated_at');
         /**
          * Since we use the video_list to fetch the videos for a playlist, it returns them to us
          * ordered by video_id, so we use the order of video_ids (the playlist order) to sort them
          * as per the playlist.
          */
         if ($video_ids) {
             $ordered_results = array();
             foreach ($video_ids as $video_id) {
                 foreach ($results as $video_result) {
                     if ($video_id === $video_result['id']) {
                         $ordered_results[] = $video_result;
                         break;
                     }
                 }
             }
             // $ordered_results is now in the same order as $video_ids
             $results = $ordered_results;
         }
     } else {
         $bc_accounts->set_current_account_by_id($account_id);
         $results = $this->cms_api->playlist_list();
     }
     $bc_accounts->restore_default_account();
     wp_send_json_success($results);
 }
 /**
  * Update a video in the Brightcove Video Cloud
  *
  * Updates a video with the provided id and optional other data in the video cloud.
  *
  * @since 1.0.0
  *
  * @param string $video_id the id of the video to update
  * @param array $args optional array of other arguments used in video creation
  *
  * @return array|bool array of data about the updated video or false on failure.
  */
 public function video_update($video_id, $args = array())
 {
     $data = array();
     $video_id = utf8_uri_encode(sanitize_text_field($video_id));
     $data = BC_Utility::sanitize_payload_args_recursive($args);
     return $this->send_request(esc_url_raw(self::CMS_BASE_URL . $this->get_account_id() . '/videos/' . $video_id), 'PATCH', $data);
 }
 public function check_allowed_file($file_data)
 {
     $bc_allowed_types = BC_Utility::get_all_brightcove_mimetypes();
     $allowed_ext = array_search($file_data['type'], $bc_allowed_types);
     if (false === $allowed_ext) {
         return false;
     }
     // Check if type is allowed by WordPress.
     $ext = pathinfo($file_data['name'], PATHINFO_EXTENSION);
     // If the extension matches the type.
     if ($allowed_ext === $ext) {
         return true;
     }
     return false;
 }