Ejemplo n.º 1
0
 public function __construct()
 {
     $view = new \Slim\Views\Twig();
     $app = new \Slim\Slim(array('debug' => DEBUG, 'view' => $view, 'templates.path' => HOME . '/' . APP . '/View'));
     $app->notFound(function () use($app) {
         $app->render('errors/404.html');
     });
     $controllerFactory = new \Core\ControllerFactory($app);
     // the class that builds the controllers
     $view->parserExtensions = array(new \MyTwigExtension($controllerFactory));
     $mainRoute = '/';
     if (!empty(SUB_FOLDER)) {
         // is the whole site in a subdirectory?
         $mainRoute .= SUB_FOLDER . '(/)';
     }
     $checkQueries = function ($q) {
         // our queries must be numerical for security's sake
         if (!empty($q)) {
             if (!is_numeric($q)) {
                 return false;
             }
             if ($q <= 0) {
                 return false;
             }
         }
         return true;
     };
     $app->group($mainRoute, function () use($app, $checkQueries, $controllerFactory) {
         // the admin route
         $app->map(ADMIN_FOLDER . '(/)(:controller)(/)(:action)(/)(:query)(/)', function ($controller = '', $action = '', $query = '') use($app, $checkQueries, $controllerFactory) {
             if (false === $checkQueries($query)) {
                 $app->notFound();
             } else {
                 $controllerFactory->buildController($controller, $action, true, $query);
             }
         })->via('POST', 'GET');
         // front end routing
         $app->map('(:controller)(/)(:action)(/)(:query)(/)(:query2)(/)', function ($controller = '', $action = '', $query = '', $query2 = '') use($app, $checkQueries, $controllerFactory) {
             if (false === $checkQueries($query) || false === $checkQueries($query2)) {
                 $app->notFound();
             } else {
                 $controllerFactory->buildController($controller, $action, false, $query, $query2);
             }
         })->via('POST', 'GET');
     });
     $app->run();
     // run Slim Application
 }
Ejemplo n.º 2
0
            $row = \FormAPI\AuthService::fetchRequester($payload->email, $payload->name);
            $jwt = \FormAPI\AuthService::generate($row['requester_id'], $row['email_address']);
            if (\FormAPI\AuthService::save($row['requester_id'], $jwt)) {
                $result['success'] = true;
                $result['jwt'] = $jwt;
                echo json_encode($result);
            } else {
                $result['success'] = false;
                $result['message'] = "Unable to save token to server cache";
                $response->setStatus(500);
                $response->setBody(json_encode($result));
            }
        } else {
            $result['success'] = false;
            $result['message'] = "Invalid Data, no email or name provided";
            $response->setStatus(400);
            $response->setbody(json_encode($result));
        }
    } else {
        //Bad Request
        $result['success'] = false;
        $result['message'] = "Invalid Data, could not decode JSON";
        $response->setStatus(400);
        $response->setBody(json_encode($result));
    }
});
//Grants Request Group Route
$app->group('/gr', function () use($app) {
    require_once "php/routes.php";
});
$app->run();
Ejemplo n.º 3
0
 $app->group('/nuovo', function () use($dati, $app) {
     $app->map('/articolo', function () use($dati, $app) {
         $app->render('forum/articoli.php', array('dati' => $dati, 'new' => true));
         if (fatto()) {
             $app->redirect($app->urlFor('articoli'));
         }
     })->via('GET', 'POST');
     $app->map('/articolo/:id', function ($id) use($dati, $app) {
         $app->render('forum/articoli.php', array('dati' => $dati, 'new' => true, 'categoria' => $id));
         if (fatto()) {
             $app->redirect($app->urlFor('articoli'));
         }
     })->via('GET', 'POST');
     if (isAdminUserAutenticate()) {
         $app->map('/categoria', function () use($dati, $app) {
             $app->render('forum/categorie.php', array('dati' => $dati, 'new' => true));
             if (fatto()) {
                 $app->redirect($app->urlFor('categorie'));
             }
         })->via('GET', 'POST');
         $app->map('/categoria/:id', function ($id) use($dati, $app) {
             $app->render('forum/categorie.php', array('dati' => $dati, 'new' => true, 'tipo' => $id));
             if (fatto()) {
                 $app->redirect($app->urlFor('categorie'));
             }
         })->via('GET', 'POST');
         $app->map('/tipo', function () use($dati, $app) {
             $app->render('forum/tipi.php', array('dati' => $dati, 'new' => true));
             if (fatto()) {
                 $app->redirect($app->urlFor('tipi'));
             }
         })->via('GET', 'POST');
     }
 });
