<?php
if (!defined('APS_DEVELOPMENT_MODE')) define ('APS_DEVELOPMENT_MODE', 'on');

## Basic user:password authentication
function rest_request_basic($url, $verb, $login, $passwd,
                $agent = 'test@aps.test', $payload = '') {
    ## $logger = \APS\LoggerRegistry::get(); // Used for troubleshooting

    $headers = array(
        'Content-type: application/json',
        'User-Agent: '.$agent
    );
    $userPwd = $login.":".$passwd;
    $connector = curl_init();
    curl_setopt_array($connector, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $verb,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD => $userPwd,
        ## CURLOPT_VERBOSE=>true, // Use it for troubleshooting
        CURLOPT_POSTFIELDS => json_encode($payload)
    ));
    $response = curl_exec($connector);
    $errors = curl_error($connector);
    $returnCode = (int)curl_getinfo($connector, CURLINFO_HTTP_CODE);
    curl_close($connector);

    ## $logger->info("Return code: ".$returnCode."\n" ); // Logs to /var/log/httpd/error_log
        /*  Use it for troubleshooting only
            print('Error Dump: ');
            var_dump($errors);
            print('Response Dump: ');
            var_dump($response);
        */

    if (!$errors) return json_decode($response);
    else return false;
}

## Authentication via a user token
function rest_request($url, $verb, $token, $agent, $payload = '') {
    $headers = array(
        'Content-type: application/json',
        'User-Agent: '.$agent,
        'Authorization: Token '.$token
    );
    $connector = curl_init();
    curl_setopt_array($connector,array(
        CURLOPT_URL =>$url,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_CUSTOMREQUEST=>$verb,
        CURLOPT_HTTPHEADER=>$headers,
        CURLOPT_FAILONERROR=>true,
        //CURLOPT_VERBOSE=>true,
        CURLOPT_POSTFIELDS=>json_encode($payload)
    ));

    $response = curl_exec($connector);
    $httpcode = curl_getinfo($connector, CURLINFO_HTTP_CODE);
    $errors = curl_error($connector);
    curl_close($connector);

    if (!$errors) {
        if ($verb == 'DELETE') return $httpcode;
        else return json_decode($response);
    }
    else return false;
}

## The function makes the repo name more robust by removing special characters
function makeRepoName($string) {
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-zA-Z0-9_\s-]/", "", $string);

    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);

    //Convert whitespaces and underscores to underscore
    $string = preg_replace("/[\s_]/", "_", $string);

    return $string;
}

?>
