HEX
Server: Apache
System: Linux www3.pit.tblive.com 5.14.0-687.38.1.el9_8.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Aug 12 17:19:12 EDT 2026 x86_64
User: awaldron (1020)
PHP: 8.1.34
Disabled: exec,passthru,shell_exec,system
Upload Files
File: /home/awaldron/_domains/api.pennhillscdc.org/v1/_globals.php
<?php

//**********************************************************************************************************//
// DATABASE FUNCTIONS **************************************************************************************//

function dbconnect() {
    // LOCALHOST
    if ($_SERVER['HTTP_HOST'] == 'localhost:8888') {
        $db = new mysqli('localhost', 'root', 'root', 'phcdc_members');
    }
    // PRODUCTION
    else if ($_SERVER['HTTP_HOST'] == 'api.pennhillscdc.org') {
        $db = new mysqli('localhost', 'awaldron_phcdc', 'R0+Igmj#YKwG', 'awaldron_phcdc_members');
    }

    if ($db->connect_errno) {
        response( 500, ['success' => false, 'errors' => ['Error connecting to the database.']]);
    }
    return $db;
}


//**********************************************************************************************************//
// CORS FUNCTIONS ******************************************************************************************//

function cors() {

    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day

    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }
}




//**********************************************************************************************************//
// API FUNCTIONS *******************************************************************************************//

function validate_body( $args, $rules ) {

    $valid = true;
    $errors = [];

    if ($args !== false && $rules !== false) {
        foreach ($rules as $param => $rule) {
            // CHECK REQUIRED
            if (strstr($rule,'req')) {
                if (empty($args[$param])) {
                    $valid = false;
                    $errors[] = $param.' is required.';
                }
            }
            // CHECK EMAIL
            if (strstr($rule,'email')) {
                if (!filter_var($args[$param], FILTER_VALIDATE_EMAIL)) {
                    $valid = false;
                    $errors[] = $param.' is not a valid email address.';
                }
            }
        }
    }

    if (!$valid) {
        response( 400, ['success'=>false,'errors'=>$errors]);
    }
    return true;
}

function validate_token( $uid ) {
    // IF uid==0 THEN THROW ERROR INVALID TOKEN
    if ($uid !== false && $uid === 0) {
        response( 401, ['success'=>false,'errors'=>['Security token invalid.'.$_SERVER['HTTP_AUTHORIZATION']]]);
    }
}

function validate_admin( $is_admin ) {
    // IF is_admin==0 THEN THROW ERROR NOT AUTHORIZED
    if (!$is_admin) {
        response( 401, ['success'=>false,'errors'=>['Unauthorized. User must be an admin.']]);
    }
}

function utf8ize($d) {
    if (is_array($d)) {
        foreach ($d as $k => $v) {
            $d[$k] = utf8ize($v);
        }
    } else if (is_string ($d)) {
        return utf8_encode($d);
    }
    return $d;
}


function response( $responseCode=200, $responseBody=[] ) {
    http_response_code($responseCode);
    header('Content-Type: application/json');
    echo json_encode(utf8ize($responseBody));
    exit;
}


function new_token( $db, $uid ) {
    $token = bin2hex(random_bytes(64));
    $created = time();
    $expires = time() + 60*60*12;
    $ins = "INSERT INTO tokens 
            (user_id, token, created, expires) VALUES 
            (".$uid.",'".$token."',".$created.",".$expires.")";
    if ($result = $db->query($ins)) {
        return [
            'token' => $token,
            'created' => $created,
            'expires' => $expires
        ];
    } else {
        response( 400, ['success'=>false,'errors'=>['Error creating token.']]);
    }
}

function check_token( $db, $token ) {
    $sql = "SELECT token_id, user_id FROM tokens WHERE token='".$token."' AND expires > ".time();
    $res = qRow( $db, $sql );
    if (!empty($res['user_id'])) {
        // UPDATE TOKEN EXPIRATION
        $upd = "UPDATE tokens SET expires=".(time()+60*60*12)." WHERE token_id=".$res['token_id'];
        $db->query($upd);
        return $res['user_id'];
    } else {
        return 0;
    }
}


function randomString($n) {
    $characters = '01234567890123456789ABCDEFGHIJKLMNPQRSTUVWXYZABCDEFGHIJKLMNPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < $n; $i++) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }

    return $randomString;
}

function randomPassword($n) {
    $uppers = "ABCDEFGHIJKLMNPQRSTUVWXYZABCDEFGHIJKLMNPQRSTUVWXYZ";
    $downers = "abcdefghijklmnpqrstuvwxyzabcdefghijklmnpqrstuvwxyz";
    $numbers = "01234567890123456789";
    $symbols = "!@#$%&*!@#$%&*";

    $randomString = '';

    // 1 Uppercase
    for ($i = 0; $i < 1; $i++) {
        $index = rand(0, strlen($uppers) - 1);
        $randomString .= $uppers[$index];
    }

    // 3 Lowercase
    for ($i = 0; $i < 3; $i++) {
        $index = rand(0, strlen($downers) - 1);
        $randomString .= $downers[$index];
    }

    // 4 Numbers
    for ($i = 0; $i < 4; $i++) {
        $index = rand(0, strlen($numbers) - 1);
        $randomString .= $numbers[$index];
    }

    // 1 symbols
    for ($i = 0; $i < 1; $i++) {
        $index = rand(0, strlen($symbols) - 1);
        $randomString .= $symbols[$index];
    }


    return $randomString;
}


