<?php
/**
 * This file contains all functions for displaying the show_publications page in admin menu
 * 
 * @package teachpress\admin\publications
 * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2 or later
 */

/**
 * Add screen options for show publications page
 */
function tp_show_publications_page_screen_options() {
    global $tp_admin_all_pub_page;
    global $tp_admin_your_pub_page;
    $screen = get_current_screen();
 
    if(!is_object($screen) || ( $screen->id != $tp_admin_all_pub_page && $screen->id != $tp_admin_your_pub_page ) ) {
        return;
    }

    $args = array(
        'label'     => esc_html__('Items per page', 'teachpress'),
        'default'   => 50,
        'option'    => 'tp_pubs_per_page'
    );
    add_screen_option( 'per_page', $args );
}

/**
 * Add help tab for show publications page
 */
function tp_show_publications_page_help () {
    $screen = get_current_screen();  
    $screen->add_help_tab( array(
        'id'        => 'tp_show_publications_help',
        'title'     => esc_html__('Display publications','teachpress'),
        'content'   => '<p><strong>' . esc_html__('Shortcodes') . '</strong></p>
                        <p>' . esc_html__('You can use publications in a page or article with the following shortcodes:','teachpress') . '</p>
                        <p>' . esc_html__('For a single publication:','teachpress') .  '<strong>[tpsingle]</strong></p>
                        <p>' . esc_html__('For a publication list with tag cloud:','teachpress') . ' <strong>[tpcloud]</strong></p>
                        <p>' . esc_html__('For normal publication lists:','teachpress') . ' <strong>[tplist]</strong></p>
                        <p><strong>' . esc_html__('More information','teachpress') . '</strong></p>
                        <p><a href="https://github.com/winkm89/teachPress/wiki#shortcodes" target="_blank" title="teachPress Shortcode Reference (engl.)">teachPress Shortcode Reference (engl.)</a></p>',
    ) );
}

/**
 * Controller for show publications page
 * @global object $current_user
 * @since 5.0.0
 */
function tp_show_publications_page() {
    // WordPress User informations
    $current_user = wp_get_current_user();
    
    // teachPress Publication Types
    global $tp_publication_types;
    
    // Get screen options
    $screen = get_current_screen();
    $screen_option = $screen->get_option('per_page', 'option');
    $per_page = get_user_meta($current_user->ID, $screen_option, true);
    if ( empty ( $per_page) || $per_page < 1 ) {
        $per_page = $screen->get_option( 'per_page', 'default' );
    }

    $array_variables['checkbox'] = isset( $_GET['checkbox'] ) ? $_GET['checkbox'] : '';
    $array_variables['action'] = isset( $_GET['action'] ) ? $_GET['action'] : '';
    $array_variables['page'] = isset( $_GET['page'] ) ? htmlspecialchars($_GET['page']) : '';
    $array_variables['type'] = ( isset( $_GET['type'] ) && intval($_GET['type']) !== 0 ) ? tp_convert_input_to_string($_GET['type']) : '';
    $array_variables['year'] = ( isset( $_GET['tp_year'] ) && intval($_GET['tp_year']) !== 0 ) ? tp_convert_input_to_string($_GET['tp_year'], 'int') : '';
    $array_variables['order'] = isset( $_GET['orderby'] ) ? htmlspecialchars($_GET['orderby']) : 'date DESC, title ASC';
    $array_variables['search'] = isset( $_GET['search'] ) ? htmlspecialchars($_GET['search']) : '';
    $array_variables['tag_id'] = isset( $_GET['tag'] ) ? tp_convert_input_to_string($_GET['tag'], 'int') : '';
    $user = $current_user->ID;

    // Page menu
    $array_variables['per_page'] = $per_page;
    
    // Handle limits
    if ( isset($_GET['limit']) ) {
        $array_variables['curr_page'] = intval($_GET['limit']);
        if ( $array_variables['curr_page'] <= 0 ) {
            $array_variables['curr_page'] = 1;
        }
        $array_variables['entry_limit'] = ( $array_variables['curr_page'] - 1 ) * $per_page;
    }
     else {
        $array_variables['entry_limit'] = 0;
        $array_variables['curr_page'] = 1;
    }
    echo '<div class="wrap">';
    
    // Chech order statements
    $acceaptable = ['date DESC, title ASC', 'pub_id ASC', 'pub_id DESC', 'date ASC', 'date DESC', 'title ASC', 'title DESC'];
    $array_variables['order'] = in_array($array_variables['order'], $acceaptable) ? $array_variables['order'] : 'date DESC, title ASC';
    
    // test if teachpress database is up to date
    TP_Admin::database_test();
    
    // Add a bookmark for the publication
    if ( isset( $_GET['add_id'] ) ) {
        TP_Bookmarks::add_bookmark( $_GET['add_id'], $current_user->ID );
    }
    
    // Delete bookmark for the publication
    if ( isset( $_GET['del_id'] ) ) {
        TP_Bookmarks::delete_bookmark( $_GET['del_id'] );
    }
    
    // Add a bookmark for the publication (bulk version)
    if ( $array_variables['action'] === 'add_list' ) {
        TP_Publications_Page::check_nonce_field();
        $max = count( $array_variables['checkbox'] );
        for( $i = 0; $i < $max; $i++ ) {
            $array_variables['checkbox'][$i] = intval($array_variables['checkbox'][$i]);
            $test = TP_Bookmarks::bookmark_exists($array_variables['checkbox'][$i], $current_user->ID);
            if ( $test === false ) {
                TP_Bookmarks::add_bookmark( $array_variables['checkbox'][$i], $current_user->ID );
            }
        }
        get_tp_message( esc_html__('Publications added','teachpress') );
    }
    
    // delete publications - part 2
    if ( isset($_GET['delete_ok']) ) {
        TP_Publications_Page::check_nonce_field();
        TP_Publications::delete_publications($array_variables['checkbox']);
        get_tp_message( esc_html__('Removing successful','teachpress') );
    }
    
    // Bulk edit of publications
    if ( isset($_GET['bulk_edit']) ) {
        TP_Publications_Page::check_nonce_field();
        $mass_edit = ( isset($_GET['mass_edit']) ) ? $_GET['mass_edit'] : '';
        $tags = ( isset($_GET['add_tags']) ) ? TP_Publication_Page::prepare_tags($_GET['add_tags']) : '';
        $delbox = ( isset($_GET['delbox']) ) ? $_GET['delbox'] : array();
        TP_Tags::change_tag_relations($mass_edit, $tags, $delbox);
        get_tp_message( esc_html__('Bulk edit executed','teachpress') );
    }
    
    // Show page
    if ( $array_variables['action'] === 'bibtex' ) {
        TP_Publications_Page::get_bibtex_screen($array_variables);
    }
    else {
        TP_Publications_Page::get_tab($user, $array_variables);
    }
    
    echo '</div>';
}

