Source Code for /public/demo-harness.php

<?php
/**
 * Renders a demo file but wrapped in a full HTML page.
 */

 // Use our convenience function to get the path to the requested file without permitting access to files outside of this application:
require('inc/functions.php');
$file_path = get_requested_file();
$relative_file_path = str_replace(__DIR__ . '/../', '', $file_path);

// Don't allow the demo harness to be used to render the demo harness! (Recursion is fun!)
if( $file_path === __FILE__ ) {
  header('HTTP/1.1 403 Forbidden');
  die('Forbidden');
}

$css_files = [];

// Check the $_GET['demo_in_full_page'] parameter to see if if might be a CSS file to link to
if( isset( $_GET['demo_in_full_page'] ) && str_ends_with( $_GET['demo_in_full_page'], '.css' ) ) {
  $override_css_file = '/' . $_GET['demo_in_full_page'];
  if( file_exists( sanitize_file_path( __DIR__ . $override_css_file ) ) ) {
    $css_files[] = $override_css_file;
  }
}

// Determine whether the file we're viewing has an associated CSS file.
$associated_css_file = get_associated_css_file( $file_path );
if( $associated_css_file ) {
  $css_files[] = $associated_css_file;
}
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Demo Harness for <?php echo htmlspecialchars($_GET['file']); ?></title>
  <?php foreach( $css_files as $css_file ) { ?>
    <link rel="stylesheet" href="<?php echo $css_file; ?>">
  <?php } ?>
</head>
<body>
  <main>
    <?php
    chdir( dirname( $file_path ) ); // 👈 Change to the directory of the file we're viewing so that relative includes work correctly
    include($file_path);
    ?>
  </main>

  <aside style="margin-top: 2em; padding-top: 2em; border-top: 1px solid #ccc;">
    🧑‍💻 <a href="/source-viewer.php?file=<?php echo $relative_file_path; ?>">View the source code for this page?</a>
    <?php if( ! empty( $css_files ) ) { ?>
      <br>
      💡 This example includes
      <?php if (count( $css_files ) > 1) { ?>
        <?php echo count( $css_files ) ?> CSS files:
        <?php
          $css_files_html = array_map( function( $css_file ) {
            return '<a href="/source-viewer.php?file=public/' . $css_file . '">' . basename( $css_file ) . '</a>';
          }, $css_files );
          echo implode( ', ', $css_files_html );
        ?>
      <?php } else { ?>
        <a href="/source-viewer.php?file=public/<?php echo $css_files[0]; ?>">a CSS file</a>.
      <?php } ?>
    <?php } ?>

    <?php add_backlink(); ?>
  </aside>
</body>
</html>