/**
 * Echoes the right link to BuddyDrive root folder regarding to context
 *
 * @uses bp_is_user() to check for user's buddydrive
 * @uses bp_current_action() to check for BuddyDrive nav
 * @uses buddydrive_get_user_buddydrive_url() to print the BuuddyBox user's url
 * @uses buddydrive_get_friends_subnav_slug() to get friends subnav slug
 * @uses buddydrive_get_friends_buddydrive_url() to print the Shared by friends BuddyDrive Url
 * @uses buddydrive_is_group() to check for the BuddyDrive group area
 * @uses buddydrive_get_group_buddydrive_url() to print the BuddyDrive group's url
 * @return the right url
 */
function buddydrive_component_home_url()
{
    if (bp_is_user() && bp_current_action() == 'files') {
        echo buddydrive_get_user_buddydrive_url();
    } else {
        if (bp_is_user() && bp_current_action() == buddydrive_get_friends_subnav_slug()) {
            echo buddydrive_get_friends_buddydrive_url();
        } else {
            if (buddydrive_is_group()) {
                echo buddydrive_get_group_buddydrive_url();
            }
        }
    }
}
/**
 * Manages file downloads based on the privacy of the file/folder
 *
 * @uses bp_displayed_user_id() to be sure we're not on a profile
 * @uses bp_is_current_component() to check for BuddyDrive component
 * @uses bp_current_action() to check if current action is file / folder
 * @uses esc_url()
 * @uses wp_get_referer() to eventually redirect the user
 * @uses bp_action_variable() to get the name of the file / folder
 * @uses buddydrive_get_buddyfile() to get the file / folder object
 * @uses buddydrive_get_folder_post_type() to get the folder post type
 * @uses bp_loggedin_user_id() to get current user id
 * @uses is_super_admin() as super admin can download anything
 * @uses bp_core_add_message() to eventually display a warning message to user
 * @uses buddydrive_get_user_buddydrive_url() to construct the user's BuddyDrive url
 * @uses bp_core_redirect() to redirect user if needed
 * @uses friends_check_friendship() to check if the current user is friend with the file owner
 * @uses bp_is_active() to check a BuddyPress component is active
 * @uses groups_is_user_member() to check if the current user is member of the group of the file
 * @uses groups_get_group() to get the group object of the group the file / folder is attached to
 * @uses bp_get_group_permalink() to build the group link
 * @uses buddydrive_get_group_buddydrive_url() to build the link to the BuddyDrive of the group
 * @uses site_url() to redirect to home if nothing match
 * @return binary the file! (or redirects to the folder)
 */