/**
 * This class contains all functions for the show publications screen
 * @package teachpress\admin\publications
 * @since 5.0.0
 */
class TP_Publications_Page {
    
    /**
     * bibtex mode for show publications page
     * @param array $array_variables
     * @since 5.0.0
     */
    public static function get_bibtex_screen($array_variables) {
        $convert_bibtex = ( get_tp_option('convert_bibtex') == '1' ) ? true : false;
        $sel = '';
        echo '<h2>' . esc_html__('BibTeX','teachpress') . '</h2>';
        echo '<form name="form1">';
        TP_HTML::line( '<p><a href="admin.php?page=' . $array_variables['page'] . '&amp;search=' . $array_variables['search'] . '&amp;limit=' . $array_variables['curr_page'] . '&amp;orderby=' . $array_variables['order'] . '" class="button-secondary">&larr; ' . esc_html__('Back','teachpress') . '</a></p>' );
        
        echo '<textarea name="bibtex_area" rows="20" style="width:90%;" >';

        if ( $array_variables['checkbox'] != '' ) {
            $max = count ($array_variables['checkbox']);
            for ($i=0; $i < $max; $i++) {
                $pub = intval($array_variables['checkbox'][$i]);
                $row = TP_Publications::get_publication( $pub, ARRAY_A );
                $tags = TP_Tags::get_tags( array('output_type' => ARRAY_A, 'pub_id' => $pub) );
                TP_HTML::line( TP_Bibtex::get_single_publication_bibtex($row, $tags, $convert_bibtex) );
                $sel = ( $sel !== '' ) ? $sel . ',' . $pub : $pub;
            }
        }
        else {
            $row = TP_Publications::get_publications( array('output_type' => ARRAY_A) );
            foreach ( $row as $row ) {
                $tags = TP_Tags::get_tags( array('output_type' => ARRAY_A, 'pub_id' => $row['pub_id']) );
                TP_HTML::line( TP_Bibtex::get_single_publication_bibtex($row, $tags, $convert_bibtex) );
            }
        }

        echo '</textarea>';
        echo '</form>';
        echo '<script>
               document.form1.bibtex_area.focus();
               document.form1.bibtex_area.select();
               </script>';
        if ( $sel != '' ) {
            echo '<form id="tp_export" method="get" action="' . home_url() . '">';
            echo '<input type="hidden" name="tp_sel" value="' . esc_html($sel) . '"/>';
            echo '<input type="hidden" name="tp_format" value="bib"/>';
            echo '<input type="hidden" name="type" value="pub"/>';
            echo '<input type="hidden" name="feed" value="tp_export"/>';
            echo '<input type="submit" name="tp_submit" class="button-primary" value="' . esc_html__('Export','teachpress') . ' (.bibtex)"/>';
            echo '</form>';
        }
    }
    
