class-export-media-urls-admin.php 18.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
<?php

/**
 * Export Media URLs
 *
 * @package Export Media URLs
 *
   

 **/

namespace Export_Media_URLs;

require_once(plugin_dir_path(__FILE__) . '../classes/constants.php');

$export_media_urls_admin = new ExportMediaURLsAdmin();

class ExportMediaURLsAdmin
{

    public function __construct()
    {


        add_action('admin_init', array($this, 'redirect_on_activation'));
        add_action('admin_menu', array($this, 'add_plugin_page'));
        add_action('admin_footer_text', array($this, 'add_plugin_text_in_footer'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    public function redirect_on_activation()
    {

        if (!get_transient('export_media_urls_activation_redirect')) {
            return;
        }

        delete_transient('export_media_urls_activation_redirect');

        wp_safe_redirect(add_query_arg(array('page' => Constants::PLUGIN_SETTINGS_PAGE_SLUG), admin_url('tools.php')));
    }

    public function add_plugin_page()
    {

        add_management_page(
            'Export Media URLs',
            'Export Media URLs',
            Constants::PLUGIN_SETTINGS_PAGE_CAPABILITY,
            Constants::PLUGIN_SETTINGS_PAGE_SLUG,
            array($this, 'emu_settings_page')
        );
    }

    public function add_plugin_text_in_footer($footer_text)
    {

        if ($this->is_my_plugin_screen()) {

            $footer_text = 'Enjoyed <strong>Export Media URLs</strong>? ';
        }

        return $footer_text;
    }

    public function enqueue_scripts($hook_suffix)
    {

        if($hook_suffix !== Constants::PLUGIN_HOOK_SUFFIX) {
            return;
        }

        wp_enqueue_style('emu_style', plugin_dir_url(__FILE__) . '../assets/css/style.css', array(), '2.1', 'all');

        if (!wp_script_is('select2', 'registered')) {
            wp_register_script('select2', plugin_dir_url(__FILE__) . '../assets/js/select2.min.js', array('jquery'), '4.0.13', true);
            wp_register_style('select2css', plugin_dir_url(__FILE__) . '../assets/css/select2.min.css', false, '4.0.13', 'all');
        }

        if (!wp_script_is('select2', 'enqueued')) {
            wp_enqueue_script('select2');
            wp_enqueue_style('select2css');
        }
        
        wp_enqueue_script('emu_script', plugin_dir_url(__FILE__) . '../assets/js/script.js', array('jquery', 'select2'), '2.1', true);
    }

    public function emu_settings_page()
    {
        if (!current_user_can(Constants::PLUGIN_SETTINGS_PAGE_CAPABILITY)) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', Constants::PLUGIN_TEXT_DOMAIN));
        }

        $user_ids = array();
        $user_names = array();

        $users = get_users();

        foreach ($users as $user) {
            $user_ids[] = $user->data->ID;
            $user_names[] = $user->data->user_login;
        }

?>

        <div class="wrap">

            <h2 align="center">Stellervista Export Media URLs</h2>

            <div class="EMU-Wrapper">
                <div class="EMU-Main-Container postbox">
                    <div class="inside">

                        <form id="infoForm" method="post">

                            <table class="form-table">

                                <tr>

                                    <th><label>Additional Data:</label></th>

                                    <td>

                                        <label><input type="checkbox" name="additional-data[]" value="id" checked/>
                                            ID</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="title" checked/>
                                            Title</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="file_name" checked/>
                                            File Name</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="caption" />
                                            Caption</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="alt" />
                                            Alt Text</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="description" />
                                            Description</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="url" checked />
                                            URL</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="date" checked/> Date Uploaded</label><br />

                                        <label><input type="checkbox" name="additional-data[]" value="type" checked/> Type</label><br />
                                        <label><input type="checkbox" name="additional-data[]" value="category" checked/> Category</label><br />

                                    </td>

                                </tr>

                                <tr>
                                    <th><label for="post-author">By Author:</label></th>
                                    <td>
                                        <select id="post-author" class="select2" name="post-author" required="required" style="width: 40%;">
                                            <option value="all" selected>All</option>
                                            <?php
                                            if (!empty($user_ids) && !empty($user_names)) {
                                                for ($i = 0; $i < count($user_ids); $i++) {
                                                    echo '<option value="' . esc_attr($user_ids[$i]) . '">' . esc_html($user_names[$i]) . '</option>';
                                                }
                                            }
                                            ?>
                                        </select>
                                    </td>
                                </tr>


                                <tr>

                                    <th><label>Export Type:</label></th>

                                    <td>

                                        <label><input type="radio" name="export-type" value="csv" required="required"  checked/> CSV File</label><br />
                                        <label><input type="radio" name="export-type" value="dashboard" required="required" />
                                            Output here</label><br />

                                    </td>

                                </tr>

                                <tr>

                                    <td></td>

                                    <td>
                                        <?php wp_nonce_field('export_media_urls'); ?>
                                        <input type="submit" name="export" class="button button-primary" value="Export Now" />
                                    </td>

                                </tr>

                            </table>


                        </form>


                    </div>
                </div>
                <div class="EMU-Side-Container">
                    
                </div>
            </div>

        </div>

<?php

        if (isset($_POST['export'])) {

            if (isset($_REQUEST['_wpnonce'])) {
                $nonce = $_REQUEST['_wpnonce'];
                if (!wp_verify_nonce($nonce, 'export_media_urls')) {
                    echo "<div class='notice notice-error' style='width: 93%'>" . __('Sorry, invalid security token!', Constants::PLUGIN_TEXT_DOMAIN) . "</div>";
                    exit;
                }

                if (!empty($_POST['additional-data']) && !empty($_POST['post-author']) && !empty($_POST['export-type'])) {
                    $additional_data = $_POST['additional-data'];
                    $post_author = $_POST['post-author'];

                    $export_type = $_POST['export-type'];

                    $this->create_output($this->emu_generate_data($additional_data, $post_author, $export_type), $export_type);
                } else {
                    echo __("Sorry, you did not select anything to export, Please <strong>Select Data </strong> you want to export, and then try again! :)", Constants::PLUGIN_TEXT_DOMAIN);
                    exit;
                }
            }
        } elseif (isset($_REQUEST['del']) && $_REQUEST['del'] == 'y') {
            if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'])) {
                echo __("You are not authorized to perform this action!", Constants::PLUGIN_TEXT_DOMAIN);
                exit();
            } else {
                $file = base64_decode($_REQUEST['f']);
                $path_info = pathinfo($file);
                $upload_dir = wp_upload_dir();

                if (($path_info['dirname'] == $upload_dir['path']) && ($path_info['extension'] == 'CSV')) {
                    echo !empty($file) ? (file_exists($file) ? (!unlink($file) ? "<div class='notice notice-error' style='width: 97%'></div>" . __("Unable to delete file, please delete it manually!", Constants::PLUGIN_TEXT_DOMAIN) : "<div class='updated' style='width: 97%'>" . __("You did great, the file was <strong>Deleted Successfully</strong>!", Constants::PLUGIN_TEXT_DOMAIN) . "</div>") : null) : "<div class='notice notice-error'>" . __("Missing file path.", Constants::PLUGIN_TEXT_DOMAIN) . "</div>";
                } else {
                    die("<div class='error' style='width: 95.3%; margin-left: 2px;'>" . __("Sorry, the file verification failed. Arbitrary file removal is not allowed.", Constants::PLUGIN_TEXT_DOMAIN) . "</div>");
                }
            }
        }
    }

    private function is_my_plugin_screen()
    {

        $current_screen = get_current_screen();

        if ($current_screen && false !== strpos($current_screen->id, Constants::PLUGIN_SETTINGS_PAGE_SLUG)) {
            return true;
        } else {
            return false;
        }
    }

    private function emu_is_checked($name, $value)
    {
        foreach ($name as $data) {
            if ($data == $value) {
                return true;
            }
        }

        return false;
    }

    private function emu_generate_data($additional_data, $post_author, $export_type)
    {

        $data = array();
        $counter = 0;

        $line_break = $export_type == 'dashboard' ? "<br/>" : "";

        $query_media_urls = array(
            'post_type'         => 'attachment',
            'author'            => $post_author != 'all' ? $post_author : "",
            'post_status'       => 'inherit',
            'posts_per_page'    => -1,
        );

        $query_urls = new \WP_Query($query_media_urls);

        if (!$query_urls->have_posts()) {
            echo __("No result found in that range, please <strong>reselect and try again</strong>!", Constants::PLUGIN_TEXT_DOMAIN);
            exit();
        }

        foreach ($additional_data as $data_type) {
            if ($this->emu_is_checked($additional_data, $data_type)) {
                $counter = 0;
                while ($query_urls->have_posts()) {
                    $query_urls->the_post();

                    if (!isset($data[$data_type][$counter])) {
                        $data[$data_type][$counter] = null;
                    }
                 
                    
                    switch ($data_type) {
                        case 'id':
                            $data[$data_type][$counter] .= get_the_ID() . $line_break;
                            break;

                        case 'title':
                            $data[$data_type][$counter] .= get_the_title() . $line_break;
                            break;

                        case 'file_name':
                            $data[$data_type][$counter] .= wp_basename(get_attached_file(get_the_ID())) . $line_break;
                            break;

                        case 'caption':
                            $data[$data_type][$counter] .= get_the_excerpt() . $line_break;
                            break;

                        case 'alt':
                            $attachment_id = get_the_ID();
                            $alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
                            $data[$data_type][$counter] .= $alt_text . $line_break;
                            break;

                        case 'description':
                            $data[$data_type][$counter] .= get_the_content() . $line_break;
                            break;

                        case 'url':
                            $data[$data_type][$counter] .= wp_get_attachment_url(get_the_ID());
                            break;

                        case 'date':
                            $data[$data_type][$counter] .= get_the_date() . $line_break;
                            break;

                        case 'type':
                            $data[$data_type][$counter] .= get_post_mime_type() . $line_break;
                            break;
                        case 'category':
                            $categories = wp_get_post_terms(get_the_ID(), 'mlo-category', array('fields' => 'names'));
                            $data['category'][$counter] .= implode(', ', $categories) . $line_break;
                            break;
                     default:
                            break;
                           
                    }

                       

                    $counter++;
                }

                wp_reset_postdata();
            }
        }

        return $data;
    }

    private function get_data_headers($data)
    {
        $filtered_headers = [];

        $headers = [
            'id'          => 'ID',
            'title'       => 'Title',
            'file_name'   => 'File Name',
            'caption'     => 'Caption',
            'alt'         => 'Alt Text',
            'description' => 'Description',
            'url'         => 'URLs',
            'date'        => 'Date Uploaded',
            'type'        => 'Type',
            'category'    => 'Categories',
        ];

        foreach ($headers as $key => $name) {
            if (isset($data[$key])) {
                $filtered_headers[$key] = $name;
            }
        }

        return $filtered_headers;
    }

    private function create_output($data, $export_type)
    {
        $count = count($data['url']);
        $headers = $this->get_data_headers($data);

        switch ($export_type) {
            case 'csv':
                $upload_directory = wp_upload_dir();
                $csv_file_name = 'export-media-urls-' . rand(111111, 999999);
                $csv_file_path = $upload_directory['path'] . "/" . $csv_file_name . '.CSV';

                $file = fopen($csv_file_path, "w");
                if (!$file) {
                    return __("Error: Could not create file.", Constants::PLUGIN_TEXT_DOMAIN);
                }

                fprintf($file, "\xEF\xBB\xBF");

                if (!fputcsv($file, $headers)) {
                    fclose($file);
                    return __("Error: Could not write headers to file.", Constants::PLUGIN_TEXT_DOMAIN);
                }

                for ($i = 0; $i < $count; $i++) {
                    $csv_row = [];

                    foreach ($headers as $key => $val) {
                        $cellValue = isset($data[$key]) ? $data[$key][$i] : '';

                        if ($key === 'description') {
                            $cellValue = wp_kses_post($cellValue);
                        } elseif ($key === 'url') {
                            $cellValue = esc_url($cellValue);
                        } else {
                            $cellValue = sanitize_text_field($cellValue);
                        }

                        $csv_row[] = $cellValue;
                    }

                    if (!fputcsv($file, $csv_row)) {
                        fclose($file);
                        return __("Error: Could not write row to file.", Constants::PLUGIN_TEXT_DOMAIN);
                    }
                }

                fclose($file);

                $csv_download_url = $upload_directory['url'] . "/" . $csv_file_name . ".CSV";
                $success_message = __("Media Data Exported Successfully! <a href='$csv_download_url' target='_blank'><strong>Click here</strong></a> to Download.", Constants::PLUGIN_TEXT_DOMAIN);

                echo "<div class='updated' style='width: 97%'>$success_message</div>";

                echo "<div class='notice notice-warning' style='width: 97%'>" . __('Once you have downloaded the file, it is recommended to delete file from the server, for security reasons.', Constants::PLUGIN_TEXT_DOMAIN) . " <a href='" . wp_nonce_url(admin_url('tools.php?page=' . Constants::PLUGIN_SETTINGS_PAGE_SLUG . '&del=y&f=') . base64_encode($csv_file_path)) . "' ><strong>" . __('Click Here', Constants::PLUGIN_TEXT_DOMAIN) . "</strong></a> " . __('to delete the file. And don\'t worry, you can always regenerate anytime. :)', Constants::PLUGIN_TEXT_DOMAIN) . "</div>";

                break;

            default:
                $tableHtml = "<h1 align='center' style='padding: 10px 0;line-height: 1'><strong>" . __("Below is a list of Exported Media Data:", Constants::PLUGIN_TEXT_DOMAIN) . "</strong></h1>";
                $tableHtml .= "<table class='form-table' id='outputData'><tr><th>#";

                foreach ($headers as $key => $val) {
                    if (isset($data[$key])) {
                        $tableHtml .= "<th id='$key'>$val</th>";
                    }
                }

                $tableHtml .= "</tr>";

                for ($i = 0; $i < $count; $i++) {
                    $id = $i + 1;

                    $tableHtml .= "<tr><td>" . absint($id) . "</td>";

                    foreach ($headers as $key => $val) {
                        if (isset($data[$key])) {
                            $cellValue = $data[$key][$i];

                            if ($key === 'description') {
                                $cellValue = wp_kses_post($cellValue);
                            } elseif ($key === 'url') {
                                $cellValue = esc_url($cellValue);
                            } else {
                                $cellValue = sanitize_text_field($cellValue);
                            }

                            $tableHtml .= "<td>$cellValue</td>";
                        }
                    }

                    $tableHtml .= "</tr>";
                }

                $tableHtml .= "</table>";

                echo $tableHtml;
        }
    }
}