Moved some app logic into lib.php