function performGet()
{
    withDatabase(function ($database) {
        $id = getParameter(PARAMETER_ID);
        $dataType = getParameter(PARAMETER_DATA_TYPE);
        $statement = null;
        if ($id) {
            // get by id
            $statement = $database->prepare('SELECT * FROM DATA WHERE id=?');
            $statement->bind_param("s", $id);
        } else {
            if ($dataType) {
                // list
                $statement = $database->prepare('SELECT * FROM DATA WHERE dataType=?');
                $statement->bind_param("s", $dataType);
            } else {
                badRequest("missing parameter 'id' or 'dataType'");
            }
        }
        executeStatement($statement);
        $result = $statement->get_result();
        if ($id) {
            resultToJsonObject($result);
        } else {
            if ($dataType) {
                resultToJsonArray($result);
            }
        }
        $statement->close();
    });
}
示例#2
0
 public function getPosts($args)
 {
     //Get post
     if (isset($args["postId"])) {
         return $this->getPostById($args, $args["postId"]);
     }
     //Get posts for event
     if (isset($args["eventId"])) {
         $eventId = $args["eventId"];
         $before = "9999-12-31";
         $after = "1000-01-01";
         if (isset($args["before"])) {
             $before = $args["before"];
         }
         if (isset($args["after"])) {
             $after = $args["after"];
         }
         return $this->getPostsBetweenDates($args, $eventId, $before, $after);
     }
     //Get posts for search term
     if (isset($args["searchTerm"])) {
         return $this->getPostsWithSearchTerm($args);
     }
     //Get posts for userId
     if (isset($args["userId"])) {
         return $this->getPostsByPublicId($args);
     }
     return $this->io - badRequest("Either the post id, a search term or the event id must be set", $args);
 }
示例#3
0
function executeStatement($statement)
{
    if (!$statement->execute()) {
        $errorMessage = 'Error executing MySQL query: ' . $statement->error;
        $statement->close();
        badRequest($errorMessage);
    }
}
function assertNotEmpty($string, $errorMessage = "bad request")
{
    if (empty($string)) {
        debug("not empty string: {$errorMessage}");
        badRequest($errorMessage);
        die;
    } else {
        return $string;
    }
}
示例#5
0
 public function getEvents($args)
 {
     if (isset($args["eventId"])) {
         $eventID = intval($args["eventId"]);
         return $this->getEventById($args, $eventID);
     }
     if (isset($args["latitude"]) && isset($args["longitude"])) {
         $latitude = $args["latitude"];
         $longitude = $args["longitude"];
         return $this->getEventsSortedByDistance($args, $latitude, $longitude);
     }
     return $this->io - badRequest("Either event id or latitude and longitude must be set", $args);
 }
示例#6
0
文件: index.php 项目: senyor/dojorama
function run()
{
    $method = strtolower($_SERVER["REQUEST_METHOD"]);
    $id = ltrim($_SERVER["REQUEST_URI"], dirname($_SERVER["SCRIPT_NAME"]));
    $id = $id !== '' ? $id : null;
    $items = array(array('id' => 0, 'title' => 'Title 1', 'format' => 1, 'releaseDate' => '2012-12-21', 'price' => '100', 'publish' => false, 'info' => ''), array('id' => 1, 'title' => 'Title 2', 'format' => 1, 'releaseDate' => '2013-12-21', 'price' => '50', 'publish' => false, 'info' => ''), array('id' => 2, 'title' => 'Title 3', 'format' => 1, 'releaseDate' => '2014-12-21', 'price' => '1000', 'publish' => false, 'info' => ''));
    switch ($method) {
        case 'get':
            return $id === null ? listing($items) : detail($id, $items);
        case 'post':
            return $id === null ? create() : badRequest();
        case 'put':
            return $id !== null ? update($id) : badRequest();
        case 'delete':
            return $id !== null ? remove($id) : badRequest();
    }
    return badRequest();
}
示例#7
0
/**
 * Validate get parameters, and die with bad request.
 *
 * @param string $value The value to validate.
 *
 * @return void
 */
