Пример #1
0
    if ($query->count("*") > 0) {
        echo json_encode($result);
    } else {
        echo json_encode(array("status" => false, "message" => "cannot find your keyword {$key}"));
    }
});
/* registation (admin restoran)*/
$app->post('/admin_restoran', function () use($app, $db) {
    require_once 'libs/PassHash.php';
    verifyRequiredParams(array('restoran_id', 'admin_username', 'admin_email', 'admin_password'));
    $restoran_id = $app->request->post('restoran_id');
    $admin_username = $app->request->post('admin_username');
    $admin_email = $app->request->post('admin_email');
    $admin_password = $app->request->post('admin_password');
    $password_hash = PassHash::hash($admin_password);
    $admin_api = generateApiKey();
    validateEmail($admin_email);
    $query = $db->admin_restoran->where("admin_username LIKE ?", $admin_email);
    if ($query->count("*") < 1) {
        $add = $db->admin_restoran->insert(array("restoran_id" => $restoran_id, "admin_username" => $admin_username, "admin_email" => $admin_email, "admin_password" => $password_hash, "admin_api" => $admin_api));
        if ($add != null) {
            echo json_encode(array("status" => true, "message" => "success add new admin"));
        } else {
            echo json_encode(array("status" => false, "message" => "failed to add new admin"));
        }
    } else {
        echo json_encode(array("status" => false, "message" => "email is already exist"));
    }
});
/* login (admin restoran)*/
$app->post('/admin_restoran', function () use($app, $db) {
Пример #2
0
/**
 * Dispatch function for POST /events
 *
 * Determines what the user is requesting -- for example, to add an
 * attachment or to create a new session -- and dispatches or handles.
 *
 * If a new event is requested, takes user input and turns it into an event,
 * including web call to Dialback provider, Event insertion, and API key
 * creation.
 *
 * @todo Why does event creation need to be JSON? Seemed like a good idea at
 *        the time. Move to just HTTP POST fields.
 *
 * @todo Assumes web call for Dialback number succeeded. Add failure handling.
 *
 * @throws BadRequestException
 */
function api_EVENTS_POST_dispatch()
{
    global $database;
    global $path;
    global $apiKey;
    switch (count($path)) {
        /** @noinspection PhpMissingBreakStatementInspection */
        case 3:
            if ($path[2] != "") {
                $response = ['status' => ['code' => 400, 'message' => 'Bad Request'], 'error' => ['message' => 'Invalid Request Path']];
                throw new BadRequestException($response);
            }
            /** @noinspection PhpMissingBreakStatementInspection */
        /** @noinspection PhpMissingBreakStatementInspection */
        case 2:
            $object2 = $path[1];
        case 1:
            $session = $path[0];
            break;
        case 0:
            break;
        default:
            $response = ['status' => ['code' => 400, 'message' => 'Bad Request'], 'error' => ['message' => 'Invalid Request Path']];
            throw new BadRequestException($response);
            break;
    }
    $funcCall = str_replace("_dispatch", "", __FUNCTION__);
    if (isset($session) && strlen($session) > 0) {
        $funcCall = $funcCall . '_ID';
        $parameter = $session;
        if (isset($object2) && strlen($object2) > 0) {
            $funcCall = $funcCall . '_' . strtoupper($object2);
        }
    }
    if ($funcCall != str_replace("_dispatch", "", __FUNCTION__)) {
        if (function_exists($funcCall)) {
            // Explicitly cast $action as a string to reassure the debugger.
            $funcCall = (string) $funcCall;
            if (isset($parameter)) {
                $funcCall($parameter);
            } else {
                $funcCall();
            }
        } else {
            $response = ['status' => ['code' => 400, 'message' => 'Bad Request'], 'error' => ['message' => 'Unsupported API Request.']];
            throw new BadRequestException($response);
        }
    } else {
        try {
            if (!($jsonRequest = json_decode($_POST['request'], true))) {
                throw new InvalidJsonException([$jsonRequest]);
            }
            $requiredFields = ['segment' => ['filter' => FILTER_VALIDATE_INT], 'phoneNumber' => ['filter' => FILTER_VALIDATE_REGEXP, 'options' => ['options' => ['regexp' => "/^\\+? ?[0-9 ]+\$/"]]], 'emailAddress' => ['filter' => FILTER_VALIDATE_EMAIL], 'state' => ['filter' => FILTER_VALIDATE_REGEXP, 'options' => ['options' => ['regexp' => "/^[A-Za-z ]{4,50}\$/"]]], 'latitude' => ['filter' => FILTER_VALIDATE_FLOAT], 'longitude' => ['filter' => FILTER_VALIDATE_FLOAT]];
            foreach ($requiredFields as $key => $parameters) {
                if (!isset($jsonRequest[$key])) {
                    throw new BadRequestException(["Required parameter `{$key}` is missing."]);
                }
                $value = $jsonRequest[$key];
                $filter = $parameters['filter'];
                $options = isset($parameters['options']) ? $parameters['options'] : [];
                if (!filter_var($value, $filter, $options)) {
                    throw new BadRequestException(["Parameter `{$key}`: Invalid value."]);
                }
            }
            $sqlQuery = <<<EOF
            
                SELECT
                    productphoneserver
                FROM
                    tbl__products
                INNER JOIN
                    tbl__segments
                ON
                    tbl__products.productkey=tbl__segments.productkey
                WHERE
                    tbl__segments.segmentkey=?
                
EOF;
            $dialbackQuery = $database->select($sqlQuery, [['i' => $jsonRequest['segment']]]);
            $data = ['emailaddress' => $jsonRequest['emailAddress'], 'phonenumber' => $jsonRequest['phoneNumber'], 'latitude' => $jsonRequest['latitude'], 'logitude' => $jsonRequest['longitude'], 'state' => $jsonRequest['state']];
            // use key 'http' even if you send the request to https://...
            $options = array('http' => array('header' => "Content-type: \n                    application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)));
            $dialbackNumber = file_get_contents($dialbackQuery[0]['productphoneserver'], false, stream_context_create($options));
            if ($dialbackNumber === FALSE) {
                /* Handle error */
                throw new NoDialbackNumberProvidedException([]);
            }
            $sqlQuery = <<<EOF
            
                INSERT INTO
                    tbl__events
                    (
                        session,
                        segmentkey,
                        phonenumber,
                        emailaddress,
                        latitude,
                        longitude,
                        state,
                        dialbacknumber
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        
EOF;
            $sessionId = null;
            $eventQuery = null;
            $eventAdded = false;
            $attempts = 1;
            $i = 0;
            $lastError = null;
            do {
                try {
                    $sessionId = generateSessionId();
                    $eventQuery = $database->insert($sqlQuery, [['s' => $sessionId], ['i' => $jsonRequest['segment']], ['s' => $jsonRequest['phoneNumber']], ['s' => $jsonRequest['emailAddress']], ['d' => $jsonRequest['latitude']], ['d' => $jsonRequest['longitude']], ['s' => $jsonRequest['state']], ['s' => $dialbackNumber]]);
                    $eventAdded = true;
                } catch (DatabaseInsertQueryFailedException $e) {
                    $lastError = print_r($e, true);
                }
                $i++;
            } while (!$eventAdded and $i <= $attempts);
            if (!$eventAdded) {
                throw new EventNotAddedException([$lastError]);
            }
            $sqlQuery = <<<EOF
            
                INSERT INTO
                    tbl__apikeys
                (
                    expiration,
                    scope,
                    ALLOW_RENEW,
                    ALLOW_UPLOAD,
                    ALLOW_LIST,
                    apikey,
                    scopekey
                )
                VALUES
                (
                    DATE_ADD(NOW(), INTERVAL 1 HOUR),
                    'EVENT',
                    1,
                    1,
                    1,
                    ?, ?
                )
                
EOF;
            $apiKey = null;
            $scopeKey = (int) $eventQuery->insert_id;
            $apiKeyAdded = false;
            $attempts = 1;
            $i = 0;
            $apiKeyQuery = null;
            do {
                try {
                    $apiKey = generateApiKey($sessionId);
                    $apiKeyQuery = $database->insert($sqlQuery, [['s' => $apiKey], ['i' => $scopeKey]]);
                    $apiKeyAdded = true;
                } catch (DatabaseInsertQueryFailedException $e) {
                    $lastError = print_r($e, true);
                }
                $i++;
            } while (!$apiKeyAdded and $i <= $attempts);
            if (!$apiKeyAdded) {
                throw new ApiKeyNotAddedException([$lastError]);
            }
            $eventQuery->close();
            $apiKeyQuery->close();
            $response = ['data' => ['session' => $sessionId, 'dial' => $dialbackNumber, 'apiKey' => $apiKey], 'status' => ['code' => 201]];
            sendResponse($response);
        } catch (Exception $e) {
            sendResponse($e);
        }
    }
}