public function connect(Application $app)
 {
     // creates a new controller based on the default route
     $controllers = $app['controllers_factory'];
     /**
      * Display a login form
      */
     $controllers->get('/', function (Request $request) use($app) {
         $IsError = $request->query->get('error') === "1";
         $x = $app['twig']->render('login.twig', ['error' => $IsError]);
         return $x;
     });
     /**
      * Handle login form submissions
      */
     $controllers->post('/', function (Request $request) use($app) {
         $UsernameInput = User::GetDomainAndUsernameFromInput($request->request->get('username'), $app);
         $Password = $request->request->get('password');
         $DeviceID = $request->query->get('device_id');
         $Username = $UsernameInput['Username'];
         $Domain = $UsernameInput['Domain'];
         $Ldap = new LdapAuthentication($app);
         try {
             $LoginResult = $Ldap->TryToAuthenticate($Domain, $Username, $Password);
         } catch (\Exception $ex) {
             return $app->redirect("/login?error=1&device_id=" . urlencode($DeviceID));
         }
         if (!$LoginResult) {
             return $app->redirect("/login?error=1&device_id=" . urlencode($DeviceID));
         }
         /* @var $User User */
         $User = User::TryGetUserByUsername($Username, $Domain, $app);
         if ($User !== NULL) {
             $User->Load();
             $User->ResetToken();
             $User->DeviceID = $DeviceID;
             $User->Save();
         } else {
             $User = new User($app);
             $User->DeviceID = $DeviceID;
             $User->Username = $Username;
             $User->Domain = $Domain;
             $User->ResetToken();
             $User->Save();
         }
         $UserFields = ['Domain' => $User->Domain, 'Username' => $User->Username, 'Token' => $User->Token];
         return $app->redirect('/login/close?' . http_build_query($UserFields));
     });
     /**
      * Close the WebView on the Android client. TODO: remove the
      * webview altogether
      */
     $controllers->get('/close', function () {
         return '';
     });
     return $controllers;
 }
 public function connect(Application $app)
 {
     // creates a new controller based on the default route
     $controllers = $app['controllers_factory'];
     /**
      * Perform a logout for the user.
      */
     $controllers->get('/', function (Request $request) use($app) {
         $Username = $request->query->get('username');
         $Token = $request->query->get('token');
         $Domain = $request->query->get('domain');
         $User = User::TryGetUserByUsername($Username, $Domain, $app);
         if ($User !== NULL) {
             $User->Load();
             if ($User->Token === $Token) {
                 $User->Delete();
             }
             return $app->redirect('/logout/clear');
         }
         return $app->redirect('/logout/close');
     });
     /**
      * Some URLs just for signaling with the WebView in the Android
      * App. TODO: stop this and user a normal API call instead.
      */
     $controllers->get('/clear', function () {
         return '';
     });
     $controllers->get('/close', function () {
         return '';
     });
     return $controllers;
 }
 /**
  * Middleware to ensure only authenticated requests produce output
  * for an HTTP GET request. The domain, token, and username must appear
  * in the request query string. The requestor should expect JSON payload
  * in the output
  * 
  * @param Request $request
  * @param Application $app
  * @return object Application response
  */
 public static function EnsureAuthenticatedGETJSON(Request $request, Application $app)
 {
     $Username = $request->query->get('username');
     $Domain = $request->query->get('domain');
     $Token = $request->query->get('token');
     $User = User::TryGetUserByUsername($Username, $Domain, $app);
     if ($User !== null) {
         $User->Load();
         if ($User->Token !== $Token) {
             return $app->json(['IsAuthenticated' => false], 403);
         }
     } else {
         return $app->json(['IsAuthenticated' => false], 403);
     }
 }
 public function ResetToken()
 {
     $this->Token = User::GetRandomToken();
 }
 public function connect(Application $app)
 {
     $controllers = $app['controllers_factory'];
     /**
      * Gets all pending print jobs for the current user.
      */
     $controllers->get('/jobs', function (Request $request) use($app) {
         $Username = User::GetUsernameFromRequest($request);
         /* @var $cups CupsPrintIPP */
         $cups = new \CupsPrintIPP();
         if (!empty($app['config']) && !empty($app['config']['cups']) && !empty($app['config']['cups']['host'])) {
             $cups->setHost($app['config']['cups']['host']);
         } else {
             throw new \Exception("Cups is not configured.");
         }
         if (!empty($app['config']) && !empty($app['config']['cups']) && !empty($app['config']['cups']['catchall_printer'])) {
             $cups->setPrinterURI($app['config']['cups']['catchall_printer']);
         } else {
             throw new \Exception("Printer is not configured.");
         }
         $cups->setUserName($Username);
         // setting user name for server
         //$cups->debug_level = 3; // Debugging very verbose
         //$cups->setLog('/tmp/printipp','file',3); // logging very verbose
         if (($error = $cups->getJobs(true)) === "successfull-ok") {
             $jobs_attributes = [];
             for ($count = 0; !empty($cups->jobs_attributes->{"job_" . $count}) && is_object($cups->jobs_attributes->{"job_" . $count}); $count++) {
                 $jobs_attributes["job_" . $count] = $cups->jobs_attributes->{"job_" . $count};
             }
             if (!empty($jobs_attributes)) {
                 return $app->json($jobs_attributes);
             } else {
                 return $app->json(new \stdClass());
             }
         }
         return $app->json($error, 500);
     })->before('PrintApp\\Controllers\\Shared::EnsureAuthenticatedGETJSON');
     /**
      * Gets a list of all known beacons and the printers they are near.
      */
     $controllers->get('/beaconMap', function (Request $request) use($app) {
         $all_beacons = $app['db']->fetchAll("SELECT * FROM vw_beacons_printers");
         if (!empty($all_beacons)) {
             $beacon_map = [];
             foreach ($all_beacons as $beacon) {
                 $beacon_map[$beacon["beacon_identifier"]] = $beacon['printer_name'];
             }
             return $app->json($beacon_map);
         } else {
             return $app->json([]);
         }
     })->before('PrintApp\\Controllers\\Shared::EnsureAuthenticatedGETJSON');
     /**
      * Release all print jobs for the current user to the printer provided in
      * the POST data
      */
     $controllers->post('/releaseAll', function (Request $request) use($app) {
         $Username = User::GetUsernameFromRequest($request);
         $Printer = $request->request->get('printer');
         if (empty($Printer)) {
             throw new \Exception("Must provider a printer to print to.");
         }
         /* @var $cups CupsPrintIPP */
         $cups = new \CupsPrintIPP();
         if (!empty($app['config']) && !empty($app['config']['cups']) && !empty($app['config']['cups']['host'])) {
             $cups->setHost($app['config']['cups']['host']);
         } else {
             throw new \Exception("Cups is not configured.");
         }
         if (!empty($app['config']) && !empty($app['config']['cups']) && !empty($app['config']['cups']['catchall_printer'])) {
             $cups->setPrinterURI($app['config']['cups']['catchall_printer']);
         } else {
             throw new \Exception("Printer is not configured.");
         }
         $cups->setUserName($Username);
         $cups->debug_level = 3;
         // Debugging very verbose
         $cups->setLog('/tmp/printipp', 'file', 3);
         // logging very verbose
         if (($error = $cups->getJobs(false)) === "successfull-ok") {
             $jobs_attributes = [];
             for ($count = 0; !empty($cups->jobs_attributes->{"job_" . $count}) && is_object($cups->jobs_attributes->{"job_" . $count}); $count++) {
                 $jobs_attributes["job_" . $count] = $cups->jobs_attributes->{"job_" . $count};
             }
             foreach ($jobs_attributes as $v) {
                 $job_uri = $v->job_uri->_value0;
                 $job_id = $v->job_id->_value0;
                 exec("/usr/sbin/lpmove " . escapeshellarg($job_id) . " " . escapeshellarg($Printer));
                 if (!empty($job_uri) && ($releaseJobsError = $cups->releaseJob($job_uri)) !== "successfull-ok") {
                     return $app->json($releaseJobsError, 500);
                 }
             }
             return $app->json(["isSuccessful" => true]);
         }
         return $app->json($error, 500);
     })->before('PrintApp\\Controllers\\Shared::EnsureAuthenticatedGETJSON');
     return $controllers;
 }