//**********************************************************************************************************//
// DB HELPER FUNCTIONS *************************************************************************************//


function qVal( $db, $sql ) {
    $res = $db->query($sql);
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        foreach ($row as $k => $v) {
            return $v;
        }
    } else {
        return false;
    }
}

function qRow( $db, $sql ) {
    $res = $db->query($sql);
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        return $row;
    } else {
        return false;
    }
}

function qSet( $db, $sql ) {
    $out = [];
    $res = $db->query($sql);
    while ($row = $res->fetch_assoc()) {
        $out[] = $row;
    }
    return $out;
}

function qsql( $q ) {
    if ($q->num_rows() == 0) return false;
    else {
        $r = $q->result_array();
        $r = $r[0];
        foreach ($r as $k => $v) return $v;
    }
}

function qin( $a ) {
    $in = '(';
    for ($i=0; $i < count($a); $i++) {
        if ($i > 0) $in .= ',';
        $in .= "'".$a[$i]."'";
    }
    $in .= ')';
    return $in;
}

function shut(){

    $error = error_get_last();

    if($error && ($error['type'] & E_FATAL)){
        handler($error['type'], $error['message'], $error['file'], $error['line']);
    }

}

function handler( $errno, $errstr, $errfile, $errline ) {

    switch ($errno){

        case E_ERROR: // 1 //
            $typestr = 'E_ERROR'; break;
        case E_WARNING: // 2 //
            $typestr = 'E_WARNING'; break;
        case E_PARSE: // 4 //
            $typestr = 'E_PARSE'; break;
        case E_NOTICE: // 8 //
            $typestr = 'E_NOTICE'; break;
        case E_CORE_ERROR: // 16 //
            $typestr = 'E_CORE_ERROR'; break;
        case E_CORE_WARNING: // 32 //
            $typestr = 'E_CORE_WARNING'; break;
        case E_COMPILE_ERROR: // 64 //
            $typestr = 'E_COMPILE_ERROR'; break;
        case E_COMPILE_WARNING: // 128 //
            $typestr = 'E_COMPILE_WARNING'; break;
        case E_USER_ERROR: // 256 //
            $typestr = 'E_USER_ERROR'; break;
        case E_USER_WARNING: // 512 //
            $typestr = 'E_USER_WARNING'; break;
        case E_USER_NOTICE: // 1024 //
            $typestr = 'E_USER_NOTICE'; break;
        case E_STRICT: // 2048 //
            $typestr = 'E_STRICT'; break;
        case E_RECOVERABLE_ERROR: // 4096 //
            $typestr = 'E_RECOVERABLE_ERROR'; break;
        case E_DEPRECATED: // 8192 //
            $typestr = 'E_DEPRECATED'; break;
        case E_USER_DEPRECATED: // 16384 //
            $typestr = 'E_USER_DEPRECATED'; break;

    }

    $message = '<b>'.$typestr.': </b>'.$errstr.' in <b>'.$errfile.'</b> on line <b>'.$errline.'</b><br/>';

    if(($errno & E_FATAL) && ENV === 'production'){

        header('Location: 500.html');
        header('Status: 500 Internal Server Error');

    }

    if(!($errno & ERROR_REPORTING))
        return;

    if(DISPLAY_ERRORS) {
        response( 400, ['success'=>false,'error'=>$message]);
        //printf('%s', $message);
    }
    //Logging error on php file error log...
    if(LOG_ERRORS)
        error_log(strip_tags($message), 0);

}