function buddydrive_file_downloader()
{
    if (!bp_displayed_user_id() && bp_is_current_component('buddydrive') && 'file' == bp_current_action()) {
        $redirect = esc_url(wp_get_referer());
        $buddyfile_name = bp_action_variable(0);
        $buddydrive_file = buddydrive_get_buddyfile($buddyfile_name);
        if (empty($buddydrive_file)) {
            bp_core_add_message(__('OOps, we could not find your file.', 'buddydrive'), 'error');
            bp_core_redirect(buddydrive_get_root_url());
        }
        $buddydrive_file_path = $buddydrive_file->path;
        $buddydrive_file_name = $buddydrive_file->file;
        $buddydrive_file_mime = $buddydrive_file->mime_type;
        // if the file belongs to a folder, we need to get the folder's privacy settings
        if (!empty($buddydrive_file->post_parent)) {
            $parent = $buddydrive_file->post_parent;
            $buddydrive_file = buddydrive_get_buddyfile($parent, buddydrive_get_folder_post_type());
        }
        $can_donwload = false;
        if (!empty($buddydrive_file->check_for)) {
            switch ($buddydrive_file->check_for) {
                case 'private':
                    if ($buddydrive_file->user_id == bp_loggedin_user_id() || is_super_admin()) {
                        $can_donwload = true;
                    }
                    break;
                case 'password':
                    if ($buddydrive_file->user_id == bp_loggedin_user_id() || is_super_admin()) {
                        $can_donwload = true;
                    } elseif (empty($_POST['buddyfile-form'])) {
                        bp_core_add_message(__('This file is password protected', 'buddydrive'), 'error');
                        add_action('buddydrive_directory_content', 'buddydrive_file_password_form');
                        $can_donwload = false;
                    } else {
                        //check admin referer
                        if ($buddydrive_file->password == $_POST['buddyfile-form']['password']) {
                            $can_donwload = true;
                        } else {
                            $redirect = buddydrive_get_user_buddydrive_url($buddydrive_file->user_id);
                            bp_core_add_message(__('Wrong password', 'buddydrive'), 'error');
                            bp_core_redirect($redirect);
                            $can_donwload = false;
                        }
                    }
                    break;
                case 'public':
                    $can_donwload = true;
                    break;
                case 'friends':
                    if ($buddydrive_file->user_id == bp_loggedin_user_id() || is_super_admin()) {
                        $can_donwload = true;
                    } elseif (bp_is_active('friends') && friends_check_friendship($buddydrive_file->user_id, bp_loggedin_user_id())) {
                        $can_donwload = true;
                    } else {
                        $redirect = buddydrive_get_user_buddydrive_url($buddydrive_file->user_id);
                        bp_core_add_message(__('You must be a friend of this member to download the file', 'buddydrive'), 'error');
                        bp_core_redirect($redirect);
                        $can_donwload = false;
                    }
                    break;
                case 'groups':
                    if ($buddydrive_file->user_id == bp_loggedin_user_id() || is_super_admin()) {
                        $can_donwload = true;
                    } elseif (!bp_is_active('groups')) {
                        bp_core_add_message(__('Group component is deactivated, please contact the administrator.', 'buddydrive'), 'error');
                        bp_core_redirect(buddydrive_get_root_url());
                        $can_donwload = false;
                    } elseif (groups_is_user_member(bp_loggedin_user_id(), intval($buddydrive_file->group))) {
                        $can_donwload = true;
                    } else {
                        $group = groups_get_group(array('group_id' => $buddydrive_file->group));
                        if ('hidden' == $group->status) {
                            $redirect = wp_get_referer();
                        } else {
                            $redirect = bp_get_group_permalink($group);
                        }
                        bp_core_add_message(__('You must be member of the group to download the file', 'buddydrive'), 'error');
                        bp_core_redirect($redirect);
                        $can_donwload = false;
                    }
                    break;
                default:
                    /**
                     * Filter here for custom privacy options
                     * 
                     * @since 1.3.3
                     * 
                     * @param bool   $can_download    True if the file can be downloaded, false otherwise.
                     * @param object $buddydrive_file The BuddyDrive file object.
                     */
                    $can_donwload = apply_filters('buddydrive_file_downloader_can_download', $can_download, $buddydrive_file);
                    break;
            }
        } else {
            if ($buddydrive_file->user_id == bp_loggedin_user_id() || is_super_admin()) {
                $can_donwload = true;
            }
        }
        // we have a file! let's force download.
        if (file_exists($buddydrive_file_path) && !empty($can_donwload)) {
            do_action('buddydrive_file_downloaded', $buddydrive_file);
            status_header(200);
            header('Cache-Control: cache, must-revalidate');
            header('Pragma: public');
            header('Content-Description: File Transfer');
            header('Content-Length: ' . filesize($buddydrive_file_path));
            header('Content-Disposition: attachment; filename=' . $buddydrive_file_name);
            header('Content-Type: ' . $buddydrive_file_mime);
            readfile($buddydrive_file_path);
            die;
        }
    } else {
        if (!bp_displayed_user_id() && bp_is_current_component('buddydrive') && 'folder' == bp_current_action()) {
            $buddyfolder_name = bp_action_variable(0);
            $buddyfolder = buddydrive_get_buddyfile($buddyfolder_name, buddydrive_get_folder_post_type());
            if (empty($buddyfolder)) {
                bp_core_add_message(__('OOps, we could not find your folder.', 'buddydrive'), 'error');
                bp_core_redirect(buddydrive_get_root_url());
            }
            // in case of the folder, we open it on the user's BuddyDrive or the group one
            $buddydrive_root_link = $buddyfolder->check_for == 'groups' ? buddydrive_get_group_buddydrive_url($buddyfolder->group) : buddydrive_get_user_buddydrive_url($buddyfolder->user_id);
            $link = $buddydrive_root_link . '?folder-' . $buddyfolder->ID;
            bp_core_redirect($link);
        }
    }
}
/**
 * Handles an embed BuddyDrive item
 *
 * @param array $matches the result of the preg_match
 * @param array $attr
 * @param string $url
 * @param array $rawattr
 * @uses is_multisite() to check for multisite config
 * @uses bp_get_root_blog_id() to get the root blog id
 * @uses switch_to_blog() to change for root blog id
 * @uses buddydrive_get_buddyfile() to get the BuddyDrive Item
 * @uses buddydrive_get_file_post_type() to get the BuddyFile post type
 * @uses wp_mime_type_icon() to get the WordPress crystal icon
 * @uses buddydrive_get_folder_post_type() to get the BuddyFolder post type
 * @uses buddydrive_get_group_buddydrive_url() to build the url to the BuddyDrive group
 * @uses buddydrive_get_user_buddydrive_url() to get the user's BuddyDrive url
 * @uses buddydrive_get_images_url() to get the image url of the plugin
 * @uses the BuddyDrive Loop and some tempkate tags
 * @uses wp_reset_postdata() to avoid some weird link..
 * @uses restore_current_blog() to restore the child blog.
 * @return string $embed the html output
 */
