Your IP : 216.73.217.117


Current Path : /var/www/cesa.co.za/php/includes/
Upload File :
Current File : /var/www/cesa.co.za/php/includes/BceAssignmentFeedbackFormsReportService.php

<?php

/**
 * BCE assignment / module feedback form reports via cesa-v3 external API.
 */
class BceAssignmentFeedbackFormsReportService
{
    /**
     * @return string
     */
    public function getV3BaseUrl()
    {
        $baseUrl = getenv('CESA_V3_API_BASE_URL');
        if (!$baseUrl || strlen(trim($baseUrl)) <= 0) {
            $baseUrl = getenv('CESA_V3_BASE_URL');
        }
        if (!$baseUrl || strlen(trim($baseUrl)) <= 0) {
            $baseUrl = 'https://v3.cesa.co.za';
        }

        if (isset($_SERVER['HTTP_HOST']) && strpos((string) $_SERVER['HTTP_HOST'], 'devstage') !== false) {
            $baseUrl = 'https://cesa-v3.devstage.co.za';
        }

        return rtrim($baseUrl, '/');
    }

    /**
     * @param string $url
     * @param string $error
     * @param int $timeoutSeconds
     * @return array|null
     */
    public function getJsonFromV3($url, &$error, $timeoutSeconds = 30)
    {
        $error = '';

        if (!class_exists('Utils')) {
            include_once $_SERVER['DOCUMENT_ROOT'] . '/php/includes/Utils.php';
        }

        $result = Utils::curlRequest(
            $url,
            'GET',
            null,
            array('Accept: application/json'),
            10,
            intval($timeoutSeconds)
        );

        $httpCode = intval($result['http_code']);
        $rawResponse = (string) $result['response'];

        if ($result['error'] !== '') {
            $error = 'Connection failed: ' . $result['error'];
            return null;
        }

        if ($rawResponse === '') {
            $error = 'Empty response from V3 API (HTTP ' . $httpCode . ').';
            return null;
        }

        $response = json_decode($rawResponse, true);
        if (!is_array($response)) {
            $snippet = preg_replace('/\s+/', ' ', substr(strip_tags($rawResponse), 0, 200));
            $error = 'Invalid response from V3 API (HTTP ' . $httpCode . ').';
            if ($snippet !== '') {
                $error .= ' ' . $snippet;
            }
            return null;
        }

        if ($httpCode < 200 || $httpCode >= 300 || (isset($response['success']) && !$response['success'])) {
            $error = isset($response['error']) ? trim((string) $response['error']) : '';
            if ($error === '') {
                $error = 'API request failed with HTTP ' . $httpCode;
            }
            return null;
        }

        return $response;
    }

    /**
     * @param string $error
     * @return array
     */
    public function listForms(&$error)
    {
        $error = '';
        $response = $this->getJsonFromV3($this->getV3BaseUrl() . '/api/external/forms/reports', $error);
        if (!is_array($response) || !isset($response['forms']) || !is_array($response['forms'])) {
            if ($error === '') {
                $error = 'Could not load feedback forms list.';
            }
            return array();
        }

        return $response['forms'];
    }

    /**
     * @param string $formId
     * @param string $error
     * @return string
     */
    public function getReportHtml($formId, &$error)
    {
        $error = '';
        $formId = trim((string) $formId);
        if ($formId === '') {
            $error = 'No form selected.';
            return '';
        }

        $response = $this->getJsonFromV3(
            $this->getV3BaseUrl() . '/api/external/forms/' . rawurlencode($formId) . '/report',
            $error,
            120
        );

        if (!is_array($response) || !isset($response['report_html'])) {
            if ($error === '') {
                $error = 'Could not load selected feedback report.';
            }
            return '';
        }

        return (string) $response['report_html'];
    }

    /**
     * @param string $url
     * @param string $error
     * @return array|null keys body, filename
     */
    public function getBinaryExportFromV3($url, &$error)
    {
        $error = '';
        $responseHeaders = '';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/json;q=0.9, */*;q=0.8',
        ));
        curl_setopt(
            $ch,
            CURLOPT_HEADERFUNCTION,
            static function ($ch, $headerLine) use (&$responseHeaders) {
                $responseHeaders .= $headerLine;
                return strlen($headerLine);
            }
        );
        $rawResponse = curl_exec($ch);
        if ($rawResponse === false) {
            $error = 'Connection failed: ' . curl_error($ch);
            curl_close($ch);
            return null;
        }

        $httpCode = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
        $contentType = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        curl_close($ch);

        if ($httpCode < 200 || $httpCode >= 300) {
            $decoded = json_decode($rawResponse, true);
            if (is_array($decoded) && isset($decoded['error'])) {
                $error = (string) $decoded['error'];
            } else {
                $error = 'Export failed with HTTP ' . $httpCode;
            }
            return null;
        }

        if (stripos($contentType, 'json') !== false) {
            $decoded = json_decode($rawResponse, true);
            $error = (is_array($decoded) && isset($decoded['error']))
                ? (string) $decoded['error']
                : 'Unexpected JSON response from export API.';
            return null;
        }

        if (strlen($rawResponse) < 4 || substr($rawResponse, 0, 2) !== 'PK') {
            $error = 'Invalid spreadsheet response from V3.';
            return null;
        }

        $filename = 'form-report.xlsx';
        if (preg_match('/^Content-Disposition:\\s*[^\\n]*filename\\*=UTF-8\'\'(.+)$/im', $responseHeaders, $m)) {
            $filename = rawurldecode(trim(rtrim($m[1], "\r\n"), " \t\""));
        } elseif (preg_match('/^Content-Disposition:\\s*[^\\n]*filename="([^"]+)"/im', $responseHeaders, $m)) {
            $filename = $m[1];
        }

        return array('body' => $rawResponse, 'filename' => $filename);
    }

    /**
     * @param string $formId
     * @param string $error
     * @return array|null
     */
    public function exportSpreadsheet($formId, &$error)
    {
        $formId = trim((string) $formId);
        if ($formId === '') {
            $error = 'Missing form_id.';
            return null;
        }

        $exportUrl = $this->getV3BaseUrl() . '/api/external/forms/' . rawurlencode($formId) . '/report/export.xlsx';

        return $this->getBinaryExportFromV3($exportUrl, $error);
    }
}