    /**
    * Bulk edit screen for show publications page
    * @param array $array_variables
    * @since 5.0.0
    */
    public static function get_bulk_edit_screen($array_variables) {
        $selected_publications = '';
        $max = count($array_variables['checkbox']);
        for ( $i = 0; $i < $max; $i++ ) {
            $selected_publications = ( $selected_publications === '' ) ? $array_variables['checkbox'][$i] : $selected_publications . ',' . $array_variables['checkbox'][$i];
        }
        echo '<tr class="inline-edit-row" id="tp-inline-edit-row" style="display:table-row;">';
        echo '<td colspan="8" class="colspanchange" style="padding-bottom:7px;">';
        echo '<h4>' . esc_html__('Bulk editing','teachpress') . '</h4>';
        echo '<div id="bulk-titles" style="width:30%; float:left;">';
        echo '<ul>';
        $list = TP_Publications::get_publications( array('include' => $selected_publications, 'output_type' => ARRAY_A) );
        foreach ( $list as $row ) {
            TP_HTML::line( '<li><input type="checkbox" name="mass_edit[]" id="mass_edit_'. intval($row['pub_id']) . '" value="'. $row['pub_id'] . '" checked="checked"/> <label for="mass_edit_'. intval($row['pub_id']) . '">'. $row['title'] . '</label></li>' );
        }
        
        echo '</ul>';
        echo '</div>';
        echo '<div class="tp_mass_edit_right">';
        echo '<p><b>' . esc_html__('Delete current tags','teachpress') . '</b></p>';
        $used_tags = TP_Tags::get_tags( array('pub_id' => $selected_publications, 'output_type' => ARRAY_A, 'group_by' => true) );
        $s = "'";
        echo '<p>';
        foreach ( $used_tags as $row ) {
            $onclick = "teachpress_change_label_color('checkbox_" . intval($row['tag_id']) . "', 'tag_label_" . intval($row['tag_id']) . "')";
            TP_HTML::line( '<input name="delbox[]" type="checkbox" value="' . intval($row['tag_id']) . '" id="checkbox_' . $row['tag_id']. '" onclick="' . $onclick . '"/> <label for="checkbox_' . intval($row['tag_id']) . '" title="Tag &laquo;' . $row['name'] . '&raquo; ' . esc_html__('Delete','teachpress') . '" id="tag_label_' . intval($row['tag_id']) . '">' . $row['name'] . '</label> | ' );
        }
        echo '</p>';
        TP_HTML::line('<p><label for="add_tags"><b>' . esc_html__('New','teachpress') . '</b></label></p>');
        TP_HTML::line('<select name="add_tags[]" id="add_tags" multiple style="width:90%;">');
        $tags = TP_Tags::get_tags( array('group_by' => true, 'output_type'   => ARRAY_A) );
        foreach ($tags as $row) {
            TP_HTML::line('<option value="' . esc_js($row['name']) . '">' . esc_html($row['name']) . '</option>');
        }
        TP_HTML::line('</select>');
        echo '</div>';
        TP_HTML::line( '<p class="submit inline-edit-save"><a accesskey="c" onclick="teachpress_showhide(' . $s . 'tp-inline-edit-row' . $s . ')" class="button-secondary cancel alignleft">' . esc_html__('Cancel') . '</a> <input type="submit" name="bulk_edit" id="bulk_edit" class="button button-primary alignright" value="' . esc_html__('Save') . '" accesskey="s"></p>' );
        echo '</td>';
        echo '</tr>';
        ?>
        <script>
            // SELECT fields
            new SlimSelect({
                select: '#add_tags',
                allowDeselect: true,
                closeOnSelect: false,
                addable: function (value) {
                    // return false or null if you do not want to allow value to be submitted
                    if (value === '') {return false;}

                    // Return the value string
                    return value;

                  }
            });
        </script>
        <?php
    }
    