function validate($value)
{
    if (preg_match('#[^a-zA-Z0-9_\\|]#', $value)) {
        badRequest();
    }
}
示例#8
0
    $kind = post('kind', 'bad');
    $nom = post('nom');
    $cognoms = post('cognoms');
    $telefon = post('telefon');
    $email = post('email');
    $municipi = post('municipi');
    $adreca = post('adreca');
    $comentari = post('comentari');
    // Optional params
    $yuemail = post('yuemail', 666);
    $filledbyspammers = $yuemail != 666;
} catch (MissingField $e) {
    badRequest($e->getMessage());
}
if (!in_array($kind, array("diy", "pressupost", "dubtes", "connectivitat"))) {
    badRequest("Not the proper form");
}
$subject = "[GuifiBaix Web] {$kind}: {$nom} {$cognoms}";
if ($filledbyspammers) {
    exit;
    $subject = "[GuifiBaix Web] SPAM comment received";
}
if ($debug) {
    echo '</pre>';
}
$yaml_file = <<<EOF
name: {$nom}
familyname: {$cognoms}
type: {$kind}
contact:
  phone:
示例#9
0
文件: gui.php 项目: tedwp/porpoise
    badRequest();
}
switch ($_REQUEST["action"]) {
    case "newAction":
        if (empty($_REQUEST["index"])) {
            badRequest();
        }
        $index = $_REQUEST["index"];
        if (!is_numeric($index)) {
            badRequest();
        }
        if (empty($_REQUEST["layerAction"]) || strtolower($_REQUEST["layerAction"]) != 'true') {
            $layerAction = FALSE;
        } else {
            $layerAction = true;
        }
        printf("%s", GUI::createActionSubtable($index, new POIAction(), $layerAction));
        exit;
    case "newAnimation":
        if (empty($_REQUEST["index"])) {
            badRequest();
        }
        $index = $_REQUEST["index"];
        if (!is_numeric($index)) {
            badRequest();
        }
        printf("%s", GUI::createAnimationSubtable($index, "", new Animation()));
        exit;
    default:
        badRequest();
}
示例#10
0
function clientLogin($email, $pass)
{
    //http://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html
    logMe('clientLogin(' . $email . ")\n");
    if (ctype_alnum($email)) {
        if (!function_exists('password_verify')) {
            include_once LIB_PATH . '/password_compat.php';
        }
        $conf = get_user_configuration($email);
        if (is_null($conf)) {
            Minz_Log::warning('Invalid API user ' . $email . ': configuration cannot be found.');
            unauthorized();
        }
        if ($conf->apiPasswordHash != '' && password_verify($pass, $conf->apiPasswordHash)) {
            header('Content-Type: text/plain; charset=UTF-8');
            $system_conf = Minz_Configuration::get('system');
            $auth = $email . '/' . sha1($system_conf->salt . $email . $conf->apiPasswordHash);
            echo 'SID=', $auth, "\n", 'Auth=', $auth, "\n";
            exit;
        } else {
            Minz_Log::warning('Password API mismatch for user ' . $email);
            unauthorized();
        }
    } else {
        badRequest();
    }
    die;
}
示例#11
0
/**
 * Envia uma notificação
 */