function get_email_template( $body, $m, $ecid ) {
    $email = <<<END
<html>
<head>
<body>
    <div style="width:100%; background-color:#F6F6F6; padding:20px 0">
        <div style="background-color:#FFFFFF; max-width:600px;margin:0 auto;font-size:16px;line-height:1.6em">
            <div style="background-color:#33612a; padding:20px; border-bottom:solid 4px #efa72d">
                <a href="https://pennhillscdc.org" target="_blank" style="display:block;text-align:center;">
                    <img src="https://pennhillscdc.org/e/email-header.png" width="200" height="148" />
                </a>
            </div>
            <div style="padding:20px;">
                <p style="font-size:24px;color:#efa72d;font-weight:bold">[SUBJECT]</p>
                <p>Hi [NAME],</p>
                [BODY]
                <p>&nbsp;<br/><b>Have a great day!</b>
                    <br/>Your friends at the Penn Hills CDC
                </p>
            </div>
            <div style="background-color:#33612a; padding:20px; border-top:solid 4px #efa72d">
                <a href="https://pennhillscdc.org" target="_blank" style="display:block;text-align:center;">
                    <img src="https://api.pennhillscdc.org/v1/mail/read/[MAILCODE]/[ECID]" width="180" height="44" />
                </a>
                <p style="color:#FFFFFF; margin-top:12px; font-size:13px; text-align:center; line-height: 1.3em">
                    <b style="color:#efa72d">Penn Hills Community Development Corporation</b>
                    <br/>PO Box 17730
                    <br/>Penn Hills, PA 15235
                    <br/>
                    <br/><a href="https://api.pennhillscdc.org/v1/mail/unsubscribe/[MAILCODE]/[ECID]" style="color:#FFFFFF"><u>unsubscribe</u></a>
                </p>
            </div>
        </div>
    </div>
</body>
</html>
END;

    $email = str_replace('[NAME]', $m['fname'], $email);
    $email = str_replace('[MAILCODE]', $m['mailcode'], $email);
    $email = str_replace('[SUBJECT]', $body['subject'], $email);
    $email = str_replace('[ECID]', $ecid, $email);
    $email = str_replace('[BODY]', $body['body'], $email);
    $email = str_replace('<img ', '<img style="max-width:100%" ', $email);

    return $email;
}


function get_email_template_one( $body, $subject, $fname, $mailcode, $ecid ) {
    $email = <<<END
<html>
<head>
<body>
    <div style="width:100%; background-color:#F6F6F6; padding:20px 0">
        <div style="background-color:#FFFFFF; max-width:600px;margin:0 auto;font-size:16px;line-height:1.6em">
            <div style="background-color:#33612a; padding:20px; border-bottom:solid 4px #efa72d">
                <a href="https://pennhillscdc.org" target="_blank" style="display:block;text-align:center;">
                    <img src="https://pennhillscdc.org/e/email-header.png" width="200" height="148" />
                </a>
            </div>
            <div style="padding:20px;">
                <p style="font-size:24px;color:#efa72d;font-weight:bold">[SUBJECT]</p>
                <p>Hi [NAME],</p>
                [BODY]
                <p>&nbsp;<br/><b>Have a great day!</b>
                    <br/>Your friends at the Penn Hills CDC
                </p>
                <p><a href="https://pennhillspassport.com">
                	<img src="https://pennhillscdc.org/e/email-ad.jpg" style="max-width:'100%'" /></a>
                </p>
            </div>
            <div style="background-color:#33612a; padding:20px; border-top:solid 4px #efa72d">
                <a href="https://pennhillscdc.org" target="_blank" style="display:block;text-align:center;">
                    <img src="https://api.pennhillscdc.org/v1/mail/read/[MAILCODE]/[ECID]" width="180" height="44" />
                </a>
                <p style="color:#FFFFFF; margin-top:12px; font-size:13px; text-align:center; line-height: 1.3em">
                    <b style="color:#efa72d">Penn Hills Community Development Corporation</b>
                    <br/>PO Box 17730
                    <br/>Penn Hills, PA 15235
                    <br/>
                    <br/><a href="https://api.pennhillscdc.org/v1/mail/unsubscribe/[MAILCODE]/[ECID]" style="color:#FFFFFF"><u>unsubscribe</u></a>
                </p>
            </div>
        </div>
    </div>
</body>
</html>
END;

    $email = str_replace('[NAME]', $fname, $email);
    $email = str_replace('[MAILCODE]', $mailcode, $email);
    $email = str_replace('[SUBJECT]', $subject, $email);
    $email = str_replace('[ECID]', $ecid, $email);
    $email = str_replace('[BODY]', $body, $email);
    $email = str_replace('<img ', '<img style="max-width:100%" ', $email);

    return $email;
}


function generatePassword($length = 10) {
    // Define the character sets to be used in the password
    $uppercase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
    $lowercase = 'abcdefghjkmnpqrstuvwxyz';
    $numbers = '123456789';
    $symbols = '!@#$%&_+?';

    // Combine all character sets
    $allCharacters = $uppercase . $lowercase . $numbers . $symbols;

    // Initialize the password variable
    $password = '';

    // Generate the random password
    for ($i = 0; $i < $length; $i++) {
        $randomIndex = mt_rand(0, strlen($allCharacters) - 1);
        $password .= $allCharacters[$randomIndex];
    }

    return $password;
}

function generateHash($length = 10) {
    // Define the character sets to be used in the password
    $uppercase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
    $lowercase = 'abcdefghjkmnpqrstuvwxyz';
    $numbers = '123456789';
    $symbols = '!@#$%&_+?';

    // Combine all character sets
    $allCharacters = $uppercase . $lowercase . $numbers;

    // Initialize the password variable
    $password = '';

    // Generate the random password
    for ($i = 0; $i < $length; $i++) {
        $randomIndex = mt_rand(0, strlen($allCharacters) - 1);
        $password .= $allCharacters[$randomIndex];
    }

    return $password;
}