function wp_embed_handler_buddydrive($matches, $attr, $url, $rawattr)
{
    $link = $title = $icon = $content = $mime_type = $filelist = $hw_attr = false;
    $current_blog = get_current_blog_id();
    if (is_multisite() && (int) $current_blog !== (int) bp_get_root_blog_id()) {
        switch_to_blog(bp_get_root_blog_id());
    }
    if ($matches[1] == 'file') {
        $buddyfile = buddydrive_get_buddyfile($matches[2], buddydrive_get_file_post_type());
        if (empty($buddyfile)) {
            return '';
        }
        $link = $buddyfile->link;
        $title = $buddyfile->title;
        $content = $buddyfile->content;
        $mime_type = $buddyfile->mime_type;
        $icon = wp_mime_type_icon($buddyfile->ID);
        if ('public' === $buddyfile->check_for) {
            $thumbnail = buddydrive_get_thumbnail($buddyfile->ID, 'thumburl', false);
            if (!empty($thumbnail[0])) {
                $icon = $thumbnail[0];
                $hw_attr = image_hwstring($thumbnail[1], $thumbnail[2]);
            }
        }
        // It's a folfer
    } else {
        $buddyfile = buddydrive_get_buddyfile($matches[2], buddydrive_get_folder_post_type());
        if (empty($buddyfile)) {
            return '';
        }
        $buddydrive_root_link = $buddyfile->check_for == 'groups' ? buddydrive_get_group_buddydrive_url($buddyfile->group) : buddydrive_get_user_buddydrive_url($buddyfile->user_id);
        $link = $buddydrive_root_link . '?folder-' . $buddyfile->ID;
        $title = $buddyfile->title;
        $mime_type = $buddyfile->mime_type;
        $icon = buddydrive_get_images_url() . 'folder.png';
    }
    $embed = '<table style="width:auto"><tr>';
    $tdwidth = 'width:60px;';
    if (!empty($hw_attr)) {
        $tdwidth = '';
    }
    $embed .= '<td style="vertical-align:middle;' . $tdwidth . '"><a href="' . esc_url($link) . '" title="' . esc_attr($title) . '"><img src="' . esc_url($icon) . '" alt="' . esc_attr($mime_type) . '" class="buddydrive-thumb" ' . $hw_attr . '></a></td>';
    $embed .= '<td style="vertical-align:middle"><h6 style="margin:0"><a href="' . esc_url($link) . '" title="' . esc_attr($title) . '">' . esc_html($title) . '</a></h6>';
    if (!empty($content)) {
        $embed .= '<p style="margin:0">' . esc_html($content) . '</p>';
    }
    if ($matches[1] == 'folder') {
        global $buddydrive_template;
        if (buddydrive_has_items(array('buddydrive_parent' => $buddyfile->ID))) {
            $filelist = '<p style="margin-top:1em;margin-bottom:0">' . esc_html__('Files included in this folder :', 'buddydrive') . '</p><ul>';
            while (buddydrive_has_items()) {
                buddydrive_the_item();
                $filelist .= '<li><a href="' . esc_url(buddydrive_get_action_link()) . '" title="' . esc_attr(buddydrive_get_item_title()) . '">' . esc_html(buddydrive_get_item_title()) . '</a></li>';
            }
            $filelist .= '</ul>';
            $buddydrive_template = false;
        }
        wp_reset_postdata();
        $embed .= $filelist;
    }
    $embed .= '</td></tr></table>';
    if (is_multisite() && (int) $current_blog !== (int) bp_get_root_blog_id()) {
        restore_current_blog();
    }
    return apply_filters('embed_buddydrive', $embed, $matches, $attr, $url, $rawattr);
}