function sendNotification()
{
    global $log;
    $notification = null;
    $app = Slim::getInstance();
    try {
        // leitura da notificação informado no post
        $input = json_decode($app->request()->getBody());
        $log->Debug(sprintf("api - sendNotification - %s", print_r($input, true)));
        if (!$input || !isset($input->message) && !isset($input->data) || !isset($input->users)) {
            throw new \InvalidArgumentException("A requisição náo contém todos os dados necessários.");
        }
        $devices = array();
        $userIds = array();
        foreach ($input->users as $item) {
            if (!isset($item->userId)) {
                throw new \InvalidArgumentException("A requisição não contém todos os dados necessários.");
            }
            $userIds[] = $item->userId;
        }
        $devices = DeviceManager::getDevicesByUsers($userIds);
        $message = isset($input->message) ? $input->message : null;
        $data = isset($input->data) ? json_decode(json_encode($input->data), true) : null;
        $notification = new Notification($devices, $message, $data);
    } catch (Exception $e) {
        badRequest($e, $log);
        return;
    }
    $pushController = new PushController();
    try {
        $notificationResult = $pushController->send($notification);
        $app->response()->header('Content-Type', 'application/json');
        echo json_encode($notificationResult);
    } catch (Exception $e) {
        internalServerError($e, $log);
    }
}
示例#12
0
    case 'PUT':
        if (array_key_exists($employeeId, $employees)) {
            if (array_key_exists('name', $requestData)) {
                $name = $requestData['name'];
            } else {
                $name = array_key_exists('name', $employees[$employeeId]) ? $employees[$employeeId]['name'] : null;
            }
            if (array_key_exists('age', $requestData)) {
                $age = (int) $requestData['age'];
            } else {
                $age = array_key_exists('age', $employees[$employeeId]) ? $employees[$employeeId]['age'] : null;
            }
            $employees[$employeeId] = array('name' => $name, 'age' => $age);
            file_put_contents($file, serialize($employees));
        } else {
            badRequest('Unable to update because the employee does not exist.');
        }
        break;
    case 'DELETE':
        if (array_key_exists($employeeId, $employees)) {
            unset($employees[$employeeId]);
            file_put_contents($file, serialize($employees));
        } else {
            badRequest('Unable to delete because the employee does not exist.');
        }
        break;
    default:
        badRequest('Unsupported REST request.');
        break;
}
exit(json_encode(true));
示例#13
0
function handleRequest($handlerArray)
{
    $method = getRequestMethod();
    debug("Request method: {$method}");
    $handler = $handlerArray[$method];
    if ($handler != null) {
        $handler();
    } else {
        badRequest("Method not supported: " . $method);
    }
}
示例#14
0
function sendEmail($args)
{
    if (!isset($args["senderName"])) {
        return badRequest("Sender name was missing", $args);
    }
    if (!isset($args["senderEmail"])) {
        return badRequest("Sender email was missing", $args);
    }
    if (!isset($args["senderWebsite"])) {
        return badRequest("Sender website was missing", $args);
    }
    if (!isset($args["message"])) {
        return badRequest("Message was missing", $args);
    }
    $senderName = $args["senderName"];
    $senderEmail = $args["senderEmail"];
    $senderWebsite = $args["senderWebsite"];
    $msg = $args["message"];
    $headers = "From: " . $senderEmail;
    $message = "Message from " . $senderName . " at " . $senderEmail . "\n\n" . "Message: \n" . $msg;
    mail("*****@*****.**", "Message from WebSite", $message, $headers);
    return [];
}
示例#15
0
$app->post('/api/bids/place', function (Request $request, Response $response) {
    if (!array_key_exists('cst_session_id', $request->getCookieParams())) {
        logger($this)->addWarning('No contractor session id', getPath($request));
        return forbidden($response);
    }
    $customerSessionId = $request->getCookieParams()["cst_session_id"];
    $customer = getCustomer($customerSessionId);
    if (!isset($customer)) {
        logger($this)->addWarning('No contractor found by session id', array('cst_session_id' => $customerSessionId, 'uri' => $request->getUri()->getPath()));
        return forbidden($response);
    }
    $bid = json_decode($request->getBody());
    list($product, $amount, $price) = parseBid($bid);
    if (!isset($product)) {
        logger($this)->addWarning('Wrong bid', getPath($request));
        return badRequest($response);
    }
    $customerId = $customer['id'];
    if ($price > $customer['amount']) {
        logger($this)->addWarning("Customer doesn't have enough funds to place the bid with price", array('customer_id' => $customerId, 'price' => $price));
        return conflict($response);
    }
    try {
        $bidId = insertBid($product, $amount, $price, $customerId);
        $response->getBody()->write("api/bids/{$bidId}");
        return $response->withStatus(201);
    } catch (PDOException $e) {
        return handleError($e, $response);
    }
});
// LOGOUT