bonny / WordPress-Simple-History

🔍🕵️‍♀️ WordPress audit log that track user changes in WordPress admin using a nice activity feed.
https://simple-history.com
310 stars 70 forks source link

Show log on front end using block or shortcode #341

Open bonny opened 1 year ago

bonny commented 1 year ago

Over the years mulitple people have requested this feature so perhaps it's something to consider.

Related support threads:

Things to consider and challenges:

1ucay commented 1 year ago

Hello, I can provide my code for this

<?php if ( class_exists( 'SimpleHistoryLogQuery' ) ): 

use Simple_History\Helpers;
function example_get_log_row_plain_text_output( $row ) {

    $context = $row->context;
    $post_id = isset( $context['post_id'] ) ? $context['post_id'] : 0;

    // Default to original log message.
    $message = $row->message;

    // Check if post still is available.
    // It will return a WP_Post Object if post still is in system.
    // If post is deleted from trash (not just moved there), then null is returned.
    $post = get_post( $post_id );

    $post_is_available = is_a( $post, 'WP_Post' );

    $message_key = isset( $context['_message_key'] ) ? $context['_message_key'] : null;

    // Try to get singular name.
    $post_type = isset( $context['post_type'] ) ? $context['post_type'] : '';
    $post_type_obj = get_post_type_object( $post_type );
    if ( ! is_null( $post_type_obj ) ) {

        if ( ! empty( $post_type_obj->labels->singular_name ) ) {
            $context['post_type'] = strtolower( $post_type_obj->labels->singular_name );
        }
    }

    if ( $context['post_type'] === 'post' )
        $context['post_type'] = 'news';

    $context['permalink'] = get_permalink( $post_id );

    // If post is not available any longer then we can't link to it, so keep plain message then.
    // Also keep plain format if user is not allowed to edit post (edit link is empty).
    if ( $post_is_available && $context['permalink'] ) {

        if ( 'post_updated' == $message_key ) {

            $message = __( 'Updated {post_type} <a href="{permalink}">"{post_title}"</a>', 'simple-history' );

        } elseif ( 'post_deleted' == $message_key ) {

            $message = __( 'Deleted {post_type} "{post_title}"', 'simple-history' );

        } elseif ( 'post_created' == $message_key ) {

            $message = __( 'Created {post_type} <a href="{permalink}">"{post_title}"</a>', 'simple-history' );

        } elseif ( 'post_trashed' == $message_key ) {

            // While in trash we can still get actions to delete or restore if we follow the edit link.
            $message = __( 'Moved {post_type} <a href="{permalink}">"{post_title}"</a> to the trash', 'simple-history' );

        }
    } // End if().

    $context['post_type'] = isset( $context['post_type'] ) ? esc_html( $context['post_type'] ) : '';
    $context['post_title'] = isset( $context['post_title'] ) ? esc_html( $context['post_title'] ) : '';

    return helpers::interpolate( $message, $context, $row );
}

    ?>
<div class="header-activity has-sub-menu has-sub-menu--large">

    <svg class="icon icon-globe lazyload" aria-hidden="true" role="img"><use xlink:href="#icon-globe"></use></svg>

    <div class="sub-menu">
        <span class="sub-menu-arrow"></span>
        <div class="sub-menu-scroll-wrapper">
            <div class="sub-menu-scroll">
                <ul class="list-bare">
                <?php

                add_filter( 'simple_history/log_query_inner_where', function( $where ) {
                    global $wpdb;

                    /*
                    $where .= sprintf(
                        '
                        AND id IN ( SELECT history_id FROM %1$s AS c WHERE c.key = "_user_id" AND c.value != "%2$s" )
                        ', $wpdb->prefix . 'simple_history_contexts', 1
                    );
                    */

                    $where .= sprintf(
                        '
                        AND id IN ( SELECT history_id FROM %1$s AS c WHERE c.key = "post_type" AND c.value IN ("%2$s") )
                        ', $wpdb->prefix . 'simple_history_contexts', implode( '","', array( 'post', 'page', 'event', 'guideline' ) )
                    );

                    return $where;
                } );

                add_filter( 'simple_history/loggers_user_can_read/can_read_single_logger', function( $user_can_read_logger, $one_logger, $user_id ) {

                    if ( isset( $one_logger->slug ) && $one_logger->slug === 'SimplePostLogger' )
                        return true;

                    return $user_can_read_logger;
                }, 10, 3 );

                $logger_query = new SimpleHistoryLogQuery();

                $logger_query_args = array(
                    //'type'                    => 'occasions',
                    'paged'                   => 1,
                    'posts_per_page'          => 80,
                    'loggers'                 => 'SimplePostLogger',
                    'occasionsCountMaxReturn' => 1,
                    'messages'                => array(
                        'SimplePostLogger:post_updated,SimplePostLogger:post_created'
                    )
                );

                $events = $logger_query->query( $logger_query_args );
                //print_r( $events );
                $unique = array();
                $total_events = 0;
                if ( !empty( $events["log_rows"] ) ):
                foreach ( $events["log_rows"] as $row ):

                    if ( $total_events > 9 )
                        break;

                    $date = date( 'Y-m-d' , strtotime( $row->date ) );
                    $post_id = ( isset( $row->context['post_id'] ) ) ? $row->context['post_id'] : 0;

                    if ( get_post_type( $post_id ) === 'acf-field-group' )
                        continue;

                    /*
                    if ( !get_post_status( $post_id ) )
                        continue;
                    */

                    if ( get_post_status( $post_id ) !== 'publish' )
                        continue;

                    $md5 = md5( $date . $post_id );

                    if ( !isset( $unique[$md5] ) ): $total_events++; ?>
                        <li class="sub-menu-item id-<?php echo $post_id; ?> sub-menu-item-<?php echo $row->id; ?>">

                            <time class="sub-menu-item-note" datetime="<?php echo date_i18n( 'c', strtotime( $row->date ) ); ?>" content="<?php echo date_i18n( 'c', strtotime( $row->date ) ); ?>" itemprop="datePublished">
                                <?php echo date_i18n( 'j. F Y', strtotime( $row->date ) ); ?>
                            </time>
                            <div class="sub-menu-item-context" itemprop="description">

                                <?php /*if ( $row->initiator === 'wp_user' ): ?>
                                <a href="<?php echo get_author_posts_url( $row->context['_user_id'] ); ?>" class="author"><?php the_author_meta( 'display_name', $row->context['_user_id'] ); ?></a>
                                <?php endif;*/ ?>

                                <?php echo example_get_log_row_plain_text_output( $row ); ?>
                            </div>
                        </li>
                    <?php endif;

                    $unique[$md5] = true;

                endforeach; else: ?>
                <li class="sub-menu-item"><?php _e( 'There are no activity.', 'example' ); ?></li>
                <?php   endif; ?>

                </ul>
            </div>
        </div>
    </div>
    <div class="header-activity-count"><?php echo $total_events; ?></div>
</div>
<?php endif; ?>
1ucay commented 1 month ago

Hello,

do we have filter "simple_history/log_query_inner_where" ? I think it is not working now.

Thank you.

bonny commented 1 month ago

Hello,

do we have filter "simple_history/log_query_inner_where" ? I think it is not working now.

Thank you.

Ah, no you are correct, it probably went missing after a big rewrite to support full group by https://github.com/bonny/WordPress-Simple-History/issues/409

I'll add another issue about this and see if I can bring it back.

1ucay commented 1 month ago

Thank you for your great work!!

bonny commented 1 month ago

@1ucay the next version will have a new filter to replace the filter that went missing. See here for more info: https://github.com/bonny/WordPress-Simple-History/issues/455