    /**
     * Gets a single publication row for the main table
     * @param object $row
     * @param array $array_variables
     * @param array $bookmarks
     * @param array $tags
     * @param string $tr_class
     * @param string $get_string
     * @since 5.0.0
     * @access private
     */
    private static function get_publication_row ($row, $array_variables, $bookmarks, $tags, $tr_class, $get_string) {
        TP_HTML::line('<tr ' . $tr_class . '>');
        TP_HTML::line('<td style="font-size:20px; padding-top:8px; padding-bottom:0px; padding-right:0px;">');
        // check if the publication is already in users publication list
        $test2 = false;
        foreach ( $bookmarks as $bookmark ) {
            if ( $bookmark['pub_id'] == $row->pub_id ) {
                $test2 = $bookmark['bookmark_id'];
                break;
            }
        }
        if ( $array_variables['page'] === 'publications.php' ) {
           // Add to your own list icon
           if ( $test2 === false ) {
              TP_HTML::line( '<a href="admin.php?page=' . $array_variables['page'] . '&amp;add_id='. $row->pub_id . $get_string . '" title="' . esc_html__('Add to your own list','teachpress') . '">+</a>' );
           }
        }
        else {
           // Delete from your own list icon
           TP_HTML::line( '<a href="admin.php?page=' . $array_variables['page'] .'&amp;del_id='. $test2 . $get_string . '" title="' . esc_html__('Delete from your own list','teachpress') . '">&laquo;</a>' );
        }
        TP_HTML::line('</td>');
        
        $checked = '';
        if ( ( $array_variables['action'] === "delete" || $array_variables['action'] === "edit" ) && is_array($array_variables['checkbox']) ) { 
            $max = count( $array_variables['checkbox'] );
            for( $k = 0; $k < $max; $k++ ) { 
                if ( $row->pub_id == $array_variables['checkbox'][$k] ) { 
                    $checked = 'checked="checked" ';
                } 
            } 
        }
        TP_HTML::line('<th class="check-column"><input name="checkbox[]" class="tp_checkbox" type="checkbox" ' . $checked . ' value="' . $row->pub_id . '" title="' . esc_html__('Select the entry','teachpress') . '" /></th>');
        TP_HTML::line('<td>');
        TP_HTML::line( '<a href="admin.php?page=teachpress/addpublications.php&amp;pub_id=' . intval($row->pub_id) . '" target="_blank" class="teachpress_link" title="' . esc_html__('Click to edit','teachpress') . '"><strong>' . TP_HTML::prepare_title($row->title, 'decode') . '</strong></a>' );
        if ( $row->status === 'forthcoming' ) {
            echo '<span class="tp_pub_label_status">' . esc_html__('Forthcoming','teachpress') . '</span>';
        }
        TP_HTML::line( '<div class="tp_row_actions"><a href="admin.php?page=teachpress/addpublications.php&amp;pub_id=' . intval($row->pub_id) . '" class="teachpress_link" target="_blank" title="' . esc_html__('Click to edit','teachpress') . '">' . esc_html__('Edit','teachpress') . '</a> | <a href="' . admin_url( 'admin-ajax.php' ) . '?action=teachpress&cite_id=' . intval($row->pub_id) . '" class="teachpress_cite_pub teachpress_link">' . esc_html__('Cite', 'teachpress') . '</a> | <a class="tp_row_delete" href="admin.php?page=' . $array_variables['page'] . '&amp;orderby=' . $array_variables['order'] . '&amp;checkbox%5B%5D=' . intval($row->pub_id) . '&amp;action=delete' . $get_string . '" title="' . esc_html__('Delete','teachpress') . '">' . esc_html__('Delete','teachpress') . '</a></div>' );
        TP_HTML::line('</td>');
        TP_HTML::line('<td>' . intval($row->pub_id) . '</td>');
        TP_HTML::line('<td>' . tp_translate_pub_type($row->type) . '</td>');
        if ( $row->type === 'collection' || ( $row->author === '' && $row->editor !== '' ) ) {
            TP_HTML::line('<td>' . TP_Bibtex::parse_author_simple($row->editor) . ' (' . esc_html__('Ed.','teachpress') . ')</td>');
        }
        else {
            TP_HTML::line('<td>' . TP_Bibtex::parse_author_simple($row->author) . '</td>');
        }
        TP_HTML::line('<td>');
        TP_HTML::line( TP_Publications_Page::get_tags_for_single_row($row->pub_id, $tags, $array_variables) );
        TP_HTML::line('</td>');
        TP_HTML::line('<td>' . $row->year . '</td>');
        TP_HTML::line('</tr>');
        
    }
    
