Source Code for /public/source-viewer.php

<?php
/**
 * Renders a source code viewer for a given file.
 */

// 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();

// If they want to download the file, do that:
if( isset( $_GET['download'] ) ) {
  header('Content-Disposition: attachment; filename="' . basename( $file_path ) . '"');
  header('Content-Type: text/plain');
  echo file_get_contents( $file_path );
  die();
}

// If the file is an image in the public directory, redirect to it:
if( in_array( strtolower( pathinfo( $file_path, PATHINFO_EXTENSION ) ), [ 'svg', 'jpg', 'jpeg', 'png', 'gif', 'webp' ] ) ) {
  $public_root = realpath( __DIR__);
  $file_path = str_replace( $public_root, '', $file_path );
  header('Location: ' . $file_path);
  die();
}

// Load the source code highlighter library and configure it:
require('vendor/autoload.php');
$hl = new \Highlight\Highlighter();
$hl->setAutodetectLanguages(array('php', 'html', 'css', 'javascript', 'json', 'markdown', 'text'));

// Load the file they want to see the source code for:
$code = file_get_contents( $file_path );

// Choose a stylesheet for source code highlighting:
$available_stylesheets = \HighlightUtilities\getAvailableStyleSheets();
$stylesheet = 'default';
if( isset( $_GET['stylesheet'] ) && in_array( $_GET['stylesheet'], $available_stylesheets ) ) {
  $stylesheet = $_GET['stylesheet'];
}

// Get a short name (relative to the application root) for the file:
$short_file_path = str_replace( realpath( __DIR__ . '/../' ), '', $file_path );

// Highlight the code:
$highlighted = $hl->highlightAuto( $code );

// Output the code:
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Source Code for <?php echo $short_file_path; ?></title>
  <style>
    <?php
    echo \HighlightUtilities\getStyleSheet($stylesheet);
    ?>
  </style>
</head>
<body>
  <h1>Source Code for <?php echo $short_file_path; ?></h1>
  <pre><code class="hljs <?php echo $highlighted->language; ?>"><?php echo $highlighted->value; ?></code></pre>
  
  <?php add_backlink(); ?>
</body>
</html>