README documented ErrorHandler.php as a "global error/exception
handler", but ErrorHandler::init() had exactly one caller app-wide
(api/get_template.php). 13 endpoints never called
ini_set('display_errors', 0) at all, relying on the server's global
php.ini default, and index.php never registered any handler — a
genuine PHP fatal during a page render fell through to PHP's raw
default handling with no app-level 500 response, styled or otherwise.
Investigating the "13 endpoints" claim turned up that 9 of them
(assign_ticket.php, audit_log.php, check_duplicates.php,
get_comments.php, get_users.php, notifications.php, saved_filters.php,
user_preferences.php, watch_ticket.php) already require
api/bootstrap.php as their first statement, which itself calls
ini_set('display_errors', 0) — so they were never actually exposed;
the static grep just couldn't see through the require. The 3 that
were genuinely unprotected (bulk_operation.php, download_attachment.php,
health.php) are fixed here. ticket_dependencies.php already has its
own complete hand-rolled equivalent (shutdown handler, error handler,
exception handler, output-buffer aware) and was deliberately left
alone rather than risk double-registering handlers.
Rather than duplicate the fix 30+ times, wired ErrorHandler::init()
directly into api/bootstrap.php (covering all 9 files above at once)
and into each of the other endpoints' own ini_set/error_reporting
pair, replacing it in place — additive only: existing try/catch blocks
in every endpoint still handle what they already handled identically,
this only adds a safety net for genuinely uncaught fatals that fell
through everything else. Before doing this app-wide, removed
ErrorHandler::init()'s override of PHP's 'error_log' ini setting: it
redirected every error_log() call in the request to a fixed /tmp file,
which would have silently diverted logs away from wherever the server
is actually configured to send them the moment this got wired into
more than one endpoint. That override only existed to support
getRecentErrors(), which has zero callers app-wide.
For index.php (page views, not JSON), added an 'html' response mode to
ErrorHandler that renders a new views/error_500.php instead of a JSON
body. That view is deliberately self-contained (no layout_header.php,
no $GLOBALS/session/DB dependency) since a genuine fatal can happen
before config.php finishes loading or mid-session-start.
Verified: a real uncaught error with no prior output correctly
produces a clean JSON 500 (API mode) or the styled HTML page (page
mode) to the client while the full stack trace goes to error_log, not
the response; normal (non-fatal) requests through both a
bootstrap.php-based endpoint and index.php are byte-for-byte
unaffected. Full project phpcs pass is clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lhz7pGMaoTfL5sdYS5XiKv
181 lines
5.5 KiB
PHP
181 lines
5.5 KiB
PHP
<?php
|
|
|
|
/**
|
|
* User Avatar API
|
|
*
|
|
* Serves profile pictures fetched from lldap via LDAP.
|
|
* Caches images locally to avoid repeated LDAP queries.
|
|
*
|
|
* GET /api/user_avatar.php?user_id=123
|
|
* Returns the user's JPEG avatar (from cache or LDAP).
|
|
* Returns 404 if the user has no avatar set in lldap.
|
|
*/
|
|
|
|
require_once dirname(__DIR__) . '/helpers/ErrorHandler.php';
|
|
ErrorHandler::init();
|
|
|
|
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
|
|
RateLimitMiddleware::apply('api');
|
|
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
require_once dirname(__DIR__) . '/config/config.php';
|
|
require_once dirname(__DIR__) . '/helpers/Database.php';
|
|
|
|
// Must be authenticated
|
|
if (!isset($_SESSION['user']['user_id'])) {
|
|
http_response_code(401);
|
|
exit;
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
|
|
http_response_code(405);
|
|
exit;
|
|
}
|
|
|
|
$cfg = $GLOBALS['config'];
|
|
|
|
// Validate user_id parameter
|
|
$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
|
|
if ($userId <= 0) {
|
|
http_response_code(400);
|
|
exit;
|
|
}
|
|
|
|
// Ensure LDAP is enabled and extension is loaded
|
|
if (!$cfg['LDAP_ENABLED'] || !extension_loaded('ldap')) {
|
|
http_response_code(404);
|
|
exit;
|
|
}
|
|
|
|
// Ensure avatar cache directory exists
|
|
$cacheDir = rtrim($cfg['AVATAR_CACHE_DIR'], '/');
|
|
if (!is_dir($cacheDir)) {
|
|
mkdir($cacheDir, 0755, true);
|
|
}
|
|
|
|
// Build cache paths from the validated integer $userId — no user-supplied strings used
|
|
$safeUserId = (int)$userId; // nosemgrep: php.lang.security.injection.tainted-filename.tainted-filename
|
|
$cacheFile = $cacheDir . '/user_' . $safeUserId . '.jpg';
|
|
$noAvatarSentinel = $cacheDir . '/user_' . $safeUserId . '.none';
|
|
$cacheTtl = (int)($cfg['AVATAR_CACHE_TTL'] ?? 3600);
|
|
|
|
// Serve from cache if fresh
|
|
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTtl) {
|
|
header('Content-Type: image/jpeg');
|
|
header('Cache-Control: private, max-age=' . $cacheTtl);
|
|
header('X-Avatar-Source: cache');
|
|
readfile($cacheFile);
|
|
exit;
|
|
}
|
|
|
|
// A sentinel empty file means "no avatar" — don't re-query LDAP until TTL expires
|
|
if (file_exists($noAvatarSentinel) && (time() - filemtime($noAvatarSentinel)) < $cacheTtl) {
|
|
http_response_code(404);
|
|
exit;
|
|
}
|
|
|
|
// Look up username from DB
|
|
try {
|
|
$conn = Database::getConnection();
|
|
$stmt = $conn->prepare("SELECT username FROM users WHERE user_id = ? LIMIT 1");
|
|
$stmt->bind_param('i', $userId);
|
|
$stmt->execute();
|
|
$result = $stmt->get_result();
|
|
$row = $result->fetch_assoc();
|
|
$stmt->close();
|
|
|
|
if (!$row || empty($row['username'])) {
|
|
http_response_code(404);
|
|
exit;
|
|
}
|
|
$username = $row['username'];
|
|
} catch (Exception $e) {
|
|
error_log("user_avatar: DB error for user_id=$userId: " . $e->getMessage());
|
|
http_response_code(500);
|
|
exit;
|
|
}
|
|
|
|
// Query lldap via LDAP
|
|
$ldapHost = $cfg['LDAP_HOST'];
|
|
$ldapPort = $cfg['LDAP_PORT'];
|
|
$bindDn = $cfg['LDAP_BIND_DN'];
|
|
$bindPw = $cfg['LDAP_BIND_PW'];
|
|
$userBase = $cfg['LDAP_USER_BASE'];
|
|
|
|
// Escape username for LDAP filter (RFC 4515)
|
|
$safeUsername = ldap_escape($username, '', LDAP_ESCAPE_FILTER);
|
|
$filter = "(uid=$safeUsername)";
|
|
|
|
$avatarData = null;
|
|
$ldapQueryOk = false; // true only if the LDAP lookup completed without error
|
|
|
|
try {
|
|
$ldap = @ldap_connect("ldap://$ldapHost:$ldapPort");
|
|
if (!$ldap) {
|
|
throw new RuntimeException("ldap_connect failed");
|
|
}
|
|
|
|
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
|
|
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
|
|
ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, 3);
|
|
ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, 3);
|
|
|
|
if (!@ldap_bind($ldap, $bindDn, $bindPw)) {
|
|
throw new RuntimeException("LDAP bind failed: " . ldap_error($ldap));
|
|
}
|
|
|
|
$search = @ldap_search($ldap, $userBase, $filter, ['avatar'], 0, 1, 3);
|
|
if (!$search) {
|
|
throw new RuntimeException("LDAP search failed: " . ldap_error($ldap));
|
|
}
|
|
|
|
$entries = ldap_get_entries($ldap, $search);
|
|
if ($entries['count'] > 0 && !empty($entries[0]['avatar'][0])) {
|
|
// ldap_get_entries() returns the attribute value as raw binary.
|
|
$avatarData = $entries[0]['avatar'][0];
|
|
}
|
|
|
|
// The query ran to completion — any "no avatar" result is authoritative.
|
|
$ldapQueryOk = true;
|
|
|
|
ldap_unbind($ldap);
|
|
} catch (Exception $e) {
|
|
error_log("user_avatar: LDAP error for username=$username: " . $e->getMessage());
|
|
// Transient LDAP failure: do NOT poison the negative cache. Fall through to
|
|
// a plain 404 so the avatar is retried on the next request once LDAP recovers.
|
|
}
|
|
|
|
if ($avatarData === null || strlen($avatarData) < 100) {
|
|
// Only cache "no avatar" when LDAP actually answered. On an error/timeout we
|
|
// leave no sentinel, so the lookup is retried instead of being stuck for the TTL.
|
|
if ($ldapQueryOk) {
|
|
file_put_contents($noAvatarSentinel, '');
|
|
}
|
|
http_response_code(404);
|
|
exit;
|
|
}
|
|
|
|
// Validate it's actually a JPEG (magic bytes FF D8 FF). A successful LDAP read of
|
|
// non-JPEG data is a genuine "no usable avatar", so the sentinel is appropriate here.
|
|
if (substr($avatarData, 0, 3) !== "\xFF\xD8\xFF") {
|
|
error_log("user_avatar: non-JPEG data for username=$username");
|
|
file_put_contents($noAvatarSentinel, '');
|
|
http_response_code(404);
|
|
exit;
|
|
}
|
|
|
|
// Cache to disk
|
|
file_put_contents($cacheFile, $avatarData);
|
|
// Remove stale sentinel if present
|
|
if (file_exists($noAvatarSentinel)) {
|
|
unlink($noAvatarSentinel);
|
|
}
|
|
|
|
header('Content-Type: image/jpeg');
|
|
header('Cache-Control: private, max-age=' . $cacheTtl);
|
|
header('X-Avatar-Source: ldap');
|
|
echo $avatarData;
|