    /**
     * Returns the tags for a publication
     * @param int $pub_id
     * @param array $tags
     * @param array $array_variables
     * @since 5.0.0
     * @access private
     */
    private static function get_tags_for_single_row ($pub_id, $tags, $array_variables) {
        $tag_string = '';
        foreach ($tags as $temp) {
            if ( $temp["pub_id"] != $pub_id ) {
               continue;
            }
            if ( $temp["tag_id"] == $array_variables['tag_id'] ) {
               $tag_string .= '<a href="admin.php?page=' . $array_variables['page']  . '&amp;search=' . $array_variables['search'] . '&amp;type=' . $array_variables['type'] . '&amp;limit=' . $array_variables['curr_page'] . '&amp;tp_year=' . $array_variables['year'] . '&amp;orderby=' . $array_variables['order'] . '" title="' . esc_html__('Delete tag as filter','teachpress') . '"><strong>' . stripslashes($temp["name"]) . '</strong></a>, ';
            }
            else {
               $tag_string .= '<a href="admin.php?page=' . $array_variables['page']  . '&amp;search=' . $array_variables['search'] . '&amp;type=' . $array_variables['type'] . '&amp;tag=' . $temp["tag_id"] . '&amp;tp_year=' . $array_variables['year'] . '&amp;orderby=' . $array_variables['order'] . '" title="' . esc_html__('Show all publications which have a relationship to this tag','teachpress') . '">' . stripslashes($temp["name"]) . '</a>, ';
            }
        }
        return substr($tag_string, 0, -2);
    }
    
    /**
     * Gets the filter box for publication tags
     * @param array $array_variables    An associative array
     * @param int $user                 The ueser ID
     * @since 5.0.0
     * @access private
     */
    private static function get_tag_filter ($array_variables, $user) {
        $array_tags = TP_Tags::get_tags( array(
                        'user'          => ($array_variables['page'] == 'publications.php') ? '' : $user, 
                        'group_by'      => true, 
                        'order'         => 'ASC',
                        'output_type'   => ARRAY_A) );
        TP_HTML::line('<select id="tag_filter" name="tag[]" multiple>');
        TP_HTML::line('<option data-placeholder="true">- ' . esc_html__('All tags','teachpress') . ' -</option>');
        $haystack = ( $array_variables['tag_id'] != '' ) ? explode(',', $array_variables['tag_id'] ): array();
        foreach ( $array_tags as $row ) {
            $selected = ( in_array($row['tag_id'], $haystack) ) ? 'selected="selected"' : '';
            TP_HTML::line('<option value="' . $row['tag_id'] . '" ' . $selected . '>' . $row['name'] . '</option>');
        }      
        TP_HTML::line('</select>');
    }
    
    /**
     * Gets the filter box for publication types
     * @param array $array_variables    An associative array
     * @param int $user                 The user ID
     * @since 5.0.0
     * @access private
     */
    private static function get_type_filter ($array_variables, $user) {
        $array_types = TP_Publications::get_used_pubtypes( array(
             'user' => ($array_variables['page'] == 'publications.php') ? '' : $user ) );
        TP_HTML::line('<select id="type_filter" name="type[]" multiple>');
        TP_HTML::line('<option data-placeholder="true">- ' . esc_html__('All types','teachpress') . ' -</option>');
        $haystack = ( $array_variables['type'] != '' ) ? explode(',', $array_variables['type'] ): array();
        foreach ( $array_types as $row ) {
            $selected = ( in_array($row['type'], $haystack)  ) ? 'selected="selected"' : '';
            TP_HTML::line('<option value="' . $row['type'] . '" ' . $selected . '>' . tp_translate_pub_type($row['type'],'pl') . '</option>');
        }
        TP_HTML::line('</select>');    
    }
    
    /**
     * Gets the filter box for publication years
     * @param array $array_variables    An associative array
     * @param int $user                 The ueser ID
     * @since 5.0.0
     * @access private
     */
    private static function get_year_filter ($array_variables, $user) {
        $array_years = TP_Publications::get_years( array(
            'order'         => 'DESC', 
            'user'          => ($array_variables['page'] == 'publications.php') ? '' : $user,
            'output_type'   => ARRAY_A ) );
        
        TP_HTML::line('<select id="year_filter" name="tp_year[]" multiple>');
        TP_HTML::line('<option data-placeholder="true">- ' . esc_html__('All years','teachpress') . ' -</option>');
        $haystack = ( $array_variables['year'] != '' ) ? explode(',', $array_variables['year'] ): array();
        foreach ( $array_years as $row ) {
            $selected = ( in_array( $row['year'], $haystack) ) ? 'selected="selected"' : '';
            TP_HTML::line('<option value="' . $row['year']. '" ' . $selected . '>' . $row['year'] . '</option>');
        }        
        TP_HTML::line('</select>');
    }
   
