$response->setStatusCode(500, "Internal Error"); $response->send(); die; } // success $response->setStatusCode(200, "Success"); $response->send(); die; }); // view the request log $app->get('/requests', function () use($app) { $redis = $app->di->get('redis'); $output = []; foreach ($redis->zrange('request-log', 0, time()) as $entry) { $entry = json_decode($entry, true); $msg = '<strong>' . date('Y-m-d H:i:s', $entry['key'] / 1000) . "</strong> - STATUS: " . $entry['status'] . " - URI: " . $entry['request'] . " - METHOD: " . $entry['method'] . " - TIME: " . $entry['time'] . "(ms) DATA: " . json_encode($entry['data']); array_unshift($output, $msg); // not efficient } echo implode('<br /><br />', $output); }); // view the error log $app->get('/errors', function () use($app) { $redis = $app->di->get('redis'); $output = []; foreach ($redis->zrange('error-log', 0, time()) as $entry) { $entry = json_decode($entry, true); $msg = '<strong>' . date('Y-m-d H:i:s', $entry['key'] / 1000) . "</strong> - MSG: " . json_encode($entry['msg']) . " - DATA: " . json_encode($entry['data']); array_unshift($output, $msg); // not efficient }
return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name)); }); /** * Registering an autoloader */ $loader = new \Phalcon\Loader(); $loader->registerDirs(array($config->application->modelsDir))->register(); /** * Starting the application */ $app = new \Phalcon\Mvc\Micro(); /** * Add your routes here */ $app->get('/', function () { require __DIR__ . "/../views/index.phtml"; }); /** * Not found handler */ $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); require __DIR__ . "/../views/404.phtml"; }); /** * Handle the request */ $app->handle(); } catch (Phalcon\Exception $e) { echo $e->getMessage(); } catch (PDOException $e) {
$loader = new \Phalcon\Loader(); $loader->registerDirs([__DIR__ . '/models/'])->register(); $di = new \Phalcon\DI\FactoryDefault(); $di->set('db', function () { return new \Phalcon\Db\Adapter\Pdo\Mysql(['host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'time']); }); $app = new \Phalcon\Mvc\Micro($di); /** * Tasks */ $app->get('/tasks', function () use($app) { $phql = "SELECT * FROM Tasks"; $tasks = $app->modelsManager->executeQuery($phql); $data = new StdClass(); $data->tasks = []; foreach ($tasks as $task) { $data->tasks[] = ['id' => $task->id, 'name' => $task->name, 'shortDescription' => $task->short_description, 'longDescription' => $task->long_description, 'day' => $task->day, 'started' => $task->started, 'completed' => $task->completed]; } echo json_encode($data); }); $app->post('/tasks', function () use($app) { $request = $app->request->getJsonRawBody()->task; $name = $request->name; $short = $request->shortDescription; $long = $request->longDescription; $day = $request->day; $phql = "INSERT INTO Tasks(name, short_description, long_description, day, started, completed) VALUES(:name:, :short:, :long:, :day:, null, null)"; $status = $app->modelsManager->executeQuery($phql, ['name' => $name, 'short' => $short, 'long' => $long, 'day' => $day]); $response = new \Phalcon\Http\Response(); if ($status->success()) { $response->setJsonContent(['status' => 'OK']);
require __DIR__ . "/../app/bootstrap/loader.php"; // Setup all required services (DI) $di = (require __DIR__ . "/../app/bootstrap/services.php"); // Instantiate main application $app = new \Phalcon\Mvc\Micro($di); // Attach the EventsManager to the main application in order to attach Middleware $eventsManager = $app->di->get(AppServices::EVENTS_MANAGER); $app->setEventsManager($eventsManager); // Attach Middleware to EventsManager require __DIR__ . "/../app/bootstrap/middleware.php"; // Mount Collections require __DIR__ . "/../app/bootstrap/collections.php"; // Other routes $app->get('/', function () use($app) { /** @var Phalcon\Mvc\View\Simple $view */ $view = $app->di->get(AppServices::VIEW); return $view->render('general/index'); }); $app->get('/proxy.html', function () use($app, $config) { /** @var Phalcon\Mvc\View\Simple $view */ $view = $app->di->get(AppServices::VIEW); $view->setVar('client', $config->clientHostName); return $view->render('general/proxy'); }); // Start application $app->handle(); // Set content $returnedValue = $app->getReturnedValue(); if ($returnedValue !== null) { if (is_string($returnedValue)) { $app->response->setContent($returnedValue);
$app->setDI($di); $app->setEventsManager($eventManager); $app->response->setContentType('text/json', 'UTF-8'); $app->response->sendHeaders(); /** * 路由 */ //注册 $app->post('/sendcode', [$app->auth, 'getYZM']); $app->post('/checkphone', [$app->auth, 'checkphone']); $app->post('/headerimg', [$app->auth, 'uploadHeaderImg']); $app->post('/register', [$app->auth, 'register']); //登陆 $app->post('/login', [$app->auth, "login"]); //登出 $app->get('/logout', [$app->auth, "logout"]); //更新所在GPS $app->post('/addr', [$app->auth, "setAddr"]); //更新交友状态 $app->post('/actstatus', [$app->auth, "setActStatus"]); //设置关注 $app->post('/like', [new SnsController(), "setLikeAction"]); //获取我关注喜欢 $app->get('/like', [new SnsController(), "getLikeAction"]); //获取关注我喜欢 $app->get('/likeme', [new SnsController(), "getLikeMeAction"]); //获取我关注喜欢 $app->get('/likestate/{fid}', [new SnsController(), "getLikeStateAction"]); //取消关注 $app->post('/unlike', [new SnsController(), "unLikeAction"]); //获取用户的基础信息
<?php $app = new Phalcon\Mvc\Micro(); $app->get('/user/{name}', function ($name) { echo "<h1>Hi {$name}!</h1>"; }); $app->get('/api/user/{name}', function ($name) { echo json_encode(array("message" => "Hi " . $name)); }); $app->handle();
include "utils.php"; $loader = new Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . '/models/'))->register(); $di = new Phalcon\DI\FactoryDefault(); $di->set('db', function () { return new Phalcon\Db\Adapter\Pdo\Sqlite(array("dbname" => "./chatroom.sqlite")); }); // Initialization $app = new Phalcon\Mvc\Micro($di); $app->getRouter()->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); //////////////////////////////////////////////////////// //////////////////////// ROUTES //////////////////////// //////////////////////////////////////////////////////// // Test call. $app->get('/chat/test', function () { echo json_encode(array('name' => 'Platform is up, check the database in case there are problems!')); }); // Get the list of all the active users in the chat. $app->get('/users', function () use($app) { $phql = "SELECT username, active, access_timestamp\n \t\tFROM Users\n \t\tWHERE active = 1 \n \t\tORDER BY access_timestamp DESC"; $users = $app->modelsManager->executeQuery($phql); $data = array(); foreach ($users as $user) { $data[] = array('id' => $user->id, 'active' => $user->active, 'access_timestamp' => $user->access_timestamp); } echo json_encode($data); }); // Get messages per pair of users. $app->get('/chat/{user1}/{user2}', function ($user1, $user2) use($app) { $phql = "SELECT * \n \t\tFROM Messages m \n \t\tWHERE (m.sender_id = :user1: AND m.receiver_id = :user2:) OR (m.sender_id = :user2: AND m.receiver_id = :user1:) \n \t\tORDER BY m.message_timestamp"; $messages = $app->modelsManager->executeQuery($phql, array('user1' => $user1, 'user2' => $user2));
<?php $app = new Phalcon\Mvc\Micro(); $app->notFound(function () use($app) { $app->response->setStatusCode(404, 'Not Found')->sendHeaders(); echo 'Page not found.'; }); // begin route config $app->get('/api/test', function () { echo "HELLO WORLD"; }); $app->handle();
/** * Mount all of the collections, which makes the routes active. */ foreach ($di->get('collections') as $collection) { $app->mount($collection); } /** * The base route return the list of defined routes for the application. * This is not strictly REST compliant, but it helps to base API documentation off of. * By calling this, you can quickly see a list of all routes and their methods. */ $app->get('/', function () use($app) { $routes = $app->getRouter()->getRoutes(); $routeDefinitions = ['GET' => [], 'POST' => [], 'PUT' => [], 'PATCH' => [], 'DELETE' => [], 'HEAD' => [], 'OPTIONS' => []]; /* @var $route Phalcon\Mvc\Router\Route */ foreach ($routes as $route) { $method = $route->getHttpMethods(); $routeDefinitions[$method][] = $route->getPattern(); } return $routeDefinitions; }); /** * Before every request, make sure user is authenticated. * Returning true in this function resumes normal routing. * Returning false stops any route from executing. */ $app->before(function () use($app, $di) { $config = $app->config; // getting access token is permitted ;) if (strpos($app->request->getURI(), '/access_token') !== FALSE || strpos($app->request->getURI(), '/authorize') !== FALSE || $app->request->isOptions()) { return $di->getShared('rateLimits', ['access_token', $app->request->getClientAddress(), $app]); }
<?php $app = new Phalcon\Mvc\Micro(); $app->get('/say/welcome/{name}', function ($name) { echo "<h1>Welcome {$name}!</h1>"; }); $app->handle();
$app->get('/configuration/{configuration}', function ($configuration) use($di, $app) { $configArray = explode(".", $configuration); $configKey = $configArray[0]; $encoding = "json"; if (count($configArray) === 2) { $encoding = $configArray[1]; } // Gerer le cas où on appelle une configuration inexistante et où il y aurait une erreur dans la configuration. if (isset($di->getConfig()->configurations[$configKey])) { $xmlPath = $di->getConfig()->configurations[$configKey]; } else { $xmlPath = $di->getConfig()->configurationsDir . $configKey . '.xml'; } if (!file_exists($xmlPath) && !curl_url_exists($xmlPath)) { $app->response->setStatusCode(404, "Not Found"); $error = new stdClass(); $error->error = "La configuration « {$configuration} » n'existe pas!"; $app->response->send(); die(json_encode($error)); } if ($encoding === "json") { $app->response->setContentType('application/json; charset=UTF-8')->sendHeaders(); if (file_exists($xmlPath)) { $element = simplexml_load_file($xmlPath, 'SimpleXMLElement', LIBXML_NOCDATA); } else { $element = simplexml_load_string(curl_file_get_contents($xmlPath), 'SimpleXMLElement', LIBXML_NOCDATA); } if ($element->getName() === "navigateur") { //Gerer le cas des couches seulement avec un Id //Retourner l'info pour creer correctement la couche cote client $result = $element->xpath('//couche[boolean(@idbd)]'); $avertissement = null; $debug = $app->getDI()->get("config")->application->debug; foreach ($result as $couche) { $coucheId = $couche->attributes()->idbd->__toString(); if (is_numeric($coucheId)) { $coucheBd = IgoVueCouche::findFirst("id=" . $coucheId); } else { $coucheBd = IgoVueCouche::findFirst("mf_layer_name='" . $coucheId . "'"); } if ($coucheBd === false) { if (is_numeric($coucheId)) { $avertissement[] = "La couche avec id:« {$coucheId} » n'existe pas!"; $dom = dom_import_simplexml($couche); $dom->parentNode->removeChild($dom); continue; } else { $avertissement[] = "La couche avec mf_layer_name:« {$coucheId} » n'existe pas!"; $dom = dom_import_simplexml($couche); $dom->parentNode->removeChild($dom); continue; } } //Vérifier l'access $permission = obtenirPermission($coucheBd->id); if ($permission != null && $permission->est_lecture) { if ($coucheBd->connexion_type == 'POSTGIS' || $coucheBd->connexion_type == null) { $mf_map_meta_onlineresource = $di->getConfig()->mapserver['host'] . $di->getConfig()->mapserver['mapserver_path'] . $di->getConfig()->mapserver['executable'] . $di->getConfig()->mapserver['mapfileCacheDir'] . $di->getConfig()->mapserver['couchesCacheDir'] . $coucheBd->mf_layer_name . '.map'; $protocole = 'WMS'; //ne pas exposer unset($coucheBd->connexion); } else { $mf_map_meta_onlineresource = $coucheBd->connexion; $protocole = $coucheBd->connexion_type; } !$couche->attributes()->nom ? $couche->addAttribute("mf_map_meta_onlineresource", $mf_map_meta_onlineresource) : null; !$couche->attributes()->protocole ? $couche->addAttribute("protocole", $protocole) : null; !$couche->attributes()->nom ? $couche->addAttribute("nom", $coucheBd->mf_layer_name) : null; !$couche->attributes()->titre ? $couche->addAttribute("titre", $coucheBd->mf_layer_meta_title) : null; !$couche->attributes()->url ? $couche->addAttribute("url", $mf_map_meta_onlineresource) : null; !$couche->attributes()->fond ? $couche->addAttribute("fond", $coucheBd->est_fond_de_carte) : null; foreach ($coucheBd as $key => $value) { if (!$couche->attributes()->{$key}) { $couche->addAttribute($key, $value); } } } else { if (isset($debug) && ($debug > 1 || $debug === true)) { $avertissement[] = 'Vous n\'avez pas les droits sur la couche "' . $coucheBd->mf_layer_meta_title . '" (id:' . $coucheBd->id . ')'; } $dom = dom_import_simplexml($couche); $dom->parentNode->removeChild($dom); } } if ($avertissement != null) { foreach ($avertissement as $value) { $element->addChild('avertissements', $value); } } echo json_encode($element); } else { $app->response->setStatusCode(404, "Not Found"); $error = new stdClass(); $error->error = "L'élément racine du fichier de configuration doit se nommer « navigateur »!"; $app->response->send(); die(json_encode($error)); } } else { $app->response->setStatusCode(404, "Not Found"); $error = new stdClass(); $error->error = "L'encodage «{$encoding} » n'est pas supporté!"; $app->response->send(); die(json_encode($error)); } });
$app->get('/balances', function () use($app, &$mysqli) { global $authinfo; //Create a response $response = new Phalcon\Http\Response(); $request = $app->request; if (!array_key_exists('CONTENT_LENGTH', $_SERVER) || intval($_SERVER['CONTENT_LENGTH']) != 0) { //Change the HTTP status $response->setStatusCode(400, "Bad Request"); //Send errors to the client $response->setJsonContent(array('status' => 'ERROR', 'messages' => array('Payload (or CONTENT_LENGTH) is missing'))); } else { // Retrieve all known nodes for current hub $sql = "SELECT TestNet, PubKey, LastUpdate FROM cmd_info_masternode_balance"; $mnpubkeys = array(); $tnpubkeys = array(); if ($result = $mysqli->query($sql)) { while ($row = $result->fetch_assoc()) { $date = new DateTime($row['LastUpdate']); $row['LastUpdate'] = $date->getTimestamp(); if ($row['TestNet'] == 1) { $tnpubkeys[$row['PubKey']] = $row['LastUpdate']; } else { $mnpubkeys[$row['PubKey']] = $row['LastUpdate']; } } //Change the HTTP status $response->setStatusCode(200, "OK"); $response->setJsonContent(array('status' => 'OK', 'data' => array('balances' => array('testnet' => $tnpubkeys, 'mainnet' => $mnpubkeys)))); } else { $response->setStatusCode(503, "Service Unavailable"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array($mysqli->errno . ': ' . $mysqli->error))); } } return $response; });
$security = new \Phalcon\Security(); $security->setWorkFactor(12); return $security; }, true); $container->set('db', function () { return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => 'localhost', "username" => 'root', "password" => 'root', "dbname" => 'dez-auth')); }); $app = new \Phalcon\Mvc\Micro(); $app->setDI($container); $app->session->start(); $app->get('/', function () use($container, $app) { /** @var \PhalconDez\Auth\Auth $auth */ $auth = $container->get('auth'); $email = '*****@*****.**'; $password = '******'; try { $auth->authenticate($email, $password); } catch (\Exception $e) { $auth->create($email, $password); $container->get('response')->redirect('auth-page'); } if ($app->request->get('auth') > 0) { $auth->authenticate('*****@*****.**', '123qwe'); } if ($app->request->get('create') > 0) { $auth->create('*****@*****.**', '123qwe'); } var_dump($auth); return new \Phalcon\Http\Response('test auth component'); }); $app->handle()->getContent();
/** * Handles the request. */ public function main() { /** * Our application is a Micro application, so we must explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new \Phalcon\Mvc\Micro(); $app->setDI($this->di); /** * This will require changes to fit your application structure. * It supports Auth, Session auth, and Exempted routes. * It also allows all Options requests, as those tend to not come with * cookies or basic auth credentials and Preflight is not implemented the * same in every browser. */ $app->before(function () use($app) { // Oauth, for programmatic responses if ($app->request->getHeader('X_COMPARE_REST_API_KEY') && $app->request->get('language') && $app->request->get('countryCode')) { $session = new SessionsController(); $result = $session->resource($app->request->getHeader('X_COMPARE_REST_API_KEY')); if ($result) { return true; } else { throw new HTTPException('Invalid access token.', 401, ['dev' => 'Please provide credentials by passing your access token.', 'internalCode' => 'Unauth:1']); } } // If we made it this far, we have no valid auth method, throw a 401. throw new HTTPException('Must provide credentials.', 401, ['dev' => 'Please provide credentials by passing your access token, language and country code.', 'internalCode' => 'Unauth:1']); return false; }); /** * Mount all of the collections, which makes the routes active. */ foreach ($this->di->getShared('collections') as $collection) { $app->mount($collection); } /** * The base route return the list of defined routes for the application. * This is not strictly REST compliant, but it helps to base API documentation off of. * By calling this, you can quickly see a list of all routes and their methods. */ $app->get('/', function () use($app) { $routes = $app->getRouter()->getRoutes(); $routeDefinitions = array('GET' => array(), 'POST' => array(), 'PUT' => array(), 'PATCH' => array(), 'DELETE' => array(), 'HEAD' => array(), 'OPTIONS' => array()); foreach ($routes as $route) { $method = $route->getHttpMethods(); $routeDefinitions[$method][] = $route->getPattern(); } return $routeDefinitions; }); /** * After a route is run, usually when its Controller returns a final value, * the application runs the following function which actually sends the response to the client. * * The default behavior is to send the Controller's returned value to the client as JSON. * However, by parsing the request querystring's 'type' paramter, it is easy to install * different response type handlers. Below is an alternate csv handler. */ $app->after(function () use($app) { // OPTIONS have no body, send the headers, exit if ($app->request->getMethod() == 'OPTIONS') { $app->response->setStatusCode('200', 'OK'); $app->response->send(); return; } // Respond by default as JSON if (!$app->request->get('type') || 'json' == $app->request->get('type') || 'option' == $app->request->get('type')) { // Results returned from the route's controller. All Controllers should return an array $records = $app->getReturnedValue(); $response = new JSONResponse(); $response->useEnvelope(true)->convertSnakeCase(true)->send($records); return; } else { if ('xml' == $app->request->get('type')) { $records = $app->getReturnedValue(); $response = new XMLResponse(); $response->send($records); return; } else { if ('csv' == $app->request->get('type')) { $records = $app->getReturnedValue(); $response = new CSVResponse(); $response->useHeaderRow(true)->send($records); return; } else { throw new HTTPException('Could not return results in specified format', 403, array('dev' => 'Could not understand type specified by type paramter in query string.', 'internalCode' => 'NF1000', 'more' => 'Type may not be implemented. Choose either "json", "xml" or "csv"')); } } } }); /** * The notFound service is the default handler function that runs when no route was matched. * We set a 404 here unless there's a suppress error codes. */ $app->notFound(function () use($app) { throw new HTTPException('Not Found.', 404, array('dev' => 'That route was not found on the server.', 'internalCode' => 'NF1000', 'more' => 'Check route for mispellings.')); }); /** * If the application throws an HTTPException, send it on to the client as json. * Elsewise, just log it. */ set_exception_handler(function ($exception) use($app) { //HTTPException's send method provides the correct response headers and body if (is_a($exception, 'App\\Common\\Lib\\Application\\Exceptions\\HTTPException')) { $exception->send(); } error_log($exception); error_log($exception->getTraceAsString()); }); $app->handle(); }
// Use Loader() to autoload our models $loader = new \Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . '/models/'))->register(); //Set up the database service, values set in config.php $di->set('db', function () { return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => MYSQL_HOST, "username" => MYSQL_USER, "password" => MYSQL_PASS, "dbname" => MYSQL_DB_NAME)); }); /** * Default routes */ $app->get("/", function () use($app, $mongo) { $mdb = $mongo->selectDB(MDB_DB_NAME); $books = $mdb->selectCollection(MDB_COLLECTION); $json = array("version" => VERSION, "mongodb" => 'ok', "collection" => $books->getName(), "db" => "ok", "routes" => array()); foreach ($app->router->getRoutes() as $route) { $json["routes"][] = $route->getPattern(); } echo "<pre>"; echo json_encode($json, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES); echo "</pre>"; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo 'La url solicitada no existe!'; }); //Before middleware $app->before(function () use($app, $logger) { $logger->log("{$app->request->getScheme()} {$app->request->getHttpHost()} {$app->request->getMethod()} {$app->request->get("_url")}"); }); /** * Route handlers
/** * Tests the notFound * * @issue T169 * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-11-06 */ public function testMicroNotFound_T169() { $handler = new RestHandler($this); $app = new \Phalcon\Mvc\Micro(); $app->get('/api/site', array($handler, 'find')); $app->post('/api/site/save', array($handler, 'save')); $flag = false; $app->notFound(function () use(&$flag) { $flag = true; }); $_SERVER['REQUEST_METHOD'] = 'GET'; $_GET['_url'] = '/fourohfour'; $app->handle(); $this->assertTrue($flag); }
<?php $loader = new \Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . '/models/'))->register(); $app = new \Phalcon\Mvc\Micro(); $app->get('/products/find', function () { foreach (Products::find() as $product) { echo $product->name, '<br>'; } }); $app->handle();
<?php $app = new Phalcon\Mvc\Micro(); $app['view'] = function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir('app/views/'); return $view; }; //Return a rendered view $app->get('/products/show', function () use($app) { // Render app/views/products/show.phtml passing some variables echo $app['view']->render('products/show', array('id' => 100, 'name' => 'Artichoke')); });
<?php use app\controllers\AuthController, app\models\feeds, app\models\feedcomments, app\models\friends, app\models\feedfollows, app\models\metafriends, app\models\notifications, app\models\profiles, app\models\users, app\models\privacy, app\models\embeds, app\models\photos, app\models\photoalbums, app\models\photocomments, app\models\phototaggroups, app\controllers\NotificationController, app\library\session\userSessions, app\library\fs\fileStorage as fs; /* * Micro doesn't support any headers (ex: cookies and redirection) */ $app = new \Phalcon\Mvc\Micro($di); $app->get('/ajax/test', function () { return 'Powered By Phalcon API'; }); $app->post('/ajax/test', function () { return 'Powered By Phalcon API'; }); $app->delete('/ajax/test', function () { return 'Powered By Phalcon API'; }); $app->post('/ajax/recover', function () use($app) { $mongo = $app->getDI()->getShared('mongo'); $json = $app->request->getJsonRawBody(); $user = $mongo->users->find(array('email' => $json->email), array('email' => 1)); $user = iterator_to_array($user, false); if (count($user) > 0) { $app->response->setJsonContent(array('success' => true)); } else { $app->response->setJsonContent(array('success' => false, 'message' => "Email doesn't exist.")); } $app->response->send(); }); $app->put('/ajax/recover/change', function () use($app) { $mongo = $app->getDI()->getShared('mongo'); });
return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "localhost", "username" => "root", "password" => "root", "dbname" => "phalcon")); }); $app = new Phalcon\Mvc\Micro($di); // Получение всех пользователей $app->get('/api/users', function () use($app) { // create token // new \Firebase\JWT\JWT; $key = "example_key"; $token = array("iss" => "http://example.org", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000); /** * IMPORTANT: * You must specify supported algorithms for your application. See * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 * for a list of spec-compliant algorithms. */ $jwt = \Firebase\JWT\JWT::encode($token, $key); $decoded = \Firebase\JWT\JWT::decode($jwt, $key, array('HS256')); print_r($decoded); // $phql = "SELECT * FROM Users ORDER BY name"; $robots = $app->modelsManager->executeQuery($phql); $data = array(); foreach ($robots as $robot) { $data[] = array('id' => $robot->id, 'name' => $robot->name); } echo json_encode($data); }); // Получение всех пользователей $app->get('/data/users', function () use($app) { $phql = "SELECT * FROM Users ORDER BY name"; $robots = $app->modelsManager->executeQuery($phql);
$app->get('/api/blocks', function () use($app, &$mysqli) { //Create a response $response = new Phalcon\Http\Response(); $response->setHeader('Access-Control-Allow-Origin', '*'); $response->setHeader("Content-Type", "application/json"); $request = $app->request; $errmsg = array(); if (!array_key_exists('CONTENT_LENGTH', $_SERVER) || intval($_SERVER['CONTENT_LENGTH']) != 0) { $errmsg[] = "No CONTENT expected"; } // Retrieve the 'testnet' parameter if ($request->hasQuery('testnet')) { $testnet = intval($request->getQuery('testnet')); if ($testnet != 0 && $testnet != 1) { $testnet = 0; } } else { $testnet = 0; } // Retrieve the 'nodetail' parameter if ($request->hasQuery('nodetail')) { $nodetail = intval($request->getQuery('nodetail')) == 1; $cachenodetail = 1; } else { $nodetail = false; $cachenodetail = 0; } // Retrieve the 'interval' parameter if ($request->hasQuery('interval')) { try { $interval = new DateInterval($request->getQuery('interval')); $cacheinterval = $request->getQuery('interval'); $cachetime = 900; } catch (Exception $e) { $errmsg[] = 'Wrong interval parameter'; $interval = new DateInterval('P1D'); $cacheinterval = "P1D"; $cachetime = 150; } } else { $interval = new DateInterval('P1D'); $cacheinterval = "P1D"; $cachetime = 150; } $interval->invert = 1; $datefrom = new DateTime(); $datefrom->add($interval); $datefrom = $datefrom->getTimestamp(); // Retrieve the 'pubkeys' parameter if ($request->hasQuery('pubkeys')) { $mnpubkeys = json_decode($request->getQuery('pubkeys')); if ($mnpubkeys === false || !is_array($mnpubkeys)) { $errmsg[] = "Parameter pubkeys: Not a JSON encoded list of pubkeys"; } else { foreach ($mnpubkeys as $mnpubkey) { if ($testnet == 1 && !(substr($mnpubkey, 0, 1) == 'x' || substr($mnpubkey, 0, 1) == 'y') || $testnet == 0 && !(substr($mnpubkey, 0, 1) == 'X' || substr($mnpubkey, 0, 1) == '7') || strlen($mnpubkey) != 34) { $errmsg[] = "Parameter pubkeys: Entry {$mnpubkey}: Incorrect pubkey format."; } } } } else { $mnpubkeys = array(); } if (count($errmsg) > 0) { //Change the HTTP status $response->setStatusCode(400, "Bad Request"); //Send errors to the client $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errmsg)); } else { $cacheserial = sha1(serialize($mnpubkeys)); $cachefnam = CACHEFOLDER . sprintf("dashninja_blocks_%d_%d_%s_%d_%s", $testnet, $cachenodetail, $cacheinterval, count($mnpubkeys), $cacheserial); $cachefnamupdate = $cachefnam . ".update"; $cachevalid = is_readable($cachefnam) && (filemtime($cachefnam) + $cachetime >= time() || file_exists($cachefnamupdate)); if ($cachevalid) { $data = unserialize(file_get_contents($cachefnam)); $response->setStatusCode(200, "OK"); $response->setJsonContent(array('status' => 'OK', 'data' => $data)); } else { touch($cachefnamupdate); $sql = "SELECT Protocol, ProtocolDescription FROM cmd_info_protocol_description"; $protocols = array(); if ($result = $mysqli->query($sql)) { while ($row = $result->fetch_assoc()) { $protocols[$row['Protocol']] = $row['ProtocolDescription']; } } else { $response->setStatusCode(503, "Service Unavailable"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => $mysqli->errno . ': ' . $mysqli->error)); } // Retrieve all blocks for last 24h $sqlpk = ""; // Add selection by pubkey if (count($mnpubkeys) > 0) { $sqlpk = " AND ("; $sqls = ''; foreach ($mnpubkeys as $mnpubkey) { if (strlen($sqls) > 0) { $sqls .= ' OR '; } $mnpubkeyesc = $mysqli->real_escape_string($mnpubkey); $sqls .= sprintf("cib.BlockMNPayee = '%s' OR cibh.BlockMNPayee = '%s'", $mnpubkeyesc, $mnpubkeyesc); } $sqlpk .= $sqls . ")"; } $sql = sprintf("SELECT BlockId, BlockHash, cib.BlockMNPayee BlockMNPayee, BlockMNPayeeDonation, BlockMNValue, BlockSupplyValue, BlockMNPayed, BlockPoolPubKey, PoolDescription, BlockMNProtocol, BlockTime, BlockDifficulty, BlockMNPayeeExpected, BlockMNValueRatioExpected FROM cmd_info_blocks cib LEFT JOIN cmd_pools_pubkey cpp ON cib.BlockPoolPubKey = cpp.PoolPubKey AND cib.BlockTestNet = cpp.PoolTestNet WHERE cib.BlockTestNet = %d AND cib.BlockTime >= %d ORDER BY BlockId DESC", $testnet, $datefrom); $numblocks = 0; $curblock = -1; $blocks = array(); $maxprotocol = 0; $blockidlow = 9999999999; $blockidhigh = 0; $sqlwheretemplate = "BlockHeight = %d"; $sqlblockids = array(); if ($result = $mysqli->query($sql)) { while ($row = $result->fetch_assoc()) { if ($row['BlockMNProtocol'] > $maxprotocol) { $maxprotocol = $row['BlockMNProtocol']; } if ($row['BlockId'] > $blockidhigh) { $blockidhigh = $row['BlockId']; } if ($row['BlockId'] < $blockidlow) { $blockidlow = $row['BlockId']; } $blocks[intval($row["BlockId"])] = array("BlockId" => intval($row["BlockId"]), "BlockHash" => $row["BlockHash"], "BlockMNPayee" => $row["BlockMNPayee"], "BlockMNPayeeDonation" => intval($row["BlockMNPayeeDonation"]), "BlockMNValue" => floatval($row["BlockMNValue"]), "BlockSupplyValue" => floatval($row["BlockSupplyValue"]), "BlockMNPayed" => intval($row["BlockMNPayed"]), "BlockPoolPubKey" => $row["BlockPoolPubKey"], "PoolDescription" => $row["PoolDescription"], "BlockMNProtocol" => $row["BlockMNProtocol"], "BlockTime" => intval($row["BlockTime"]), "BlockDifficulty" => floatval($row["BlockDifficulty"]), "BlockMNPayeeExpected" => $row["BlockMNPayeeExpected"], "BlockMNValueRatioExpected" => floatval($row["BlockMNValueRatioExpected"])); $sqlblockids[] = sprintf($sqlwheretemplate, $row['BlockId']); } $curmnpaymentratio = 0.5; foreach ($blocks as $blockid => $block) { $blocks[$blockid]['BlockMNValueRatio'] = round($block['BlockMNValue'] / $block['BlockSupplyValue'], 3); if (count($mnpubkeys) > 0 && !in_array($blocks[$blockid]['BlockMNPayee'], $mnpubkeys) && !in_array($blocks[$blockid]['BlockMNPayeeExpected'], $mnpubkeys)) { unset($blocks[$blockid]); } elseif ($blocks[$blockid]['BlockMNValueRatioExpected'] > $curmnpaymentratio) { $curmnpaymentratio = $blocks[$blockid]['BlockMNValueRatioExpected']; } } $blocksnew = array(); foreach ($blocks as $block) { $blocksnew[] = $block; } $blocks = $blocksnew; unset($blocksnew); $totalmninfo = 0; $uniquemnips = 0; $mninfo = drkmn_masternodes_count($mysqli, $testnet, $totalmninfo, $uniquemnips); if ($mninfo === false) { $response->setStatusCode(503, "Service Unavailable"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array($mysqli->errno . ': ' . $mysqli->error, $totalmninfo))); return $response; } $perversion = array(); $perminer = array(); foreach ($blocks as $block) { if (!is_null($block['PoolDescription'])) { $minerkey = $block['PoolDescription']; } else { $minerkey = $block['BlockPoolPubKey']; } if (!array_key_exists($minerkey, $perminer)) { $perminer[$minerkey] = array('PoolPubKeys' => array($block['BlockPoolPubKey']), 'PoolName' => $block['PoolDescription'], 'Blocks' => 0, 'BlocksPayed' => 0, 'TotalAmount' => 0.0, 'MasternodeAmount' => 0.0, 'BlocksPayedToCurrentProtocol' => 0, 'BlocksPayedToOldProtocol' => 0, 'BlocksPayedCorrectly' => 0, 'RatioMNPaymentsExpected' => round($curmnpaymentratio, 3)); if (is_null($perminer[$minerkey]['PoolName'])) { $perminer[$minerkey]['PoolName'] = ''; } } if (!in_array($block['BlockPoolPubKey'], $perminer[$minerkey]['PoolPubKeys'])) { $perminer[$minerkey]['PoolPubKeys'][] = $block['BlockPoolPubKey']; } $perminer[$minerkey]['Blocks']++; $perminer[$minerkey]['TotalAmount'] += $block['BlockSupplyValue']; $perminer[$minerkey]['MasternodeAmount'] += $block['BlockMNValue']; $perminer[$minerkey]['BlocksPayed'] += $block['BlockMNPayed']; if (!array_key_exists($block['BlockMNProtocol'], $perversion)) { if (array_key_exists($block['BlockMNProtocol'], $mninfo)) { $mncount = $mninfo[$block['BlockMNProtocol']]['ActiveMasternodesCount']; $mnuniqueips = $mninfo[$block['BlockMNProtocol']]['UniqueActiveMasternodesIPs']; } else { $mncount = 0; $mnuniqueips = 0; } if (array_key_exists($block['BlockMNProtocol'], $protocols)) { $protocoldesc = $protocols[$block['BlockMNProtocol']]; } else { $protocoldesc = $protocols[0]; } $perversion[$block['BlockMNProtocol']] = array('ProtocolDesc' => $protocoldesc, 'Blocks' => 0, 'BlocksPayed' => 0, 'Amount' => 0.0, 'BlocksPayedCorrectRatio' => 0.0, 'BlocksPayedIncorrectRatio' => 0.0, 'MasternodesPopulation' => $mncount, 'MasternodesUniqueIPs' => $mnuniqueips, 'EstimatedMNDailyEarnings' => 0.0); } $perversion[$block['BlockMNProtocol']]['Blocks']++; $perversion[$block['BlockMNProtocol']]['Amount'] += $block['BlockMNValue']; $perversion[$block['BlockMNProtocol']]['BlocksPayed'] += $block['BlockMNPayed']; if (round($block['BlockMNValueRatio'], 3) == round($block['BlockMNValueRatioExpected'], 3)) { $perversion[$block['BlockMNProtocol']]['BlocksPayedCorrectRatio']++; $correctpayment = true; } elseif ($block['BlockMNValueRatio'] > 0) { $perversion[$block['BlockMNProtocol']]['BlocksPayedIncorrectRatio']++; $correctpayment = false; } if ($block['BlockMNProtocol'] == $maxprotocol) { $perminer[$minerkey]['BlocksPayedToCurrentProtocol'] += $block['BlockMNPayed']; if ($correctpayment) { $perminer[$minerkey]['BlocksPayedCorrectly']++; } } else { $perminer[$minerkey]['BlocksPayedToOldProtocol'] += $block['BlockMNPayed']; } } foreach ($perversion as $protocol => $info) { if ($protocol == 0) { $perversion[$protocol]['EstimatedMNDailyEarnings'] = 0; } else { if ($info['MasternodesPopulation'] != 0) { $perversion[$protocol]['EstimatedMNDailyEarnings'] = $info['Amount'] / $info['MasternodesPopulation']; } else { $perversion[$protocol]['EstimatedMNDailyEarnings'] = 0; } } $perversion[$protocol]['RatioBlocksAll'] = $info['Blocks'] / count($blocks); $perversion[$protocol]['RatioBlocksPayed'] = $info['BlocksPayed'] / count($blocks); $perversion[$protocol]['RatioBlocksPayedIncorrectRatio'] = $info['BlocksPayedIncorrectRatio'] / count($blocks); $perversion[$protocol]['RatioBlocksPayedCorrectRatio'] = $info['BlocksPayedCorrectRatio'] / count($blocks); } ksort($perversion, SORT_NUMERIC); $globalstats = array('Blocks' => count($blocks), 'BlocksPayed' => 0, 'BlocksPayedToCurrentProtocol' => 0, 'BlocksPayedCorrectly' => 0, 'SupplyAmount' => 0.0, 'MNPaymentsAmount' => 0.0); foreach ($perminer as $miner => $info) { $perminer[$miner]['RatioMNPayments'] = round($perminer[$miner]['MasternodeAmount'] / $perminer[$miner]['TotalAmount'], 3); $perminer[$miner]['RatioBlocksFound'] = $perminer[$miner]['Blocks'] / count($blocks); $perminer[$miner]['RatioBlocksPayed'] = $perminer[$miner]['BlocksPayed'] / $perminer[$miner]['Blocks']; $perminer[$miner]['RatioBlocksPayedToCurrentProtocol'] = $perminer[$miner]['BlocksPayedToCurrentProtocol'] / $perminer[$miner]['Blocks']; $perminer[$miner]['RatioBlocksPayedToOldProtocol'] = $perminer[$miner]['BlocksPayedToOldProtocol'] / $perminer[$miner]['Blocks']; $perminer[$miner]['RatioBlocksPayedCorrectly'] = $perminer[$miner]['BlocksPayedCorrectly'] / $perminer[$miner]['Blocks']; $globalstats['BlocksPayed'] += $perminer[$miner]['BlocksPayed']; $globalstats['BlocksPayedToCurrentProtocol'] += $perminer[$miner]['BlocksPayedToCurrentProtocol']; $globalstats['BlocksPayedCorrectly'] += $perminer[$miner]['BlocksPayedCorrectly']; $globalstats['SupplyAmount'] += $perminer[$miner]['TotalAmount']; $globalstats['MNPaymentsAmount'] += $perminer[$miner]['MasternodeAmount']; } if ($globalstats['Blocks'] != 0) { $globalstats['RatioBlocksPayed'] = $globalstats['BlocksPayed'] / $globalstats['Blocks']; $globalstats['RatioBlocksPayedToCurrentProtocol'] = $globalstats['BlocksPayedToCurrentProtocol'] / $globalstats['Blocks']; $globalstats['RatioBlocksPayedCorrectly'] = $globalstats['BlocksPayedCorrectly'] / $globalstats['Blocks']; } else { $globalstats['RatioBlocksPayed'] = 0; $globalstats['RatioBlocksPayedToCurrentProtocol'] = 0; $globalstats['RatioBlocksPayedCorrectly'] = 0; } if ($nodetail) { $blocks = array(); $perminer = array(); } $data = array('blocks' => $blocks, 'stats' => array('perversion' => $perversion, 'perminer' => $perminer, 'global' => $globalstats)); //Change the HTTP status $response->setStatusCode(200, "OK"); $response->setJsonContent(array('status' => 'OK', 'data' => $data)); file_put_contents($cachefnam, serialize($data), LOCK_EX); unlink($cachefnamupdate); } else { $response->setStatusCode(503, "Service Unavailable"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => $mysqli->errno . ': ' . $mysqli->error)); } } } return $response; });
/** * Mount all of the collections, which makes the routes active. */ foreach ($di->get('collections') as $collection) { $app->mount($collection); } /** * The base route return the list of defined routes for the application. * This is not strictly REST compliant, but it helps to base API documentation off of. * By calling this, you can quickly see a list of all routes and their methods. */ $app->get('/', function () use($app) { $routes = $app->getRouter()->getRoutes(); $routeDefinitions = array('GET' => array(), 'POST' => array(), 'PUT' => array(), 'PATCH' => array(), 'DELETE' => array(), 'HEAD' => array(), 'OPTIONS' => array()); foreach ($routes as $route) { $method = $route->getHttpMethods(); $routeDefinitions[$method][] = $route->getPattern(); } return $routeDefinitions; }); /** * After a route is run, usually when its Controller returns a final value, * the application runs the following function which actually sends the response to the client. * * The default behavior is to send the Controller's returned value to the client as JSON. * However, by parsing the request querystring's 'type' paramter, it is easy to install * different response type handlers. Below is an alternate csv handler. */ $app->after(function () use($app) { // OPTIONS have no body, send the headers, exit if ($app->request->getMethod() == 'OPTIONS') {
<?php $app = new Phalcon\Mvc\Micro(); $app->get('/say/hello/{name}', function ($name) { echo "Hello ", $name, "!"; }); $app->handle();
$loader = new \Phalcon\Loader(); $loader->registerNamespaces(['Example\\Models' => __DIR__ . '/../app/models', 'DataTables' => __DIR__ . '/../../src/']); $loader->register(); $di = new \Phalcon\DI\FactoryDefault(); $di->setShared('db', function () { return new \Phalcon\Db\Adapter\Pdo\Sqlite(['dbname' => __DIR__ . '/../db.sqlite']); }); $di->setShared('view', function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(__DIR__ . '/../app/views/'); $view->registerEngines(['.volt' => 'Phalcon\\Mvc\\View\\Engine\\Volt']); return $view; }); $app = new \Phalcon\Mvc\Micro($di); /** @noinspection PhpUndefinedMethodInspection */ $app->getRouter()->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); $app->get('/', function () use($app) { $app['view']->render('index.volt', []); }); $app->post('/example_querybuilder', function () use($app) { $builder = $app->getService('modelsManager')->createBuilder()->columns('id, name, email, balance')->from('Example\\Models\\User'); $dataTables = new \DataTables\DataTable(); $dataTables->fromBuilder($builder)->sendResponse(); }); $app->get('/example_resultset', function () use($app) { $resultset = $app->getService('modelsManager')->createQuery("SELECT * FROM \\Example\\Models\\User")->execute(); $dataTables = new \DataTables\DataTable(); $dataTables->fromResultSet($resultset)->sendResponse(); }); $app->handle();
<?php $app = new Phalcon\Mvc\Micro(); $app->get('/', function () { echo "<h1>Welcome!</h1>"; }); $app->get('/say/hello/{name}', function ($name) use($app) { echo "<h1>Hello! {$name}</h1>"; echo "Your IP Address is ", $app->request->getClientAddress(); }); $app->post('/store/something', function () use($app) { $name = $app->request->getPost('name'); echo "<h1>Hello! {$name}</h1>"; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo 'This is crazy, but this page was not found!'; }); $app->handle();
<?php $app = new Phalcon\Mvc\Micro(); //Retrieves all robots $app->get('/api/robots', function () { }); //Searches for robots with $name in their name $app->get('/api/robots/search/{name}', function ($name) { }); //Retrieves robots based on primary key $app->get('/api/robots/{id:[0-9]+}', function ($id) { }); //Adds a new robot $app->post('/api/robots', function () { }); //Updates robots based on primary key $app->put('/api/robots/{id:[0-9]+}', function () { }); //Deletes robots based on primary key $app->delete('/api/robots/{id:[0-9]+}', function () { }); $app->handle();