Ejemplo n.º 4
0
    $data['most_schooladvices'] = array();
    foreach ($picked_advice as $picked_adv) {
        array_push($data['most_schooladvices'], $picked_adv);
    }
    // Get all users registered by day
    if ($school_id == null) {
        $users_by_day = User::groupBy('day')->get(array(new raw('DATE(created_at) as day'), new raw('count(id) as amount')));
    } else {
        $users_by_day = User::groupBy('day')->where('school_id', '=', $school_id)->get(array(new raw('DATE(created_at) as day'), new raw('count(id) as amount')));
    }
    $data['users']['created_by_day'] = $users_by_day->toArray();
    $app->render('dashboard.html', $data);
})->name('dashboard');
$app->group('/users', function () use($app, $data) {
    $app->get('/', function () use($app, $data) {
        $data['users'] = User::with('talents', 'educationLevel', 'skills', 'school')->orderBy('created_at', 'DESC')->get()->toArray();
        $app->render('users/overview.html', $data);
    })->name('users_overview');
});
$app->group('/talents', function () use($app, $data) {
    $app->get('/', function () use($app, $data) {
        $data['talents'] = Talent::all()->toArray();
        $app->render('talents/overview.html', $data);
    })->name('talents_overview');
    $app->map('/edit/:id', function ($id) use($app, $data) {
        $data['request_method'] = $app->request->getMethod();
        $talent = Talent::with('questions')->find($id);
        if ($app->request->isGet()) {
            $data['talent'] = $talent->toArray();
        } else {
            if ($app->request->isPost()) {
                foreach ($app->request->post('question') as $key => $value) {
Ejemplo n.º 5
0
$app->group('/api', 'APIRequest', function () use($app) {
    $app->get('/getLink/:id', function ($id) use($app) {
        $result = $app->api->getLinkById($id);
        if ($result != null) {
            $app->render(200, $result);
        } else {
            $app->render(404, array('error' => true, 'msg' => 'Link has not been found'));
        }
    })->conditions(array('id' => '\\d+'));
    $app->put('/addLink', function () use($app) {
        $putData = $app->request->put();
        if (array_key_exists('url', $putData)) {
            $url = $putData['url'];
            if ($app->api->validateUrl($url)) {
                if (strpos($url, $app->domain)) {
                    $app->render(200, array('msg' => 'Huehue, nice try! <img src="http://' . $app->domain . '/media/gfx/smtlikethis.jpg" alt="">', 'zonk' => true));
                    return;
                }
                $existingUrl = $app->api->getLinkByUrl($url);
                if ($existingUrl) {
                    $app->render(200, $existingUrl);
                } else {
                    $lastInsertId = $app->api->addLink($url);
                    $result = $app->api->getLinkById($lastInsertId);
                    $app->render(201, $result);
                }
            } else {
                $app->render(400, array('error' => true, 'msg' => 'Provided url is not in a valid form'));
            }
        } else {
            $app->render(400, array('error' => true, 'msg' => 'Parameter `url` must be set'));
        }
    });
});
Ejemplo n.º 6
0
$app->get('/', function () use($app) {
    $data = array('status' => '200');
    $app->render('default.php', $data, 200);
});
$app->group('/products', function () use($app) {
    //list
    //delete id
    //update id
    //ADD
    $app->post('/upload', function () use($app) {
        if (!isset($_FILES['file'])) {
            echo "No files uploaded!!";
            return;
        }
        $file = $_FILES['file'];
        if ($file['error'] !== 0) {
            echo "Error no upload!!";
            return;
        }
        $name = md5($file['tmp_name']) . '-' . $file['name'];
        if (move_uploaded_file($file['tmp_name'], '../images/products/' . $name) === true) {
            $image = array('url' => 'images/products/' . $name, 'name' => $file['name']);
        }
        $response = array();
        $response['image'] = $image;
        $app->render('default.php', $response, 200);
    });
});
$app->group('/users', function () use($app) {
    //login
    //rota para a home
    $app->get('/', function () use($app) {
Ejemplo n.º 7
0
$app->response->headers->set('Content-Type', 'application/json;charset=utf-8');
$app->etag(md5(time()));
// Define path & URL
$req = $app->request;
define('ROOT', $req->getPath());
define('URL', $req->getUrl());
// Bookings
$app->group('/booking', function () use($app, $log) {
    // Returns the details of all current and future bookings
    $app->get("/all", function () use($app, $log) {
        Booking::all($app);
    });
    // Returns the details of the next bookings for room number of :room
    $app->get("/next/:room", function ($room) use($app, $log) {
        Booking::next($app, $room);
    });
    // Returns the details of the booking an id of :id
    $app->get("/:id", function ($id) use($app, $log) {
        Booking::get($app, $id);
    });
    // Create booking & return success or failure
    $app->post("/create", function ($title, $room, $creator, $from, $to, $notes, $attendees, $guests) use($app, $log) {
        Booking::create($app, $details);
    });
});
// Statistics
$app->group('/statistics', function () use($app, $log) {
    // Return total amount of bookings managed by the system
    $app->get("/bookings", function () use($app, $log) {
        Statistics::bookings($app);
    });
});
Ejemplo n.º 8
0
$app->group('/api', function () use($app) {
    $app->group('/v0', function () use($app) {
        $app->get('/bgp', 'authToken', 'list_bgp')->name('list_bgp');
        // api/v0/bgp
        $app->get('/oxidized', 'authToken', 'list_oxidized')->name('list_oxidized');
        $app->group('/devices', function () use($app) {
            $app->delete('/:hostname', 'authToken', 'del_device')->name('del_device');
            // api/v0/devices/$hostname
            $app->get('/:hostname', 'authToken', 'get_device')->name('get_device');
            // api/v0/devices/$hostname
            $app->patch('/:hostname', 'authToken', 'update_device')->name('update_device_field');
            $app->get('/:hostname/vlans', 'authToken', 'get_vlans')->name('get_vlans');
            // api/v0/devices/$hostname/vlans
            $app->get('/:hostname/graphs', 'authToken', 'get_graphs')->name('get_graphs');
            // api/v0/devices/$hostname/graphs
            $app->get('/:hostname/ports', 'authToken', 'get_port_graphs')->name('get_port_graphs');
            $app->get('/:hostname/port_stack', 'authToken', 'get_port_stack')->name('get_port_stack');
            // api/v0/devices/$hostname/ports
            $app->get('/:hostname/components', 'authToken', 'get_components')->name('get_components');
            $app->post('/:hostname/components/:type', 'authToken', 'add_components')->name('add_components');
            $app->put('/:hostname/components', 'authToken', 'edit_components')->name('edit_components');
            $app->delete('/:hostname/components/:component', 'authToken', 'delete_components')->name('delete_components');
            $app->get('/:hostname/groups', 'authToken', 'get_device_groups')->name('get_device_groups');
            $app->get('/:hostname/:type', 'authToken', 'get_graph_generic_by_hostname')->name('get_graph_generic_by_hostname');
            // api/v0/devices/$hostname/$type
            $app->get('/:hostname/ports/:ifname', 'authToken', 'get_port_stats_by_port_hostname')->name('get_port_stats_by_port_hostname');
            // api/v0/devices/$hostname/ports/$ifName
            $app->get('/:hostname/ports/:ifname/:type', 'authToken', 'get_graph_by_port_hostname')->name('get_graph_by_port_hostname');
            // api/v0/devices/$hostname/ports/$ifName/$type
        });
        $app->get('/devices', 'authToken', 'list_devices')->name('list_devices');
        // api/v0/devices
        $app->post('/devices', 'authToken', 'add_device')->name('add_device');
        // api/v0/devices (json data needs to be passed)
        $app->group('/devicegroups', function () use($app) {
            $app->get('/:name', 'authToken', 'get_devices_by_group')->name('get_devices_by_group');
        });
        $app->get('/devicegroups', 'authToken', 'get_device_groups')->name('get_devicegroups');
        $app->group('/portgroups', function () use($app) {
            $app->get('/:group', 'authToken', 'get_graph_by_portgroup')->name('get_graph_by_portgroup');
            // api/v0/portgroups/$group
        });
        $app->group('/bills', function () use($app) {
            $app->get('/:bill_id', 'authToken', 'list_bills')->name('get_bill');
            // api/v0/bills/$bill_id
        });
        $app->get('/bills', 'authToken', 'list_bills')->name('list_bills');
        // api/v0/bills
        // /api/v0/alerts
        $app->group('/alerts', function () use($app) {
            $app->get('/:id', 'authToken', 'list_alerts')->name('get_alert');
            // api/v0/alerts
            $app->put('/:id', 'authToken', 'ack_alert')->name('ack_alert');
            // api/v0/alerts/$id (PUT)
            $app->put('/unmute/:id', 'authToken', 'unmute_alert')->name('unmute_alert');
            // api/v0/alerts/unmute/$id (PUT)
        });
        $app->get('/alerts', 'authToken', 'list_alerts')->name('list_alerts');
        // api/v0/alerts
        // /api/v0/rules
        $app->group('/rules', function () use($app) {
            $app->get('/:id', 'authToken', 'list_alert_rules')->name('get_alert_rule');
            // api/v0/rules/$id
            $app->delete('/:id', 'authToken', 'delete_rule')->name('delete_rule');
            // api/v0/rules/$id (DELETE)
        });
        $app->get('/rules', 'authToken', 'list_alert_rules')->name('list_alert_rules');
        // api/v0/rules
        $app->post('/rules', 'authToken', 'add_edit_rule')->name('add_rule');
        // api/v0/rules (json data needs to be passed)
        $app->put('/rules', 'authToken', 'add_edit_rule')->name('edit_rule');
        // api/v0/rules (json data needs to be passed)
        // Inventory section
        $app->group('/inventory', function () use($app) {
            $app->get('/:hostname', 'authToken', 'get_inventory')->name('get_inventory');
        });
        // End Inventory
        // Routing section
        $app->group('/routing', function () use($app) {
            $app->group('/ipsec', function () use($app) {
                $app->get('/data/:hostname', 'authToken', 'list_ipsec')->name('list_ipsec');
            });
        });
        // End Routing
        // Resources section
        $app->group('/resources', function () use($app) {
            $app->group('/ip', function () use($app) {
                $app->get('/arp/:ip', 'authToken', 'list_arp')->name('list_arp');
            });
        });
        // End Resources
        // Service section
        $app->group('/services', function () use($app) {
            $app->get('/:hostname', 'authToken', 'list_services')->name('get_service_for_host');
        });
        $app->get('/services', 'authToken', 'list_services')->name('list_services');
        // End Service
    });
    $app->get('/v0', 'authToken', 'show_endpoints');
    // api/v0
});
Ejemplo n.º 9
0
    foreach ($repos as $repo) {
        echo '<a href="/api/' . $uname . '/' . $repo->name . '">' . $repo->name . '</a><br>';
    }
    echo '<br><br><a href="/">Search Again</a>';
});
// group for api; preparing for when more methods are added
$app->group('/api', function () use($app) {
    // print out repos for user provided
    $app->get('/:username', function ($username) {
        $repos = getUserRepos($username);
        echo 'Current repos for user ' . $username . ':<br>';
        foreach ($repos as $repo) {
            echo '<a href="/api/' . $username . '/' . $repo->name . '">' . $repo->name . '</a><br>';
        }
        echo '<br><br><a href="/">Search Again</a>';
    });
    // print out commits from the provided repo
    $app->get('/:username/:repo', function ($username, $repo) {
        $client = new Client(['base_uri' => 'https://api.github.com/']);
        // get user commits
        $response = $client->request("GET", "repos/{$username}/{$repo}/commits");
        $commits = json_decode($response->getBody());
        echo "Commits for the {$repo} repo by user {$username}:" . '<br><br>';
        foreach ($commits as $commit) {
            echo $commit->commit->message . '<br>';
        }
        echo '<br><br><a href="/api/' . $username . '">Back to Repos</a>';
        echo '<br><br><a href="/">Start Over</a>';
    });
});
$app->run();
Ejemplo n.º 10
0
});
$app->group('/nucleus', function () use($app) {
    $app->get('/', function () use($app) {
        $nuclei = Nucleus::valid()->with(['sets' => function ($q) {
            $q->where('is_valid', '=', '1');
        }])->get();
        $res = $app->response();
        $res['Content-Type'] = 'application/json';
        $res->body($nuclei);
    });
    $app->get('/:id', function ($id) use($app) {
        //      $nucleus = Nucleus::find($id);
        $ids = explode(';', $id);
        $nucleus = Nucleus::whereIn('id', $ids)->with(['sets' => function ($q) {
            $q->where('is_valid', '=', '1');
        }])->get();
        $res = $app->response();
        $res['Content-Type'] = 'application/json';
        $res->body($nucleus);
    });
    $app->get('/:id/sets', function ($id) use($app) {
        $ids = explode(';', $id);
        $sets = Set::whereHas('nucleus', function ($q) use($ids) {
            $q->whereIn('id', $ids);
        })->valid()->get();
        $res = $app->response();
        $res['Content-Type'] = 'application/json';
        $res->body($sets);
    });
});
$app->group('/set(s)', function () use($app) {
Ejemplo n.º 11
0
$app->group('/api', function () use($app) {
    $app->group('/v0', function () use($app) {
        $app->get('/bgp', 'authToken', 'list_bgp')->name('list_bgp');
        // api/v0/bgp
        $app->get('/oxidized', 'authToken', 'list_oxidized')->name('list_oxidized');
        $app->group('/devices', function () use($app) {
            $app->delete('/:hostname', 'authToken', 'del_device')->name('del_device');
            // api/v0/devices/$hostname
            $app->get('/:hostname', 'authToken', 'get_device')->name('get_device');
            // api/v0/devices/$hostname
            $app->get('/:hostname/vlans', 'authToken', 'get_vlans')->name('get_vlans');
            // api/v0/devices/$hostname/vlans
            $app->get('/:hostname/graphs', 'authToken', 'get_graphs')->name('get_graphs');
            // api/v0/devices/$hostname/graphs
            $app->get('/:hostname/ports', 'authToken', 'get_port_graphs')->name('get_port_graphs');
            // api/v0/devices/$hostname/ports
            $app->get('/:hostname/:type', 'authToken', 'get_graph_generic_by_hostname')->name('get_graph_generic_by_hostname');
            // api/v0/devices/$hostname/$type
            $app->get('/:hostname/ports/:ifname', 'authToken', 'get_port_stats_by_port_hostname')->name('get_port_stats_by_port_hostname');
            // api/v0/devices/$hostname/ports/$ifName
            $app->get('/:hostname/ports/:ifname/:type', 'authToken', 'get_graph_by_port_hostname')->name('get_graph_by_port_hostname');
            // api/v0/devices/$hostname/ports/$ifName/$type
        });
        $app->get('/devices', 'authToken', 'list_devices')->name('list_devices');
        // api/v0/devices
        $app->post('/devices', 'authToken', 'add_device')->name('add_device');
        // api/v0/devices (json data needs to be passed)
        $app->group('/portgroups', function () use($app) {
            $app->get('/:group', 'authToken', 'get_graph_by_portgroup')->name('get_graph_by_portgroup');
            // api/v0/portgroups/$group
        });
        $app->group('/bills', function () use($app) {
            $app->get('/:bill_id', 'authToken', 'list_bills')->name('get_bill');
            // api/v0/bills/$bill_id
        });
        $app->get('/bills', 'authToken', 'list_bills')->name('list_bills');
        // api/v0/bills
        // /api/v0/alerts
        $app->group('/alerts', function () use($app) {
            $app->get('/:id', 'authToken', 'list_alerts')->name('get_alert');
            // api/v0/alerts
            $app->put('/:id', 'authToken', 'ack_alert')->name('ack_alert');
            // api/v0/alerts/$id (PUT)
        });
        $app->get('/alerts', 'authToken', 'list_alerts')->name('list_alerts');
        // api/v0/alerts
        // /api/v0/rules
        $app->group('/rules', function () use($app) {
            $app->get('/:id', 'authToken', 'list_alert_rules')->name('get_alert_rule');
            // api/v0/rules/$id
            $app->delete('/:id', 'authToken', 'delete_rule')->name('delete_rule');
            // api/v0/rules/$id (DELETE)
        });
        $app->get('/rules', 'authToken', 'list_alert_rules')->name('list_alert_rules');
        // api/v0/rules
        $app->post('/rules', 'authToken', 'add_edit_rule')->name('add_rule');
        // api/v0/rules (json data needs to be passed)
        $app->put('/rules', 'authToken', 'add_edit_rule')->name('edit_rule');
        // api/v0/rules (json data needs to be passed)
        // Inventory section
        $app->group('/inventory', function () use($app) {
            $app->get('/:hostname', 'authToken', 'get_inventory')->name('get_inventory');
        });
        // End Inventory
    });
    $app->get('/v0', 'authToken', 'show_endpoints');
    // api/v0
});
Ejemplo n.º 12
0
$app->group('/api/v1', $authenticate, function () use($app, $player, $game) {
    $app->get('/hello/:name', function ($name) {
        echo json_encode("{'name':{$name}}");
    })->name("route with params");
    $app->map('/players', function () use($player) {
        $players = $player->get_players();
        if ($players) {
            echo json_encode($players);
        } else {
            echo $player->last_error();
        }
    })->via('GET', 'POST');
    $app->map('/getPlayers', function () use($player) {
        $players = $player->get_players();
        if ($players) {
            echo json_encode($players);
        } else {
            echo $player->last_error();
        }
    })->via('GET', 'POST');
    $app->get('/getgame/:id', function () use($app, $game) {
        //serve up mock data for game
        $board = file_get_contents("./monopolyData.json");
        $mockData = array("title" => "Mock Game", "turn" => 10, "balance" => 524, "currentPlayerTurn" => "Stuart", "board" => json_decode($board));
        echo json_encode($mockData);
    })->name("get the current state of a game by id");
    $app->get('/getgames', function () use($app, $game) {
        $header = json_decode($app->request->headers->get('x-auth-token'));
        $games = $game->get_games(intval($header->player_id));
        echo json_encode($games);
    })->name("get all games by a particular player");
    $app->get('/getallgames', function () use($app, $game) {
        $header = json_decode($app->request->headers->get('x-auth-token'));
        $games = $game->get_all_games();
        echo json_encode($games);
    })->name("get all games available");
    $app->post('/creategame', function () use($app, $game) {
        $postData = json_decode($app->request->getBody(), true);
        // Validate POST variables
        if ($postData['name'] === NULL) {
            echo "Missing information";
        } else {
            $newGame = $game->create_game($postData['name']);
            if ($newGame) {
                echo $newGame;
            } else {
                echo $game->last_error();
            }
        }
    });
});
Ejemplo n.º 13
0
Archivo: index.php Proyecto: TM30/api
$app->group('/api', function () use($app, $userController, $platformController) {
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    //CONTACTS
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    $app->get('/users', function () use($app, $userController) {
        if (file_exists("users.json")) {
            echo file_get_contents('users.json');
            return;
        }
        echo $data = json_encode($userController->fetchAllUsers());
        file_put_contents('users.json', $data);
    });
    $app->get('/user/:id', function ($id) use($app, $userController) {
        $user = $userController->fetchUser(intval($id));
        echo json_encode($user[0]);
    })->conditions(array("id" => "[0-9]+"));
    $app->get('/user/:email', function ($email) use($app, $userController) {
        $email = str_replace('%', '.', $email);
        $user = $userController->fetchUserByMail($email);
        echo json_encode($user[0]->id);
    });
    $app->post('/user', function () use($app, $userController) {
        $username = $app->request->post('name');
        $username = filter_var($username, FILTER_SANITIZE_STRING);
        $email = $app->request->post('email');
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        $role = $app->request->post('role');
        /*$role = intval($role);*/
        $password = $app->request->post('password');
        $userController->createUser(array("name" => $username, "email" => $email, "role" => $role, "password" => $password));
        file_put_contents('users.json', json_encode($userController->fetchAllUsers()));
        echo json_encode(array('message' => "User has been created  successfully.."));
    });
    $app->put('/user/:id', function ($id) use($app, $userController) {
        $username = $app->request->post('name');
        $username = filter_var($username, FILTER_SANITIZE_STRING);
        $email = $app->request->post('email');
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        $role = $app->request->post('role');
        /*$role = intval($role);*/
        $password = $app->request->post('password');
        $fieldsToUpdate = array();
        if ($username) {
            $fieldsToUpdate['name'] = $username;
        }
        if ($email) {
            $fieldsToUpdate['email'] = $email;
        }
        if ($role) {
            $fieldsToUpdate['role'] = $role;
        }
        if ($password) {
            $fieldsToUpdate['password'] = $password;
        }
        $userController->updateUser($fieldsToUpdate, intval($id));
        file_put_contents('users.json', json_encode($userController->fetchAllUsers()));
        echo json_encode(array('message' => "user updated successfully.."));
    });
    $app->delete('/user/:id', function ($id) use($app, $userController) {
        $userController->removeUser(intval($id));
        file_put_contents('users.json', json_encode($userController->fetchAllUsers()));
        echo json_encode(array('message' => "User Deleted Successfully..."));
    });
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    //PLATFORMS
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    $app->get("/platforms", function () use($app, $platformController) {
        if (file_exists("platforms.json")) {
            echo file_get_contents('platforms.json');
            return;
        }
        echo $data = json_encode($platformController->fetchAllPlatforms());
        file_put_contents('platforms.json', $data);
    });
    $app->get("/platform/:id", function ($id) use($app, $platformController) {
        $platform = $platformController->fetchPlatforms(intval($id));
        echo json_encode($platform[0]);
    });
    $app->post("/platform", function () use($app, $platformController) {
        $name = $app->request->post('name');
        $name = filter_var($name, FILTER_SANITIZE_STRING);
        $bl_gate = $app->request->post('bl_gate');
        $bl_gate = filter_var($bl_gate, FILTER_VALIDATE_URL);
        $bc_gate = $app->request->post('bc_gate');
        $bc_gate = filter_var($bc_gate, FILTER_VALIDATE_URL);
        $sev_app = $app->request->post('sev_app');
        $sev_app = filter_var($sev_app, FILTER_VALIDATE_URL);
        $tech_admin_email = $app->request->post('tech_admin_email');
        $tech_admin_email = filter_var($tech_admin_email, FILTER_VALIDATE_EMAIL);
        $ops_admin_email = $app->request->post('ops_admin_email');
        $ops_admin_email = filter_var($ops_admin_email, FILTER_VALIDATE_EMAIL);
        $gen_admin_email = $app->request->post('gen_admin_email');
        $gen_admin_email = filter_var($gen_admin_email, FILTER_VALIDATE_EMAIL);
        $ipAddress = $app->request->post('ip_address');
        $ipAddress = filter_var($ipAddress, FILTER_SANITIZE_STRING);
        $platformController->createPlatform(array("name" => $name, "ip_address" => $ipAddress, "bl_gate" => $bl_gate, "bc_gate" => $bc_gate, "sev_app" => $sev_app, "tech_admin_email" => $tech_admin_email, "ops_admin_email" => $ops_admin_email, "gen_admin_email" => $gen_admin_email));
        file_put_contents('platforms.json', json_encode($platformController->fetchAllPlatforms()));
        echo json_encode(array('message' => "Platform has been created  successfully.."));
    });
    $app->put("/platform/:id", function ($id) use($app, $platformController) {
        $name = $app->request->post('name');
        $name = filter_var($name, FILTER_SANITIZE_STRING);
        $bl_gate = $app->request->post('bl_gate');
        $bl_gate = filter_var($bl_gate, FILTER_VALIDATE_URL);
        $bc_gate = $app->request->post('bc_gate');
        $bc_gate = filter_var($bc_gate, FILTER_VALIDATE_URL);
        $sev_app = $app->request->post('sev_app');
        $sev_app = filter_var($sev_app, FILTER_VALIDATE_URL);
        $tech_admin_email = $app->request->post('tech_admin_email');
        $tech_admin_email = filter_var($tech_admin_email, FILTER_VALIDATE_EMAIL);
        $ops_admin_email = $app->request->post('ops_admin_email');
        $ops_admin_email = filter_var($ops_admin_email, FILTER_VALIDATE_EMAIL);
        $gen_admin_email = $app->request->post('gen_admin_email');
        $gen_admin_email = filter_var($gen_admin_email, FILTER_VALIDATE_EMAIL);
        $ipAddress = $app->request->post('ip_address');
        $ipAddress = filter_var($ipAddress, FILTER_SANITIZE_STRING);
        $fieldsToUpdate = array();
        if ($name) {
            $fieldsToUpdate['name'] = $name;
        }
        if ($bl_gate) {
            $fieldsToUpdate['bl_gate'] = $bl_gate;
        }
        if ($bc_gate) {
            $fieldsToUpdate['bc_gate'] = $bc_gate;
        }
        if ($sev_app) {
            $fieldsToUpdate['sev_app'] = $sev_app;
        }
        if ($tech_admin_email) {
            $fieldsToUpdate['tech_admin_email'] = $tech_admin_email;
        }
        if ($ops_admin_email) {
            $fieldsToUpdate['ops_admin_email'] = $ops_admin_email;
        }
        if ($gen_admin_email) {
            $fieldsToUpdate['gen_admin_email'] = $gen_admin_email;
        }
        if ($ipAddress) {
            $fieldsToUpdate['ip_address'] = $ipAddress;
        }
        $platformController->updatePlatform($fieldsToUpdate, intval($id));
        file_put_contents('platforms.json', json_encode($platformController->fetchAllPlatforms()));
        echo json_encode(array('message' => "Platform has been updated  successfully.."));
    });
    $app->delete("/platform/:id", function ($id) use($app, $platformController) {
        $platformController->removePlatform(intval($id));
        file_put_contents('platforms.json', json_encode($platformController->fetchAllPlatforms()));
        echo json_encode(array('message' => "Platform has been deleted successfully.."));
    });
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    //STATUSES
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    $app->get("/status/:platform/:module", function ($platformName, $moduleId) use($app) {
        $statusController = new \Controller\StatusController($platformName, 8585, $moduleId);
        echo json_encode($statusController->getStatus());
    });
    $app->get("/uptime/:platform", function ($platform) use($app) {
        $status = \Controller\StatusController::getSevassAppStatus($platform);
        echo json_encode($status);
    });
});
Ejemplo n.º 14
0
$app->group("/api", function () use($app) {
    $app->group("/downloader", function () use($app) {
        $app->post("/begin", function () use($app) {
            $json = array();
            $json['success'] = true;
            $url = $app->request->post('url');
            $format = $app->request->post('format');
            $email = $app->request->post('email');
            $resume = $app->request->post('resume');
            $currentId = $app->request->post('currentId');
            if (isset($_SESSION['currentId']) && $currentId != $_SESSION['currentId']) {
                $json['success'] = false;
                $json['message'] = "A new session has been started in a different window! Please switch to the new session or refresh the page.";
            } else {
                if ($resume != null) {
                    $json['downloads'] = $_SESSION['downloads'];
                } else {
                    if (!empty($url) && !empty($format)) {
                        try {
                            $story = getInfo($url);
                            $download = array('id' => uniqid(), 'story' => (array) $story, 'currentChapter' => 1, 'totalChapters' => $story->chapters, 'format' => $format, 'email' => $email == null ? '' : $email, 'status' => Status::PENDING, 'statusMessage' => '', 'fileName' => '', 'timestamp' => time());
                            $_SESSION['downloads'][$download['id']] = $download;
                            $json['downloads'] = $_SESSION['downloads'];
                        } catch (FicSaveException $ex) {
                            $json['success'] = false;
                            $json['message'] = $ex->getMessage();
                        }
                    } else {
                        $json['success'] = false;
                        $json['message'] = "URL cannot be empty!";
                    }
                }
            }
            $app->response()->headers()->set('Content-Type', 'application/json');
            $app->response()->body(json_encode($json));
        });
        $app->post("/process", function () use($app) {
            ini_set('memory_limit', '512M');
            $json = array();
            $json['success'] = true;
            $currentId = $app->request->post('currentId');
            if (isset($_SESSION['currentId']) && $currentId != $_SESSION['currentId']) {
                $json['success'] = false;
                $json['message'] = "Downloading has been resumed in a different window!";
            } else {
                $activeDownloads = 0;
                $activeBuilds = 0;
                foreach ($_SESSION['downloads'] as &$download) {
                    if ($download['status'] == Status::PENDING) {
                        $download['status'] = Status::DOWNLOADING;
                        $_SESSION[$download['id']] = array();
                    } else {
                        if ($download['status'] == Status::DOWNLOADING) {
                            if ($activeDownloads >= 3) {
                                continue;
                            }
                            $activeDownloads++;
                            try {
                                $_SESSION[$download['id']][] = (array) getChapter($download['story']['url'], $download['currentChapter'], $download['story']['metadata']);
                                if ($download['currentChapter'] == $download['totalChapters']) {
                                    $download['status'] = Status::DOWNLOAD_COMPLETE;
                                } else {
                                    $download['currentChapter']++;
                                }
                            } catch (Exception $ex) {
                                $app->getLog()->error($ex);
                                $download['status'] = Status::ERROR;
                                $download['statusMessage'] = "Failed to download chapter {$download['currentChapter']}.";
                                unset($_SESSION[$download['id']]);
                            }
                        } else {
                            if ($download['status'] == Status::DOWNLOAD_COMPLETE) {
                                $download['status'] = Status::BUILDING;
                            } else {
                                if ($download['status'] == Status::BUILDING) {
                                    if ($activeBuilds >= 1) {
                                        continue;
                                    }
                                    $activeBuilds++;
                                    try {
                                        $book = new \PHPePub\Core\EPub();
                                        $book->setTitle($download['story']['title']);
                                        $book->setAuthor($download['story']['author'], $download['story']['author']);
                                        $book->setIdentifier($download['id'], PHPePub\Core\EPub::IDENTIFIER_UUID);
                                        $book->setSourceURL($download['story']['url']);
                                        if (!empty($download['story']['description'])) {
                                            $book->setDescription($download['story']['description']);
                                        }
                                        $contentStart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n" . "    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" . "<head>" . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" . "<title>" . $download['story']['title'] . "</title>\n" . "<style type=\"text/css\">\n" . "body{font-family:'Arial',sans-serif;}\n" . "</style>\n" . "</head>\n" . "<body>\n";
                                        $contentEnd = "</body>\n</html>\n";
                                        $book->addChapter($download['story']['title'] . " by " . $download['story']['author'], 'Cover.html', $contentStart . '<div style="text-align: center;">' . '<h1>' . htmlspecialchars($download['story']['title']) . '</h1>' . '<h3><i>by ' . $download['story']['author'] . '</i></h3>' . '<div style="text-align: left;">' . $download['story']['description'] . '</div>' . '<div style="text-align: left;">URL: <a href="' . $download['story']['url'] . '">' . $download['story']['url'] . '</a></div>' . '</div>' . $contentEnd);
                                        if ($download['totalChapters'] > 1) {
                                            $book->buildTOC();
                                        }
                                        foreach ($_SESSION[$download['id']] as $chapter) {
                                            $chapterTitle = htmlspecialchars($chapter['title']);
                                            if ($book->addChapter($chapterTitle, $book->sanitizeFileName($chapter['title']) . ".html", $contentStart . '<h2 style="text-align: center;">' . $chapterTitle . '</h2>' . PHP_EOL . '<div>' . PHP_EOL . $chapter['content'] . PHP_EOL . '</div>' . $contentEnd) === FALSE) {
                                                $download['status'] = Status::ERROR;
                                                $download['statusMessage'] = "Failed to generate chapter {$chapter['number']} of eBook.";
                                                unset($_SESSION[$download['id']]);
                                                break;
                                            }
                                        }
                                        if ($download['status'] != Status::ERROR) {
                                            if ($book->finalize()) {
                                                $fileName = $download['id'] . "_" . $download['story']['title'] . " - " . $download['story']['author'];
                                                $filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . "tmp";
                                                if ($book->saveBook($fileName, $filePath) === FALSE) {
                                                    $download['status'] = Status::ERROR;
                                                    $download['statusMessage'] = "Failed to generate eBook.";
                                                    unset($_SESSION[$download['id']]);
                                                } else {
                                                    $download['fileName'] = $book->sanitizeFileName($fileName);
                                                    $fileNameWithPath = $filePath . DIRECTORY_SEPARATOR . $download['fileName'];
                                                    if ($download['format'] != 'epub') {
                                                        if (file_exists("{$fileNameWithPath}.{$download['format']}")) {
                                                            $app->getLog()->warn("{$fileNameWithPath}.{$download['format']} already exists, waiting for build to complete...");
                                                        } else {
                                                            set_time_limit(0);
                                                            try {
                                                                // set UTF8-encoding for foreign characters
                                                                $locale = 'en_US.UTF-8';
                                                                setlocale(LC_ALL, $locale);
                                                                putenv('LC_ALL=' . $locale);
                                                                $result = exec("ebook-convert {$fileNameWithPath}.epub {$fileNameWithPath}.{$download['format']} --margin-left 36 --margin-right 36 --margin-top 36 --margin-bottom 36 2>&1", $output);
                                                                if (strpos($result, 'saved to') === FALSE) {
                                                                    $app->getLog()->error("Could not save file.");
                                                                    $app->getLog()->error($output);
                                                                    $download['status'] = Status::ERROR;
                                                                    $download['statusMessage'] = "Failed to convert eBook to requested format.";
                                                                    unset($_SESSION[$download['id']]);
                                                                } else {
                                                                    if (strpos($result, 'Killed') !== FALSE) {
                                                                        $app->getLog()->error("Not enough memory.");
                                                                        $app->getLog()->error($output);
                                                                        $download['status'] = Status::ERROR;
                                                                        $download['statusMessage'] = "Failed to convert eBook to requested format. File may be too large.";
                                                                        unset($_SESSION[$download['id']]);
                                                                    } else {
                                                                        unlink($fileNameWithPath . '.epub');
                                                                    }
                                                                }
                                                            } catch (Exception $ex) {
                                                                $download['status'] = Status::ERROR;
                                                                $download['statusMessage'] = "Failed to convert eBook to requested format. Please try again later.";
                                                            }
                                                        }
                                                    }
                                                    if ($download['status'] != Status::ERROR) {
                                                        if (empty($download['email'])) {
                                                            $download['status'] = Status::DONE;
                                                        } else {
                                                            if (mailAttachment($download['id'], $download['fileName'] . '.' . $download['format'], $filePath, $download['email'])) {
                                                                $download['status'] = Status::EMAILED;
                                                                unlink($fileNameWithPath . '.' . $download['format']);
                                                            } else {
                                                                $download['status'] = Status::ERROR;
                                                                $download['statusMessage'] = "Failed to send email!";
                                                            }
                                                            unset($_SESSION[$download['id']]);
                                                        }
                                                    }
                                                }
                                            } else {
                                                $download['status'] = Status::ERROR;
                                                $download['statusMessage'] = "Failed to finalize eBook generation.";
                                                unset($_SESSION[$download['id']]);
                                            }
                                        }
                                    } catch (Exception $ex) {
                                        $app->getLog()->error($ex);
                                        $download['status'] = Status::ERROR;
                                        $download['statusMessage'] = "Failed to build eBook.";
                                        unset($_SESSION[$download['id']]);
                                    }
                                } else {
                                    if ($download['status'] >= Status::DONE) {
                                        $fileName = "{$download['fileName']}.{$download['format']}";
                                        $fileNameWithPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . "tmp" . DIRECTORY_SEPARATOR . $fileName;
                                        if (!file_exists($fileNameWithPath) && $download['status'] != Status::EMAILED) {
                                            unset($_SESSION['downloads'][$download['id']]);
                                        }
                                    } else {
                                        if ($download['status'] == Status::ERROR) {
                                            unset($_SESSION['downloads'][$download['id']]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                $json['downloads'] = $_SESSION['downloads'];
            }
            $app->response()->headers()->set('Content-Type', 'application/json');
            $app->response()->body(json_encode($json));
        });
    });
    $app->group("/donation", function () use($app) {
        $app->post("/paypal/new", function () use($app) {
            // http://ficsave.com/api/donation/paypal/new
            require 'include/custom/ipn/paypal.php';
        });
    });
});
Ejemplo n.º 15
0
$app->group(rtrim($app->config('product_path'), '/'), function () use($app) {
    $app->get('/', function () use($app) {
        unset($_SESSION['project']);
        unset($_SESSION['sheetData']);
        //connect to mongo
        $mongoCollection = getMongoCollection('project');
        $get = $app->request->get();
        //list
        $list['creator'] = $mongoCollection->distinct('dct:creator');
        $list['tag'] = $mongoCollection->distinct('eg:tag');
        $list['license'] = $mongoCollection->distinct('dct:license');
        //count
        foreach ($list['creator'] as $key => $value) {
            if (is_string($value)) {
                $list['creator_count'][$key] = $mongoCollection->count(array('dct:creator' => $value));
            }
        }
        foreach ($list['tag'] as $key => $value) {
            if (is_string($value)) {
                $list['tag_count'][$key] = $mongoCollection->count(array('eg:tag' => $value));
            }
        }
        foreach ($list['license'] as $key => $value) {
            if (is_string($value)) {
                $list['license_count'][$key] = $mongoCollection->count(array('dct:license' => $value));
            }
        }
        //search
        $conditions = array();
        $creator = '';
        if (isset($get['creator']) && is_string($get['creator']) && in_array($get['creator'], $list['creator'])) {
            $creator = $get['creator'];
            $conditions['$and'][] = array('dct:creator' => $creator);
        }
        $tag = '';
        if (isset($get['tag']) && is_string($get['tag']) && in_array($get['tag'], $list['tag'])) {
            $tag = $get['tag'];
            $conditions['$and'][] = array('eg:tag' => $tag);
        }
        $license = '';
        if (isset($get['license']) && is_string($get['license']) && array_key_exists($get['license'], $app->config('license'))) {
            $license = $get['license'];
            $conditions['$and'][] = array('dct:license' => $license);
        }
        $keyword = '';
        if (isset($get['keyword']) && is_string($get['keyword'])) {
            $keyword = $get['keyword'];
            $regex = new MongoRegex('/' . preg_quote($keyword) . '/');
            $conditions['$and'][] = array('$or' => array(array('eg:keyword' => $regex), array('dct:description' => $regex), array('rdfs:label' => $regex)));
        }
        $cursor = $mongoCollection->find($conditions);
        $cursor->sort(array('dct:created' => -1));
        //paging
        $count = $cursor->count();
        $cursor->limit($app->config('perpage'));
        if (isset($get['page']) && (int) $get['page'] > 0) {
            $cursor->skip($app->config('perpage') * ((int) $get['page'] - 1));
        }
        $results = array();
        foreach ($cursor as $document) {
            $results[] = $document;
        }
        $path = $app->request()->getPath();
        $perpage = $app->config('perpage');
        $app->render('index.php', compact('list', 'results', 'count', 'creator', 'tag', 'license', 'keyword', 'path', 'perpage'));
    });
    $app->get('/complete', function () use($app) {
        $app->render('complete.php');
    });
    $app->get('/login', function () use($app) {
        $app->render('login.php');
    });
    $app->post('/login', function () use($app) {
        try {
            $post = $app->request->post();
            if (!(isset($post['email']) && is_string($post['email']) && isset($post['password']) && is_string($post['password']))) {
                throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります');
            }
            $mongoCollection = getMongoCollection('user');
            foreach ($post as $key => $value) {
                $encode = mb_detect_encoding($value, array('UTF-8'));
                if ($encode !== 'UTF-8') {
                    throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります');
                }
            }
            $result = $mongoCollection->find(array('email' => $post['email'], 'password' => getPasswordHash($post['email'], $post['password'], $app->config('salt'))));
            if ($result->count()) {
                session_regenerate_id(true);
                $user = $result->next();
                $_SESSION['user'] = $user;
                $_SESSION['expires'] = time() + (int) $app->config('timeout');
                $app->flash('info', 'ログインしました。');
                $app->getLog()->info('ユーザー名「' . $user['username'] . '」(メールアドレス"' . $user['email'] . '")がログインしました。');
                $app->redirect($app->config('static_path'));
            } else {
                throw new RuntimeException('メールアドレスまたはパスワードに誤りがあります');
            }
        } catch (RuntimeException $e) {
            $app->flash('error', $e->getMessage());
            $app->redirect($app->config('static_path') . 'login');
        }
    });
    $app->map('/logout', function () use($app) {
        if (isset($_SESSION['user'])) {
            $app->getLog()->info('ユーザー名「' . $_SESSION['user']['username'] . '」(メールアドレス"' . $_SESSION['user']['email'] . '")がログアウトしました。');
        }
        session_destroy();
        session_regenerate_id(true);
        session_start();
        $app->flash('info', 'ログアウトしました。');
        $app->redirect($app->config('static_path'));
    })->via('GET', 'POST');
    require_once __DIR__ . '/../app/routes/project.php';
    require_once __DIR__ . '/../app/routes/api.php';
});
Ejemplo n.º 16
0
 */
require 'vendor/autoload.php';
require 'config.php';
require 'Database.php';
// run Slim app
$app = new \Slim\Slim();
/**
 * Routes
 */
$app->get('/', 'hello');
$app->post('/users', 'registerUser');
$app->get('/users', 'getUsers');
$app->get('/users/:id', 'getUser');
$app->group('/user', function () use($app) {
    $app->get('/:id', 'getUser');
    // $app->put('/:id', 'updateUser');
    // $app->delete('/:id', 'deleteUser');
});
$app->post('/page-sponsors', 'addPageSponsor');
$app->get('/bases', 'getBases');
$app->get('/bases/:id/listings', 'getListingsByBaseId');
$app->get('/bases/:id/messages', 'getBaseMessages');
$app->get('/bases/:id/sponsors', 'getBaseSponsors');
$app->get('/branches/:id/bases', 'getBasesByBranchId');
$app->get('/branches/:id/listings', 'getListingsByBranchId');
$app->get('/branches/:id', 'getBranchesById');
$app->get('/branches', 'getBranches');
$app->get('/listings/nearme/:lat/:long/:distance', 'getListingsNearMe');
$app->get('/listings', 'getListings');
$app->get('/listings/search/:type/:query', 'searchListings');
$app->get('/lennieList', 'getLennie');
Ejemplo n.º 17
0
$app->group('/services', function () use($app) {
    $app->get('/data/:id/:in/:out', function ($id, $in, $out) use($app) {
        $json = array();
        if (preg_match("/^[0-9]+\$/", $id) && preg_match("/^[0-9\\-\\ \\:]+\$/", $in) && preg_match("/^[0-9\\-\\ \\:]+\$/", $out)) {
            $surveys = ORM::ForTable('lime_survey_' . $id)->where_gte('submitdate', $in)->where_lte('submitdate', $out)->order_by_asc('id')->find_many();
            foreach ($surveys as $survey) {
                $date = DateTime::createFromFormat('Y-m-d H:i:s', $survey->submitdate);
                $survey->submitdts = $date->format('U');
                // TODO: should considerate Paris Time
                array_push($json, $survey->as_array());
            }
        }
        echo json_encode($json);
    });
    $app->get('/questions/:sid', function ($sid) use($app) {
        $json = array();
        if (preg_match("/^[0-9]+\$/", $sid)) {
            $lss = @json_decode(@json_encode((array) @simplexml_load_string(@file_get_contents('http://mcp.ocd-dbs-france.org/lss/lss_' . $sid), 'SimpleXMLElement', LIBXML_NOCDATA), TRUE));
            $answers = array();
            if ($lss) {
                foreach ($lss->answers->rows->row as $row) {
                    if (!array_key_exists((string) $row->qid, $answers)) {
                        $answers[(string) $row->qid] = array();
                    }
                    $answers[(string) $row->qid][(string) $row->code] = $row->answer;
                }
            }
            $questions = ORM::ForTable('lime_questions')->where('sid', $sid)->order_by_asc('qid')->find_many();
            foreach ($questions as $question) {
                if (array_key_exists($question->qid, $answers)) {
                    $question->answers = $answers[$question->qid];
                }
                array_push($json, $question->as_array());
            }
        }
        echo json_encode($json);
    });
});
Ejemplo n.º 18
0
});
$app->get('/signin/:netid/:reason', function ($netid, $reason) use($app) {
    $result = signin_netid($netid, $reason);
    render_json($result);
});
$app->group('/signins', function () use($app) {
    $app->get('/today', function () use($app) {
        render_json(signins_today());
    });
    $app->get('/all', function () use($app) {
        if (!require_admin()) {
            return;
        }
        render_json(signins_all());
    });
    $app->get('/reasons', function () use($app) {
        $reasons = signInReasonQuery::create()->find();
        render_json($reasons->toArray());
    });
    $app->get('/stats', function () use($app) {
        $beginOfDay = strtotime("midnight", time());
        $stats = array();
        $stats['signinsToday'] = signInQuery::create()->filterByCreatedAt(array('min' => $beginOfDay))->count();
        $stats['uniqueUsers'] = UserQuery::create()->count();
        render_json($stats);
    });
});
$app->group('/users', function () use($app) {
    $app->get('/list', function () use($app) {
        if (!require_admin()) {
            return;
        }
Ejemplo n.º 19
0
$app = new \Slim\Slim(array('mode' => 'development'));
$app->setName('See Time API');
$app->configureMode('development', function () use($app) {
    $app->config(array('debug' => true, 'log.enable' => true, 'log.level' => \Slim\Log::DEBUG));
});
$app->configureMode('production', function () use($app) {
    $app->config(array('debug' => false, 'log.enable' => true, 'log.level' => \Slim\Log::DEBUG));
});
$app->group('/users', function () use($app) {
    global $decode_body;
    $app->post('', $decode_body, function () {
        create_user();
    });
    $app->group('/:username', function () use($app) {
        global $check_token_exists;
        global $decode_body;
        $app->put('', $check_token_exists, $decode_body, function ($username) {
            change_pwd($username);
        });
        $app->delete('', $check_token_exists, function ($username) {
            delete_user($username);
        });
    });
});
$app->group('/calendars', function () use($app) {
    global $check_token_exists;
    global $decode_body;
    $app->get('', $check_token_exists, function () {
        get_calendars();
    });
    $app->post('', $check_token_exists, $decode_body, function () {
        create_calendar();
Ejemplo n.º 20
0
    echo $app->redirect('/');
});
$app->group('/usuario', function () use($app) {
    // Acción asociada al formulario de login
    $app->get('/login', 'Login::forzarLogin', function () use($app) {
    });
    // Cierra la sesión de usuario
    $app->get('/logout', function () use($app) {
        global $twig;
        unset($_SESSION['user']);
        session_destroy();
        echo $twig->render('inicio.php');
    });
    // Accion asociada al email de login
    $app->get('/autenticar/:token', function ($token) use($app) {
        $email = $app->request->get('email');
        // Si intentan autenticarse (estando ya logados en el sistema) ignoramos el token vílmente
        // (si quieres entrar, estando ya dentro... pues disfruta)
        if (Login::isLogged()) {
            $email = Login::getEmail();
        }
        if (Login::isLogged() || Login::autenticar($app->db, $email, $token)) {
            global $twig;
            echo $twig->render('inicio.php', array('message' => "Bienvenido/a <b>{$email}</b>"));
        } else {
            global $twig;
            echo $twig->render('login.php', array('error' => 'El enlace de acceso utilizado ya <strong>no está en vigor</strong>.<br>Indique su dirección de correo electrónico y le enviaremos uno válido.<br>Disculpe las molestias.'));
        }
    });
});
$app->group('/dictado', function () use($app) {
    // Anota que un usuario ha realizado todos los dictados para poder avisarle cuando se cree uno nuevo
Ejemplo n.º 21
0
<?php

chdir(__DIR__ . '/../../../');
ini_set('session.use_cookies', 0);
require 'vendor/autoload.php';
\Caco\MiniAR::setDefaultPdo($pdo = new \PDO('sqlite:database/app.sqlite3'));
$pdo->exec('PRAGMA foreign_keys = ON');
$app = new \Slim\Slim();
$app->view(new \Caco\Slim\JsonView());
$app->add($auth = new \Caco\Slim\Auth\Basic());
$auth->setRealm('Caco Cloud');
$app->group('/password', function () use($app) {
    $app->get('/:key/:id', '\\Caco\\Password\\REST:one')->conditions(['id' => '\\d+']);
    $app->get('/:key', '\\Caco\\Password\\REST:all');
    $app->post('/:key', '\\Caco\\Password\\REST:add');
    $app->delete('/:key/:id', '\\Caco\\Password\\REST:delete')->conditions(['id' => '\\d+']);
    $app->put('/:key/:id', '\\Caco\\Password\\REST:edit')->conditions(['id' => '\\d+']);
});
$app->group('/bookmark', function () use($app) {
    $app->get('/:id', '\\Caco\\Bookmark\\REST:one')->conditions(['id' => '\\d+']);
    $app->get('', '\\Caco\\Bookmark\\REST:all');
    $app->post('', '\\Caco\\Bookmark\\REST:add');
    $app->delete('/:id', '\\Caco\\Bookmark\\REST:delete')->conditions(['id' => '\\d+']);
    $app->put('/:id', '\\Caco\\Bookmark\\REST:edit')->conditions(['id' => '\\d+']);
});
$app->group('/config', function () use($app) {
    $app->get('/:key', '\\Caco\\Config\\REST:one');
    $app->get('', '\\Caco\\Config\\REST:all');
    $app->post('', '\\Caco\\Config\\REST:add');
    $app->delete('/:key', '\\Caco\\Config\\REST:delete');
    $app->put('/:key', '\\Caco\\Config\\REST:edit');
Ejemplo n.º 22
0
$app->group('/content', function () use($app) {
    $app->response->headers->set('Content-Type', 'application/json');
    $app->map('/get', function () use($app) {
        //if(isset($data->token) && security_token($token)){
        //if(security_token($token)){
        if ($app->getCookie('aco-lan') !== null) {
            $lan = $app->getCookie('aco-lan');
        } else {
            $app->redirect($app->urlFor('setLanguage', array('lan' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2))));
        }
        if ($app->getCookie('aco-user') !== null) {
            $app->redirect($app->urlFor('getModified'));
        } else {
            $app->redirect($app->urlFor('getFinished'));
        }
        /*}else{
              $app->halt(403, json_encode([   'type' => 'error',
                                              'title' => 'Forbidden Request',
                                              'message' => 'You do not have the permission to call this request.']));
          }*/
    })->via('GET', 'PUT', 'POST', 'DELETE')->name('getContent');
    $app->map('/get/finished', function () use($app) {
        if ($app->getCookie('aco-lan') !== null) {
            $lan = $app->getCookie('aco-lan');
        }
        if (($db = connectToMySql()) !== false) {
            try {
                $query = 'SELECT category, element, text FROM TextContent WHERE lan = ?';
                $sql_text = $db->prepare($query);
                $sql_text->bindParam(1, $lan);
                $sql_text->execute();
                $sql_text->setFetchMode(PDO::FETCH_OBJ);
                $query = 'SELECT category, element, url FROM FileContent WHERE lan = ?';
                $sql_file = $db->prepare($query);
                $sql_file->bindParam(1, $lan);
                $sql_file->execute();
                $sql_file->setFetchMode(PDO::FETCH_OBJ);
                /*$query = 'SELECT lan, language FROM Language WHERE toggle != 0 AND toggle IS NOT NULL';
                  $sql_lan = $db->prepare($query);
                  $sql_lan->execute();
                  $sql_lan->setFetchMode(PDO::FETCH_OBJ);*/
                //$language = $sql_lan->fetchAll();
                $textcontent = $sql_text->fetchAll();
                $filecontent = $sql_file->fetchAll();
            } catch (Exception $e) {
                setupMySql($db);
                $app->redirect($app->urlFor('getContent'));
                $app->halt(503, json_encode(['type' => 'Error', 'title' => 'Oops, something went wrong!', 'message' => $e->getMessage()]));
            } finally {
                $db = null;
            }
        } else {
            $app->halt(503, json_encode(['type' => 'Error', 'title' => 'Oops, sadsomething went wrong!', 'message' => 'No database connection']));
        }
        $app->response->status(200);
        $app->response->body(json_encode(['lan' => $lan, 'textContent' => $textcontent, 'fileContent' => $filecontent]));
    })->via('GET', 'PUT', 'POST', 'DELETE')->name('getFinished');
    $app->map('/get/modified', function () use($app) {
        if ($app->getCookie('aco-lan') !== null) {
            $lan = $app->getCookie('aco-lan');
        }
        if (($db = connectToMySql()) !== false) {
            try {
                $case = '';
                $query = 'SELECT    category, element,
                            CASE    WHEN 	tmp_text       IS NULL      	THEN text
                                    WHEN	tmp_text       = ?  			THEN text
                            ELSE    tmp_text
       	                    END AS  text
                            FROM    TextContent            WHERE lan = ?';
                $sql_text = $db->prepare($query);
                $sql_text->bindParam(1, $case);
                $sql_text->bindParam(2, $lan);
                $sql_text->execute();
                $sql_text->setFetchMode(PDO::FETCH_OBJ);
                $query = 'SELECT    category, element,
                            CASE    WHEN 	tmp_url       IS NULL 	       THEN url
		                            WHEN	tmp_url       = ?    	       THEN url
                            ELSE    tmp_url
       	                    END AS 	url
                            FROM    FileContent           WHERE lan = ?';
                $sql_file = $db->prepare($query);
                $sql_file->bindParam(1, $case);
                $sql_file->bindParam(2, $lan);
                $sql_file->execute();
                $sql_file->setFetchMode(PDO::FETCH_OBJ);
                /*$query = 'SELECT lan, language, toggle, preset FROM Language';
                  $sql_lan = $db->prepare($query);
                  $sql_lan->execute();
                  $sql_lan->setFetchMode(PDO::FETCH_OBJ);*/
                //$language = $sql_lan->fetchAll();
                $textcontent = $sql_text->fetchAll();
                $filecontent = $sql_file->fetchAll();
            } catch (Exception $e) {
                setupMySql($db);
                $app->redirect($app->urlFor('getContent'));
                $app->halt(503, json_encode(['type' => 'Error', 'title' => 'Oops, something went wrong!', 'message' => $e->getMessage()]));
            } finally {
                $db = null;
            }
        } else {
            $app->halt(503, json_encode(['type' => 'Error', 'title' => 'Oops, sadsomething went wrong!', 'message' => 'No database connection']));
        }
        $app->response->status(200);
        $app->response->body(json_encode(['lan' => $lan, 'textContent' => $textcontent, 'fileContent' => $filecontent]));
    })->via('GET', 'PUT', 'POST', 'DELETE')->name('getModified');
    $app->put('/save/lan', function () use($app) {
        if ($app->getCookie('aco-lan') !== null) {
            $lan = $app->getCookie('aco-lan');
        }
        if (isset($data->token) && security_token($data->token)) {
            if (($db = connectToMySql()) !== false) {
                try {
                    $case = '';
                    $query = 'UPDATE TextContent t SET t.text = t.tmp_text, t.tmp_text = NULL
                    WHERE t.tmp_text IS NOT NULL AND t.tmp_text != ? AND t.lan = ?';
                    $sql_text = $db->prepare($query);
                    $sql_text->bindParam(1, $case);
                    $sql_text->bindParam(2, $lan);
                    $sql_text->execute();
                    $query = 'UPDATE FileContent f SET f.url = f.tmp_url, f.src = f.tmp_src,
                    f.tmp_url = NULL, f.tmp_src = NULL
                    WHERE f.tmp_url IS NOT NULL AND f.tmp_src IS NOT NULL
                    AND f.tmp_url != ? AND f.tmp_src != ? AND f.lan = ?';
                    $sql_file = $db->prepare($query);
                    $sql_file->bindParam(1, $case);
                    $sql_file->bindParam(2, $case);
                    $sql_file->bindParam(3, $lan);
                    $sql_file->execute();
                } catch (Exception $e) {
                    $app->halt(503, json_encode(['type' => 'error', 'title' => 'Oops, something went wrong!', 'message' => $e->getMessage()]));
                } finally {
                    $db = null;
                }
            } else {
                $app->halt(503, json_encode(['type' => 'error', 'title' => 'Oops, something went wrong!', 'message' => 'No database connection']));
            }
        } else {
            $app->halt(403, json_encode(['type' => 'error', 'title' => 'Forbidden Request', 'message' => 'You do not have the permission to call this request.']));
        }
    });
    $app->put('/save/all', function () use($app) {
        if (isset($data->token) && security_token($data->token)) {
            if (($db = connectToMySql()) !== false) {
                try {
                    $case = '';
                    $query = 'UPDATE TextContent t SET t.text = t.tmp_text, t.tmp_text = NULL
                    WHERE t.tmp_text IS NOT NULL AND t.tmp_text != ?';
                    $sql_text = $db->prepare($query);
                    $sql_text->bindParam(1, $case);
                    //$sql_text->bindParam(2,$lan);
                    $sql_text->execute();
                    $query = 'UPDATE FileContent f SET f.url = f.tmp_url, f.src = f.tmp_src,
                    f.tmp_url = NULL, f.tmp_src = NULL
                    WHERE f.tmp_url IS NOT NULL AND f.tmp_src IS NOT NULL
                    AND f.tmp_url != ? AND f.tmp_src != ?';
                    $sql_file = $db->prepare($query);
                    $sql_file->bindParam(1, $case);
                    $sql_file->bindParam(2, $case);
                    $sql_file->execute();
                } catch (Exception $e) {
                    $app->halt(503, json_encode(['type' => 'error', 'title' => 'Oops, something went wrong!', 'message' => $e->getMessage()]));
                } finally {
                    $db = null;
                }
            } else {
                $app->halt(503, json_encode(['type' => 'error', 'title' => 'Oops, something went wrong!', 'message' => 'No database connection']));
            }
        } else {
            $app->halt(403, json_encode(['type' => 'error', 'title' => 'Forbidden Request', 'message' => 'You do not have the permission to call this request.']));
        }
    });
});
    $app = \Slim\Slim::getInstance();
    $data = json_decode($app->request->getBody(), true);
    if (array_key_exists('publisher_id', $data) && array_key_exists('recipient_id', $data) && array_key_exists('rating', $data) && array_key_exists('comment', $data)) {
        if (isset($data['publisher_id']) && isset($data['recipient_id']) && isset($data['rating']) && isset($data['comment'])) {
            if (empty($data['publisher_id']) || empty($data['recipient_id']) || empty($data['comment']) || !($data['rating'] >= 0 && $data['rating'] <= 5)) {
                $app->halt(422, json_encode(array('status' => 422, 'error' => 'Empty or Invalid value parameters')));
            }
        } else {
            $app->halt(422, json_encode(array('status' => 422, 'error' => 'Undefined parameters')));
        }
    } else {
        $app->halt(422, json_encode(array('status' => 422, 'error' => 'Missing parameters')));
    }
}
// Define routes
$app->group('/api', function () use($app) {
    // Get all ratings
    $app->get('/', 'getAllRatings');
    // Get single by rating id
    $app->get('/:id/', 'getSingleRatingByID');
    // Get all by recipient id
    $app->get('/recipients/:id', 'getAllRatingsByRecipientID');
    // Get all by publisher id
    $app->get('/publishers/:id', 'getAllRatingsByPublisherID');
    // Delete single rating
    $app->delete('/delete/:id', 'deleteRatingByID');
    // Create new rating
    $app->post('/create', 'reqDataCheck', 'publishNewRating');
});
// Run app
$app->run();
Ejemplo n.º 24
0
$app->group('/v1', function () use($app, $db, $trucking) {
    /**
     *   Trucking routes
     */
    $app->group('/trucking', function () use($app, $db, $trucking) {
        /**
         *   Adds a new job to the list
         */
        $app->post('/job', function () use($app, $db, $trucking) {
            try {
                $data = file_get_contents("php://input");
                $request = json_decode($data);
                $decoded_array = isTokenValid($request->token);
                if ($decoded_array != null) {
                    $owner_id = $decoded_array['data']->userId;
                    if ($trucking->saveNewJob($request, $owner_id)) {
                        header("HTTP/1.0 200 Success");
                        echo json_encode(array("status" => "ok", "message" => "New job post created!!"));
                    } else {
                        // we have errors
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo json_encode($trucking->getErrors());
                    }
                } else {
                    header("HTTP/1.0 401 Not Authorized");
                    echo '{"status":"fail","message":"Please login to perform action."}';
                }
            } catch (Exception $e) {
                header("HTTP/1.0 400 Bad data submitted");
                echo '{"status":"fail","message":"Data is not in correct format."}';
            }
        });
        /**
         *   GET list of jobs
         */
        $app->get('/jobs', function () use($app, $db, $trucking) {
            if ($app->request->isGet()) {
                // return the list of jobs available
                echo $trucking->getJobs();
            }
        });
        $app->get('/jobs/:id/:ownerId', function ($id, $owner_id) use($app, $db, $trucking) {
            echo $trucking->getJobDetails($id, $owner_id);
        });
        /**
         * @API /trucking/searchTerm
         * @description Allows you to search terms
         */
        $app->get('/searchJobs', function () use($app, $trucking) {
            $searchTerm = $app->request()->get('searchTerm');
            $result = $trucking->findBySearchTerm($searchTerm);
            if ($result != null) {
                echo json_encode($result);
            } else {
                echo '{"status":"fail", "message":"No records matched your search."}';
            }
        });
        /**
         * @description
         * @API /trucking/job      DELETE
         */
        $app->options('/job/:id', function ($id) use($app, $trucking) {
            // make sure user token is valid.
            echo 'The actual OPTIONS call. token: ';
        });
        $app->delete('/job/:id', function ($id) use($app, $trucking) {
            // make sure user token is valid.
            $token = $app->request()->get('token');
            if (isTokenValid($token) != null) {
                $decoded_array = isTokenValid($token);
                $owner_id = $decoded_array['data']->userId;
                // process request
                if ($trucking->deleteJobPost($id, $owner_id)) {
                    // success deleting the job post
                    echo '{"status":"OK", "message":"Job post removed succesfully"}';
                } else {
                    // failure in deleting the item. The job post might have been removed already.
                    echo '{"status":"fail", "message":"The job post might have been removed already"}';
                }
            } else {
                // return header with a 401 status code.
                header("HTTP/1.0 401 Not Authorized");
                echo '{"status":"fail", "message":"User needs to log in."}';
            }
        });
    });
    // my account api
    $app->group('/account', function () use($app, $db, $trucking) {
        // login
        $app->post('/login', function () use($app) {
            if ($app->request->isPost()) {
                $json = json_decode(file_get_contents("php://input"));
                $username = isset($json->username) ? trim($json->username) : "";
                //trim($app->request()->post('username'));
                $password = isset($json->password) ? trim($json->password) : "";
                //trim($app->request()->post('password'));
                try {
                    // query the database
                    $sql = "SELECT user_id, user_name, user_active, user_password_hash, user_role FROM users WHERE user_name = :username";
                    $pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
                    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $query = $pdo->prepare($sql);
                    $query->bindValue(':username', $username, PDO::PARAM_STR);
                    $query->execute();
                    $result = $query->fetch(PDO::FETCH_OBJ);
                    // we have user. I saw that it might not be a good practice to do this check.
                    if (count($result) > 0) {
                        // let's verify the credentials.
                        $storedPassword = $result->user_password_hash;
                        if (password_verify($password, $storedPassword)) {
                            // we have an user, let's create the TOKEN
                            $secretKey = base64_decode(SECRET_KEY);
                            // encode the array
                            $jwt = JWT::encode(token($result->user_id, $result->user_name, $result->user_role), $secretKey, 'HS256');
                            $enencodedArray = array('jwt' => $jwt);
                            echo json_encode($enencodedArray);
                        } else {
                            header("HTTP/1.0 401 Not Authorized");
                            echo '{"status":"fail", "message":"Unable to log you in. Please try again!"}';
                        }
                    } else {
                        header("HTTP/1.0 401 Not Authorized");
                        echo '{"status":"fail", "message":"Unable to log you in. Please try again!"}';
                    }
                } catch (Exception $ex) {
                    header("HTTP/1.0 401 Not Authorized");
                    echo '{"status":"fail", "message":"Unable to log you in. Please contact your system administrator"' . $ex->getMessage() . ' }';
                }
            } else {
                // method is not post
                header("HTTP/1.0 405 Method Not Allowed");
            }
        });
        // register
        $app->post('/register', function () use($app, $db) {
            if ($app->request->getMethod() == "POST") {
                // initialize array of errors.
                $errors = array();
                $user_role = "admin";
                $json = json_decode(file_get_contents("php://input"));
                if ($user_role === "admin") {
                    $username = isset($json->username) ? trim($json->username) : "";
                    $password = isset($json->password) ? trim($json->password) : "";
                    $pwdConfirm = isset($json->confirmPassword) ? trim($json->confirmPassword) : "";
                    $email = isset($json->email) ? trim($json->email) : "";
                    //trim($json->email);
                    $userRole = 'basic';
                    // create instance to database
                    $db = new DbConnection();
                    if (empty($username)) {
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo '{"status":"fail", "message":"Username field cannot be empty"}';
                        //json_encode($errors);
                    } elseif (strlen($username) < 6) {
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo '{"status":"fail","message": "Make sure username is at least 6 characters long."}';
                    } elseif (empty($password) || empty($pwdConfirm)) {
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo '{"status":"fail", "message":"Password or confirm password fields cannot be empty."}';
                    } elseif (empty($email)) {
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo '{"status":"fail", "message":"Email field cannot be empty, or it is not a valid email address"}';
                    } elseif ($password !== $pwdConfirm) {
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo '{"status":"fail","message":"Passwords donot match."}';
                    } elseif (strlen($password) < 7) {
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo '{"status":"fail", "message":"Passwords should be at least 7 characters long."}';
                    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        header("HTTP/1.0 401 Invalid submitted data");
                        echo '{"status":"fail", "message":"Please input valid email address!"}';
                    } elseif ($db->isConnected()) {
                        // let's make sure user doesn't exists
                        $pdo = $db->getConnection();
                        $query = $pdo->prepare("SELECT user_name from users WHERE user_name = :username");
                        $query->bindValue(':username', $username, PDO::PARAM_STR);
                        $query->execute();
                        $result = $query->fetchAll();
                        if (count($result) > 0 || count($errors) > 0) {
                            header("HTTP/1.0 401 Invalid submitted data");
                            echo '{"status":"fail", "message":"Please make sure your password or username are valids"}';
                            //json_encode($errors);
                        } else {
                            // check to see if we don't have errors
                            try {
                                $options = ['cost' => 12];
                                $user_password_hash = password_hash($password, PASSWORD_BCRYPT, $options);
                                $new_user = $pdo->prepare("INSERT INTO users (user_name, user_password_hash, user_email, user_registration_datetime) VALUES (:username, :user_password_hash, :email, NOW())");
                                $new_user->bindValue(':username', $username, PDO::PARAM_STR);
                                $new_user->bindValue(':user_password_hash', $user_password_hash, PDO::PARAM_STR);
                                $new_user->bindValue(':email', $email, PDO::PARAM_STR);
                                $new_result = $new_user->execute();
                                // get the id of the last user
                                //$user_id = $pdo->lastInsertId();
                                if ($new_result) {
                                    // we have succeded in adding the user
                                    echo '{"status":"OK", "message":"User created succesfully. Please check your email address for confirmation.", "email":"' . $email . '"}';
                                } else {
                                    // we have failed :(
                                    header("HTTP/1.0 403 Not enough credentials");
                                    echo '{"status":"fail","message":"Registration failed. Not your fault. Please try again!"}';
                                }
                            } catch (PDOException $ex) {
                                $ex->getMessage();
                            }
                        }
                    } else {
                        header("HTTP/1.0 401 Not enough credentials");
                        echo json_encode($errors);
                    }
                } else {
                    header("HTTP/1.0 403 Not enough credentials");
                    $errors[] = ["status" => "fail", "message" => "You don't have enough credentials to complete this task"];
                    echo json_encode($errors);
                }
            } else {
                // method is not post
                header("HTTP/1.0 405 Method Not Allowed");
            }
        });
        // <-- end of Register
        $app->post('/logout', function () use($app, $db) {
            if ($app->request->getMethod() == "POST") {
                echo '{"status":"OK", "message":"You are now signed out of 343Trucking.com!"}';
            }
        });
        /**
         *   @description
         *   This will get the account information of the user that's logged in.
         *   For now, we will only get the jobs that the user has active and inactive and retrieve
         *   account cancellation, activation, post new add, remove or cancel add, and that.
         */
        $app->get('/dashboard', function () use($app, $trucking) {
            $tokenFromClient = $app->request()->get('token');
            if ($tokenFromClient) {
                try {
                    // decode the jwt
                    $secretKey = base64_decode(SECRET_KEY);
                    JWT::$leeway = 60;
                    // decode the key
                    $token = JWT::decode($tokenFromClient, $secretKey, array('HS256'));
                    // if no exception twron here, we are good to go.
                    // let's also decode so we can access some info about the user.
                    $decoded_array = (array) $token;
                    // return some dummy data for now.
                    $userListings = $trucking->getUserListings($decoded_array['data']->userId);
                    if ($userListings !== null) {
                        echo json_encode($userListings);
                    } else {
                        echo '{"status":"fail", "message":"No data :("}';
                    }
                } catch (Exception $e) {
                    header("HTTP/1.0 401 Authorization Exception");
                    echo '{"status":"fail", "message":"Your session has ended!! ' . $e->getMessage() . '"}';
                }
            } else {
                header("HTTP/1.0 401 Authorization Token Not Present");
                echo '{"status":"fail", "message":"Authorization Token not present."}';
            }
        });
    });
    // end of my account
});
Ejemplo n.º 25
0
$app->group('/', function () use($app, $dbsettings) {
    $username = $app->request()->headers('PHP_AUTH_USER');
    $password = $app->request()->headers('PHP_AUTH_PW');
    if ($username != $dbsettings->dbuser || $password != $dbsettings->dbpass) {
        $app->response()->status(401);
        $app->response()->header('WWW-Authenticate', sprintf('Basic realm="%s"', 'Protected Area'));
        return;
    }
    $app->get('/', function () use($app) {
        $app->render('app.html');
    });
    $app->post('procparams', function () use($app) {
        $entry = json_decode($app->request()->getBody());
        echo getInputParams($entry);
    });
    $app->get('api', function () use($app) {
        $app->render('../../api/api.json');
    });
    $app->post('api', function () use($app) {
        $json = $app->request()->getBody();
        $data = json_decode($json);
        // TODO: CHECK INPUT FOR VALIDITY
        // GENERATE SQL CODE FOR PROCEDURES
        $mysqli = getConnection_mysqli();
        // Set the procedures according to the existing API when an error occurs
        if (!createProcedures($mysqli, $data)) {
            if (file_exists("../api/api.json")) {
                $api = json_decode(file_get_contents("../api/api.json"));
                createProcedures($mysqli, $api);
            }
            $app->halt(400, "Stored procedure command failed: (" . $mysqli->errno . ") " . $mysqli->error);
        }
        // Make a backup
        if (file_exists("../api/api.json")) {
            copy("../api/api.json", "../api/api_" . date("ymd_His") . ".json");
        }
        file_put_contents("../api/api.json", json_encode($data, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES));
    });
});
function reqDataCheck()
{
    $app = \Slim\Slim::getInstance();
    $data = json_decode($app->request->getBody(), true);
    if (array_key_exists('name', $data) && array_key_exists('description', $data)) {
        if (isset($data['name']) && isset($data['description'])) {
            if (empty($data['name']) || empty($data['description'])) {
                $app->halt(422, json_encode(array('status' => 422, 'error' => 'Empty value parameters')));
            }
        } else {
            $app->halt(422, json_encode(array('status' => 422, 'error' => 'Undefined parameters')));
        }
    } else {
        $app->halt(422, json_encode(array('status' => 422, 'error' => 'Missing parameters')));
    }
}
// Define routes
$app->group('/api', function () use($app) {
    // Get a Category
    $app->get('/:id', 'getCategoryById');
    // Get all Categories
    $app->get('/', 'getAllCategories');
    // Create new Category
    $app->post('/', 'reqDataCheck', 'createCategory');
    // Update a Category by ID
    $app->put('/:id', 'reqDataCheck', 'updateCategoryById');
    // Delete a Category by ID
    $app->delete('/:id', 'deleteCategoryById');
});
// Run app
$app->run();
Ejemplo n.º 27
0
 /**
  * Test route groups
  */
 public function testRouteGroups()
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'GET', 'SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/bar/baz'));
     $s = new \Slim\Slim();
     $mw1 = function () {
         echo "foo";
     };
     $mw2 = function () {
         echo "bar";
     };
     $callable = function () {
         echo "xyz";
     };
     $s->group('/bar', $mw1, function () use($s, $mw2, $callable) {
         $s->get('/baz', $mw2, $callable);
     });
     $s->call();
     $this->assertEquals('foobarxyz', $s->response()->body());
 }
Ejemplo n.º 28
0
$app->group('/users', function () use($app, $userModel) {
    // GET request on /songs. Perform actions getAmountOfSongs() and getAllSongs() and pass the result to the view.
    // Note that $model is passed to the route via "use ($app, $model)". I've written it like that to prevent creating
    // the model / database connection in routes that does not need the model / db connection.
    $app->get('/', function () use($app, $userModel) {
        $users = $userModel->getAllUsers();
        $app->render('users.twig', array('users' => $users));
    });
    // POST request on /users/adduser (after a form submission from /users). Asks for POST data, performs
    // model-action and passes POST data to it. Redirects the user afterwards to /users.
    $app->post('/adduser', function () use($app, $userModel) {
        // in a real-world app it would be useful to validate the values (inside the model)
        $userModel->addUser($_POST["firstname"], $_POST["lastname"], $_POST["preferredname"], $_POST["month"], $_POST["day"], $_POST["year"], $_POST["phone1"], $_POST["phone2"], $_POST["email1"], $_POST["email2"]);
        $app->redirect('/users');
    });
    $app->get('/:user_id', function ($user_id) use($app) {
        $app->redirect('/users/edituser/' . $user_id);
    });
    // POST request on /songs/deleteuser after a form submission from /users. Asks for POST data
    // Performs an action on the model and redirects the user to /users.
    $app->post('/deleteuser', function () use($app, $userModel) {
        $userModel->deleteUser($_POST["user_id"]);
        $app->redirect('/users');
    });
    // GET request on /users/editusers/:user_id. Should be self-explaining. If user id exists show the editing page,
    // if not redirect the user. Note the short syntax: 'user' => $model->getUser($user_id)
    $app->get('/edituser/:user_id', function ($user_id) use($app, $userModel) {
        $user = $userModel->getUser($user_id);
        if (!$user) {
            $app->redirect('/users');
        }
        $app->render('users.edit.twig', array('user' => $user));
    });
    // POST request on /users/updateuser. Self-explaining.
    $app->post('/updateuser', function () use($app, $userModel) {
        // passing an array would be better here, but for simplicity this way is okay
        $userModel->updateUser($_POST["user_id"], $_POST['firstname'], $_POST["lastname"], $_POST["preferredname"], $_POST["month"], $_POST["day"], $_POST["year"], $_POST["gender"], $_POST["phone1"], $_POST["phone2"], $_POST["email1"], $_POST["email2"]);
        $app->redirect('/users');
    });
    // POST request on /search. Self-explaining.
    $app->post('/search', function () use($app, $userModel) {
        $result_users = $userModel->searchUser($_POST['searchTerm']);
        $app->render('users.twig', array('users' => $result_users, 'filter' => 'filtered by: ' . $_POST['searchTerm']));
    });
    // GET request on /search. Simply redirects the user to /songs
    $app->get('/search', function () use($app) {
        $app->redirect('/users');
    });
});
Ejemplo n.º 29
0
$app->group('/cursos', function () use($app, $db) {
    $app->get('/', function () use($app, $db) {
        //devuelve todos los cursos
        $courseController = new \Controllers\Cursos($app, $db);
        $courseController->index();
    });
    $app->get('/:id', function ($id) use($app, $db) {
        //devuelve el curso según el id dado
        $courseController = new \Controllers\Cursos($app, $db);
        $courseController->view($id);
    });
    $app->get('/:id/obtener_clase', function ($id) use($app, $db) {
        //status true: devuelve la clase más reciente según el id dado
        $courseController = new \Controllers\Cursos($app, $db);
        //status false: no hay ninguna clase que no esté finalizada
        $courseController->obtener_clase($id);
    });
    $app->get('/checkname/:name', function ($name) use($app, $db) {
        //Verificar si existe un curso con nombre "name"
        $courseController = new \Controllers\Cursos($app, $db);
        $courseController->checkname($name);
    });
    $app->get('/buscar/:usuario_id/:name', function ($usuario_id, $name) use($app, $db) {
        //busqueda de un curso por nombre
        $courseController = new \Controllers\Cursos($app, $db);
        $courseController->buscar($usuario_id, $name);
    });
    $app->post('/alta', function () use($app, $db) {
        //dar de alta un nuevo curso
        try {
            $request = $app->request();
            $courseController = new \Controllers\Cursos($app, $db);
            $courseController->crearCurso($request->post('nombre'), $request->post('descripcion'), $request->post('horarios'), $request->post('usuario_id'));
        } catch (Exception $e) {
            $app->response()->status(400);
            $app->response()->header('X-Status-Reason', $e->getMessage());
        }
    });
    $app->post('/generar_clase/', function () use($app, $db) {
        //generar una clase para un curso
        try {
            $request = $app->request();
            $courseController = new \Controllers\Cursos($app, $db);
            $courseController->generarClase($request->post('curso_id'));
        } catch (Exception $e) {
            $app->response()->status(400);
            $app->response()->header('X-Status-Reason', $e->getMessage());
        }
    });
    $app->post('/resolver_pendientes/', function () use($app, $db) {
        //recibe clase_id, pasa todos los pendientes a ausentes
        try {
            $request = $app->request();
            $courseController = new \Controllers\Cursos($app, $db);
            $courseController->resolver_pendientes($request->post('clase_id'));
        } catch (Exception $e) {
            $app->response()->status(400);
            $app->response()->header('X-Status-Reason', $e->getMessage());
        }
    });
    $app->post('/marcar_completada/', function () use($app, $db) {
        //marca una clase como completada
        try {
            $request = $app->request();
            $courseController = new \Controllers\Cursos($app, $db);
            $courseController->marcar_completada($request->post('clase_id'));
        } catch (Exception $e) {
            $app->response()->status(400);
            $app->response()->header('X-Status-Reason', $e->getMessage());
        }
    });
    $app->get('/:id/clases', function ($id) use($app, $db) {
        //devuelve todas las clases para un curso
        $courseController = new \Controllers\Cursos($app, $db);
        $courseController->get_clases($id);
    });
    $app->get('/clase/:id', function ($id) use($app, $db) {
        //devuelve los alumnos y su asistencia para una clase
        $courseController = new \Controllers\Cursos($app, $db);
        $courseController->informacion_clase($id);
    });
});
Ejemplo n.º 30
0
$app->get('/occupation', function () use($app) {
    $app->response()->header('Content-Type', 'application/json');
    echo Skill::all()->toJson();
});
$app->group('/user', function () use($app) {
    $app->options('/:name', function ($name) use($app) {
        $app->response()->header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    });
    $app->options('/', function () use($app) {
        $app->response()->header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    });
    $app->options('/progress', function () use($app) {
        $app->response()->header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    });
    $app->options('/talent/:name', function () use($app) {
        $app->response()->header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    });
    $app->options('/occupation', function () {
        $app->response()->header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    });
    $app->options('/skills', function () use($app) {
        $app->response()->header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    });
    $app->options('/mindmap', function () use($app) {
        $app->response()->header('Access-Control-Allow-Methods', 'POST, OPTIONS');
    });
});
$app->options('/authenticate', function () {
    $app->response()->header('Access-Control-Allow-Methods', 'POST, OPTIONS');
});
$app->options('/schooladvice', function () {