    /**
     * Show publications main screen
     * @param int $user
     * @param array $array_variables
     * @since 5.0.0
     */
    public static function get_tab($user, $array_variables) {
        $title = ($array_variables['page'] == 'publications.php' && $array_variables['search'] == '') ? esc_html__('All publications','teachpress') : esc_html__('Your publications','teachpress');
        TP_HTML::line('<h2>' . $title . '<a href="admin.php?page=teachpress/addpublications.php" class="add-new-h2">' . esc_html__('Add new','teachpress') . '</a></h2>');
        TP_HTML::line('<form id="show_publications_form" name="form1" method="get" action="admin.php">');
        TP_HTML::line('<input type="hidden" name="page" id="page" value="' . $array_variables['page'] . '" />');
        TP_HTML::line('<input type="hidden" name="orderby" id="orderby" value="' . $array_variables['order'] . '" />');
        wp_nonce_field( 'verify_teachpress_pub_ui', 'tp_nonce', false, true );

        // Delete publications - part 1
        if ( $array_variables['action'] == "delete" ) {
            TP_HTML::line('<div class="teachpress_message">
                  <p class="teachpress_message_headline">' . esc_html__('Do you want to delete the selected items?','teachpress') . '</p>
                  <p><input name="delete_ok" type="submit" class="button-primary" value="' . esc_html__('Delete','teachpress') . '"/>
                  <a href="admin.php?page=publications.php&search=' . $array_variables['search'] . '&amp;limit=' . $array_variables['curr_page'] . '&amp;orderby=' . $array_variables['order'] . '" class="button-secondary"> ' . esc_html__('Cancel','teachpress') . '</a></p>
                  </div>');
        }
        
        $args = array('search'  => $array_variables['search'],
                      'user'    => ($array_variables['page'] == 'publications.php') ? '' : $user,
                      'tag'     => $array_variables['tag_id'],
                      'year'    => $array_variables['year'],
                      'limit'   => $array_variables['entry_limit'] . ',' .  $array_variables['per_page'],
                      'type'    => $array_variables['type'],
                      'order'   => $array_variables['order']
                     );
        $test = TP_Publications::get_publications($args, true);
        
        // Load tags
        $tags = TP_Tags::get_tags( array('output_type' => ARRAY_A) );
        
        // Load bookmarks
        $bookmarks = TP_Bookmarks::get_bookmarks( array('user'=> $user, 'output_type' => ARRAY_A) );
        
        // Searchbox
        TP_HTML::line('<div id="tp_searchbox">');
        if ( $array_variables['search'] != '' ) { 
              TP_HTML::line( '<a href="admin.php?page=' . $array_variables['page'] . '&amp;type=' . $array_variables['type'] . '&amp;tag=' . $array_variables['tag_id'] . '&amp;tp_year=' . $array_variables['year'] . '&amp;orderby=' . $array_variables['order'] . '" class="tp_search_cancel" title="' . esc_html__('Cancel the search','teachpress') . '">X</a>');
           } 
        TP_HTML::line('<input type="search" name="search" id="pub_search_field" value="' . stripslashes($array_variables['search']) . '"/>');
        TP_HTML::line('<input type="submit" name="pub_search_button" id="pub_search_button" value="' . esc_html__('Search','teachpress') . '" class="button-secondary"/>');
        TP_HTML::div_close('tp_searchbox');
        
        // Actions
        TP_HTML::line('<div class="tablenav" style="padding-bottom:5px;">');
        TP_HTML::div_open('alignleft actions');
        TP_HTML::line('<select name="action">');
        TP_HTML::line('<option value="0">- ' . esc_html__('Bulk actions','teachpress') . ' -</option>');
        TP_HTML::line('<option value="edit">' . esc_html__('Edit','teachpress') . '</option>');
        TP_HTML::line('<option value="bibtex">' . esc_html__('Show as BibTeX entry','teachpress') . '</option>');
        if ( $array_variables['page'] === 'publications.php' ) {
            TP_HTML::line('<option value="add_list">' . esc_html__('Add to your own list','teachpress') . '</option>');
            TP_HTML::line('<option value="delete">' . esc_html__('Delete','teachpress') . '</option>');
        }
        TP_HTML::line('</select>');
        TP_HTML::line('<input name="ok" id="doaction" value="' . esc_html__('OK','teachpress') . '" type="submit" class="button-secondary"/>');
        
        TP_HTML::div_close('alignleft actions');
        
        // Filters
        TP_HTML::div_open('alignleft actions slim-select');
        TP_Publications_Page::get_type_filter($array_variables, $user);
        TP_Publications_Page::get_year_filter($array_variables, $user);
        TP_Publications_Page::get_tag_filter($array_variables, $user);
        TP_HTML::line('<button class="button-secondary" name="filter-ok" type="submit" >' . esc_html__('Limit selection','teachpress') . '</button>');

        TP_HTML::div_close('alignleft actions');
           
        // Page Menu
        $link = 'search=' . $array_variables['search'] . '&amp;type=' . $array_variables['type'] . '&amp;tag=' . $array_variables['tag_id'] . '&amp;tp_year=' . $array_variables['year'] . '&amp;orderby=' . $array_variables['order'];
        tp_page_menu(
            array(  'number_entries'    => $test,
                    'entries_per_page'  => $array_variables['per_page'],
                    'current_page'      => $array_variables['curr_page'],
                    'entry_limit'       => $array_variables['entry_limit'],
                    'page_link'         => 'admin.php?page=' . $array_variables['page'] . '&amp;',
                    'link_attributes'   => $link),
            true
        );
        TP_HTML::div_close('tablenav');
        
        // Publication table
        TP_HTML::line('<table class="widefat">');
        TP_HTML::line('<thead>');
        TP_HTML::line('<tr>');
        TP_HTML::line('<th>&nbsp;</th>');
        TP_HTML::line('<td class="check-column"><input name="tp_check_all" id="tp_check_all" type="checkbox" value="" onclick="teachpress_checkboxes(' . "'checkbox', 'tp_check_all'" . ');" /></td>');
        TP_HTML::line('<th>' . TP_Publications_Page::get_order_link( 'title', esc_html__('Title','teachpress'), $array_variables)  . '</th>');
        TP_HTML::line('<th width="30">' . TP_Publications_Page::get_order_link( 'pub_id', esc_html__('ID'), $array_variables) . '</th>');
        TP_HTML::line('<th>' . esc_html__('Type') . '</th>');
        TP_HTML::line('<th>' . esc_html__('Author(s)','teachpress') . '</th>');
        TP_HTML::line('<th>' . esc_html__('Tags') . '</th>');
        TP_HTML::line('<th>' . esc_html__('Year','teachpress') . '</th>');
        TP_HTML::line('</tr>');
        TP_HTML::line('</thead>');
        TP_HTML::line('<tbody>');
        
        // Bulk edit
        if ( $array_variables['action'] === 'edit' && $array_variables['checkbox'] !== '' ) {
            TP_Publications_Page::get_bulk_edit_screen($array_variables);
        }

        if ( intval($test) === 0 ) {
            TP_HTML::line('<tr><td colspan="8"><strong>' . esc_html__('Sorry, no entries matched your criteria.','teachpress') . '</strong></td></tr>');
        }

        else {
            $row = TP_Publications::get_publications($args);
            $class_alternate = true;
            $get_string = '&amp;search=' . $array_variables['search'] . '&amp;type=' . $array_variables['type'] . '&amp;limit=' . $array_variables['curr_page'] . '&amp;site=' . $array_variables['page'] . '&amp;tag=' . $array_variables['tag_id'] . '&amp;tp_year=' . $array_variables['year'] . '&amp;orderby=' . $array_variables['order'];
            foreach ($row as $row) { 
                if ( $class_alternate === true ) {
                    $tr_class = 'class="alternate"';
                    $class_alternate = false;
                }
                else {
                    $tr_class = '';
                    $class_alternate = true;
                }
                TP_Publications_Page::get_publication_row($row, $array_variables, $bookmarks, $tags, $tr_class, $get_string);
            }
        }
        TP_HTML::line('</tbody>');
        TP_HTML::line('<table>');
        
        TP_HTML::line('<div class="tablenav"><div class="tablenav-pages" style="float:right;">');
        
        if ( $test > $array_variables['per_page'] ) {
            tp_page_menu(
                    array(  'number_entries'    => $test,
                            'entries_per_page'  => $array_variables['per_page'],
                            'current_page'      => $array_variables['curr_page'],
                            'entry_limit'       => $array_variables['entry_limit'],
                            'page_link'         => 'admin.php?page=' . $array_variables['page'] . '&amp;',
                            'link_attributes'   => $link,
                            'mode'              => 'bottom'),
                    true);
        } 
        else {
            if ($test === 1) {
               echo intval($test) . " " . esc_html__('entry','teachpress');
            }
            else {
               echo intval($test) . " " . esc_html__('entries','teachpress');
            }
        }
     
        TP_HTML::line( '</div></div>' );
        
        // print_scripts
        TP_Publications_Page::print_scripts();
        
        TP_HTML::line( '</form>' );
    } 
    
    /**
     * Returns the navigations link for changing the sort order of the table
     * @param string $field     table field
     * @param string $title
     * @param array $array_variables
     */
    private static function get_order_link ($field, $title, $array_variables) {
        // pub_id
        if ( $field === 'pub_id' ) {
            switch ( $array_variables['order'] ) {
                case 'date DESC, title ASC' :
                    $val = 'pub_id ASC';
                    $sim = '';
                    break;
                case 'pub_id ASC':
                    $val = 'pub_id DESC';
                    $sim = '&darr;';
                    break;
                case 'pub_id DESC':
                    $val = 'date DESC, title ASC';
                    $sim = '&uarr;';
                    break;
                default:
                    $val = 'pub_id ASC';
                    $sim = '';
            }
        }
        
        // title
        if ( $field === 'title' ) {
            switch ( $array_variables['order'] ) {
                case 'date DESC, title ASC' :
                    $val = 'title ASC';
                    $sim = '';
                    break;
                case 'title ASC':
                    $val = 'title DESC';
                    $sim = '&darr;';
                    break;
                case 'title DESC':
                    $val = 'date DESC, title ASC';
                    $sim = '&uarr;';
                    break;
                default:
                    $val = 'title ASC';
                    $sim = '';
            }
        }
        
        // set link attributes
        $link = 'search=' . $array_variables['search'] . '&amp;type=' . $array_variables['type'] . '&amp;tag=' . $array_variables['tag_id'] . '&amp;tp_year=' . $array_variables['year'] . '&amp;orderby=' . $val;
        
        // return link
        return '<a href="admin.php?page=' . $array_variables['page'] . '&amp;=1&amp;' . $link . '" title="' . esc_html__('Change sort order','teachpress') . '">' . $title . ' </a>' . $sim . '</span>';
    }
    
    /**
     * Checks the nonce field of the form. If the check fails wp_die() will be executed
     * @since 9.0.5
     */
    public static function check_nonce_field () {
        if ( ! isset( $_GET['tp_nonce'] ) 
            || ! wp_verify_nonce( $_GET['tp_nonce'], 'verify_teachpress_pub_ui' ) 
        ) {
           wp_die('teachPress error: This request could not be verified!');
           exit;
        }
    }
    
    /**
     * Prints the js scripts
     * @since 6.0.0
     */
    public static function print_scripts () {
        ?>
        <script>
            // SELECT fields
            new SlimSelect({
                select: '#type_filter',
                allowDeselect: true,
                closeOnSelect: false
            });
            new SlimSelect({
                select: '#year_filter',
                allowDeselect: true,
                closeOnSelect: false
            });
            new SlimSelect({
                select: '#tag_filter',
                allowDeselect: true,
                closeOnSelect: false
            });
        </script>
        <script>
            // Cite methods
            jQuery(document).ready(function($){
                // Start cite publication window
                $(".teachpress_cite_pub").each(function() {
                    var $link = $(this);
                    var $dialog = $('<div></div>')
                        .load($link.attr('href') + ' .content')
                        .dialog({
                                autoOpen: false,
                                title: '<?php esc_html_e('Cite publication','teachpress'); ?>',
                                width: 600
                        });
                        
                    $link.click(function() {
                        $dialog.dialog('open');
                        $('.tp_cite_full').focus();
                        $('.tp_cite_full').select();
                        return false;
                    });
                    
                });
                
                // bibtex button in the cite publication window 
                $("body").on('click','.tp_cite_bibtex', function() {
                    var pub_id = $(this).attr("pub_id");
                    $.get("<?php echo admin_url( 'admin-ajax.php' ) ;?>?action=teachpress&cite_pub=" + pub_id + "&cite_type=bibtex", 
                    function(text){
                        $("#tp_cite_full_" + pub_id).text(text);
                        $("#tp_cite_full_" + pub_id).select();
                        $("#tp_cite_bibtex_" + pub_id).addClass("nav-tab-active");
                        $("#tp_cite_text_" + pub_id).removeClass("nav-tab-active");
                    });
                });
                
                // text button in the cite publication window 
                $("body").on('click','.tp_cite_text',function() {
                    var pub_id = $(this).attr("pub_id");
                    $.get("<?php echo admin_url( 'admin-ajax.php' ) ;?>?action=teachpress&cite_pub=" + pub_id + "&cite_type=text", 
                    function(text){
                        $("#tp_cite_full_" + pub_id).text(text);
                        $("#tp_cite_full_" + pub_id).select();
                        $("#tp_cite_text_" + pub_id).addClass("nav-tab-active");
                        $("#tp_cite_bibtex_" + pub_id).removeClass("nav-tab-active");
                    });
                });
            });
        </script>
        <?php
    }
    
}