Advertisement
Guest User

Untitled

a guest
Jun 21st, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 62.93 KB | None | 0 0
  1. <?php
  2. require_once __DIR__.'/../../config.php';
  3. require UELEARNING_ROOT.'/vendor/autoload.php';
  4. require_once __DIR__.'/src/ApiTemplates.php';
  5. require_once UELEARNING_LIB_ROOT.'/User/User.php';
  6. require_once UELEARNING_LIB_ROOT.'/User/UserSession.php';
  7. require_once UELEARNING_LIB_ROOT.'/User/UserAdmin.php';
  8. require_once UELEARNING_LIB_ROOT.'/Study/StudyActivity.php';
  9. require_once UELEARNING_LIB_ROOT.'/Study/StudyActivityManager.php';
  10. require_once UELEARNING_LIB_ROOT.'/Study/StudyManager.php';
  11. require_once UELEARNING_LIB_ROOT.'/Target/Target.php';
  12. require_once UELEARNING_LIB_ROOT.'/Target/TargetManager.php';
  13. require_once UELEARNING_LIB_ROOT.'/Database/DBInfo.php';
  14. require_once UELEARNING_LIB_ROOT.'/Database/DBQuestion.php';
  15. require_once UELEARNING_LIB_ROOT.'/Recommand/RecommandPoint.php';
  16. require_once UELEARNING_LIB_ROOT.'/Log/Log.php';
  17. use UElearning\User;
  18. use UElearning\Study;
  19. use UElearning\Target;
  20. use UElearning\Recommand;
  21. use UElearning\Exception;
  22. use UElearning\Database;
  23. use UElearning\Log;
  24.  
  25. $app = new \Slim\Slim(array(
  26.     'templates.path' => './', // 設定Path
  27.     'debug' => true
  28. ));
  29. $app_template = new ApiTemplates($app);
  30.  
  31. // 設定成將使用JSON格式輸出
  32. function APIrequest() {
  33.     $app = \Slim\Slim::getInstance();
  34.     $app->view(new \JsonApiView());
  35.     $app->add(new \JsonApiMiddleware());
  36. }
  37.  
  38.  
  39. /*
  40.  * 測試用 Say hello!~~~
  41.  * GET http://localhost/api/v2/hello/{string}
  42.  */
  43. $app->get('/hello/:name', 'APIrequest', function ($name) use ($app) {
  44.     $app->render(200,array(
  45.         'error'   => false,
  46.         'msg' => 'Hello, '.$name
  47.     ));
  48. });
  49.  
  50. // ============================================================================
  51.  
  52. function login($user_id = null) {
  53.     $app = \Slim\Slim::getInstance();
  54.  
  55.     // 取得帶來的參數
  56.     $cType = $app->request->getContentType();
  57.     if($cType == 'application/x-www-form-urlencoded') {
  58.         if(!isset($user_id)) {
  59.             $user_id = $_POST['user_id'];
  60.         }
  61.         $password = $_POST['password'];
  62.         $browser  = isset($_POST['browser']) ? $_POST['browser'] : 'api';
  63.     }
  64.     else /*if($cType == 'application/json')*/ {
  65.         $postData = $app->request->getBody();
  66.         $postDataArray = json_decode($postData);
  67.         $user_id = $postDataArray->user_id;
  68.         $password = $postDataArray->password;
  69.         $browser  = isset($postDataArray->browser)
  70.                         ? $postDataArray->browser : 'api';
  71.     }
  72.     /*else {
  73.         $app->render(400, array(
  74.                 'Content-Type'=> $cType,
  75.                 'error'       => true,
  76.                 'msg'     => '',
  77.                 'msg_cht' => '輸入參數的Content-Type不在支援範圍內 或是沒有輸入',
  78.                 'substatus'   => 102
  79.             )
  80.         );
  81.     }*/
  82.  
  83.     // 進行登入
  84.     try {
  85.         $session = new User\UserSession();
  86.         $loginToken = $session->login($user_id, $password, $browser);
  87.         $user = $session->getUser($loginToken);
  88.         $sessionInfo = $session->getTokenInfo($loginToken);
  89.  
  90.         // 取得現在時間,用字串的形式
  91.         $nowDate = date("Y-m-d H:i:s");
  92.  
  93.         // 取得支援的教材類型
  94.         $db_material = new Database\DBMaterial();
  95.         $all_material_kind = $db_material->queryAllKind();
  96.  
  97.         // 輸出結果
  98.         $app->render(201,array(
  99.             'user_id'      => $user_id,
  100.             'token'        => $loginToken,
  101.             'browser'      => $browser,
  102.             'user' => array(
  103.                 'id'            => $user->getId(),
  104.                 'user_id'            => $user->getId(),
  105.                 'nickname'           => $user->getNickName(),
  106.                 'group_id'           => $user->getGroupID(),
  107.                 'group_name'         => $user->getGroupName(),
  108.                 'class_id'           => $user->getClassId(),
  109.                 'class_name'         => $user->getClassName(),
  110.                 'enable'             => $user->isEnable(),
  111.                 'build_time'         => $user->getCreateTime(),
  112.                 'modify_time'        => $user->getModifyTime(),
  113.                 'learnStyle_mode'    => $user->getLearnStyle(),
  114.                 'material_mode'      => $user->getMaterialStyle(),
  115.                 'enable_noAppoint'   => $user->isEnableNoAppoint(),
  116.                 'realname'           => $user->getRealName(),
  117.                 'email'              => $user->getEmail(),
  118.                 'memo'               => $user->getMemo(),
  119.             ),
  120.             'login_time'   => $sessionInfo['login_date'],
  121.             'current_time' => $nowDate,
  122.             'material_kind'=> $all_material_kind,
  123.             'error'        => false,
  124.             'msg'          => '\''.$user_id.'\' is logined',
  125.             'msg_cht'      => '\''.$user_id.'\'使用者已登入'
  126.         ));
  127.     }
  128.     catch (Exception\UserNoFoundException $e) {
  129.         $app->render(404,array(
  130.             'user_id'     => $user_id,
  131.             'browser'     => $browser,
  132.             'error'       => true,
  133.             'msg'         => '\''.$user_id.'\' is not found',
  134.             'msg_cht'     => '找不到\''.$user_id.'\'使用者'
  135.         ));
  136.     }
  137.     catch (Exception\UserPasswordErrException $e) {
  138.         $app->render(401,array(
  139.             'user_id'     => $user_id,
  140.             'browser'     => $browser,
  141.             'error'       => true,
  142.             'msg'         => 'Input \''.$user_id.'\' password is wrong',
  143.             'msg_cht'     => '\''.$user_id.'\'使用者密碼錯誤',
  144.             'substatus'   => 201
  145.         ));
  146.     }
  147.     catch (Exception\UserNoActivatedException $e) {
  148.         $app->render(401,array(
  149.             'user_id'     => $user_id,
  150.             'browser'     => $browser,
  151.             'error'       => true,
  152.             'msg'         => '\''.$user_id.'\' is not enable',
  153.             'msg_cht'     => '\''.$user_id.'\'帳號目前未啟用',
  154.             'substatus'   => 202
  155.         ));
  156.     }
  157. }
  158.  
  159. $app->group('/users', 'APIrequest', function () use ($app, $app_template) {
  160.  
  161.     /*
  162.      * 建立帳號
  163.      * POST http://localhost/api/v2/users
  164.      */
  165.     $app->post('/', function () use ($app) {
  166.         // 取得帶來的參數
  167.         $cType = $app->request->getContentType();
  168.         if($cType == 'application/x-www-form-urlencoded') {
  169.             $user_id          = $_POST['user_id'];
  170.             $password         = $_POST['password'];
  171.             $group_id         = $_POST['group_id'];
  172.             $class_id         = isset($_POST['class_id'])
  173.                                     ? $_POST['class_id'] : null;
  174.             $enable           = isset($_POST['enable'])
  175.                                     ? $_POST['enable'] : null;
  176.             $learnStyle_mode  = isset($_POST['learnStyle_mode'])
  177.                                     ? $_POST['learnStyle_mode'] : null;
  178.             $material_mode    = isset($_POST['material_mode'])
  179.                                     ? $_POST['material_mode'] : null;
  180.             $enable_noAppoint = isset($_POST['enable_noAppoint'])
  181.                                     ? $_POST['enable_noAppoint'] : null;
  182.             $nickname         = isset($_POST['nickname'])
  183.                                     ? $_POST['nickname'] : null;
  184.             $realname         = isset($_POST['realname'])
  185.                                     ? $_POST['realname'] : null;
  186.             $email            = isset($_POST['email'])
  187.                                     ? $_POST['email'] : null;
  188.             $memo             = isset($_POST['memo'])
  189.                                     ? $_POST['memo'] : null;;
  190.         }
  191.         else /*if($cType == 'application/json')*/ {
  192.             $postData = $app->request->getBody();
  193.             $postDataArray = json_decode($postData);
  194.             $user_id          = $postDataArray->user_id;
  195.             $password         = $postDataArray->password;
  196.             $group_id         = $postDataArray->group_id;
  197.             $class_id         = isset($postDataArray->class_id)
  198.                                     ? $postDataArray->class_id : null;
  199.             $enable           = isset($postDataArray->enable)
  200.                                     ? $postDataArray->enable : null;
  201.             $learnStyle_mode  = isset($postDataArray->learnStyle_mode)
  202.                                     ? $postDataArray->learnStyle_mode : null;
  203.             $material_mode    = isset($postDataArray->material_mode)
  204.                                     ? $postDataArray->material_mode : null;
  205.             $enable_noAppoint = isset($postDataArray->enable_noAppoint)
  206.                                     ? $postDataArray->enable_noAppoint : null;
  207.             $nickname         = isset($postDataArray->nickname)
  208.                                     ? $postDataArray->nickname : null;
  209.             $realname         = isset($postDataArray->realname)
  210.                                     ? $postDataArray->realname : null;
  211.             $email            = isset($postDataArray->email)
  212.                                     ? $postDataArray->email : null;
  213.             $memo             = isset($postDataArray->memo)
  214.                                     ? $postDataArray->memo : null;
  215.         }
  216.         /*else {
  217.             $app->render(400, array(
  218.                     'Content-Type'=> $cType,
  219.                     'error'       => true,
  220.                     'msg'     => '',
  221.                     'msg_cht' => '輸入參數的Content-Type不在支援範圍內 或是沒有輸入',
  222.                     'substatus'   => 102
  223.                 )
  224.             );
  225.         }*/
  226.  
  227.         // 建立使用者帳號
  228.         try {
  229.             $userAdmin = new User\UserAdmin();
  230.             $userAdmin->create(
  231.                 array( 'user_id'            => $user_id,
  232.                        'password'           => $password,
  233.                        'group_id'           => $group_id,
  234.                        'class_id'           => $class_id,
  235.                        'enable'             => $enable,
  236.                        'learnStyle_mode'    => $learnStyle_mode,
  237.                        'material_mode'      => $material_mode,
  238.                        'enable_noAppoint'   => $enable_noAppoint,
  239.                        'nickname'           => $nickname,
  240.                        'realname'           => $realname,
  241.                        'email'              => $email,
  242.                        'memo'               => $memo)
  243.             );
  244.  
  245.             // 顯示建立成功
  246.             $app->render(201,array(
  247.                 'user_id'            => $user_id,
  248.                 'group_id'           => $group_id,
  249.                 'class_id'           => $class_id,
  250.                 'enable'             => $enable,
  251.                 'learnStyle_mode'    => $learnStyle_mode,
  252.                 'material_mode'      => $material_mode,
  253.                 'enable_noAppoint'   => $enable_noAppoint,
  254.                 'nickname'           => $nickname,
  255.                 'realname'           => $realname,
  256.                 'email'              => $email,
  257.                 'memo'               => $memo,
  258.                 'error'   => false,
  259.                 'msg'     => '\''.$user_id.'\' is created.',
  260.                 'msg_cht' => '\''.$user_id.'\'使用者已成功建立'
  261.             ));
  262.  
  263.         }
  264.         // 若已有重複帳號名稱
  265.         catch (Exception\UserIdExistException $e) {
  266.              $app->render(409,array(
  267.                 'user_id'     => $user_id,
  268.                 'error'       => true,
  269.                 'msg'     => '\''.$user_id.'\' is exist.',
  270.                 'msg_cht' => '\''.$user_id.'\'使用者名稱已被使用'
  271.             ));
  272.         }
  273.     });
  274.  
  275.     /*
  276.      * 取得帳號資訊
  277.      * GET http://localhost/api/v2/users/{帳號ID}
  278.      */
  279.     $app->get('/:user_id', function ($user_id) use ($app) {
  280.  
  281.         try {
  282.             $user = new User\User($user_id);
  283.  
  284.             $app->render(200,array(
  285.                 'user_id'     => $user_id,
  286.                 'nickname'    => $user->getNickName(),
  287.                 'class_name'  => $user->getClassName(),
  288.                 'error'       => false
  289.             ));
  290.         }
  291.         catch (Exception\UserNoFoundException $e) {
  292.             $app->render(404,array(
  293.                 'user_id'     => $user_id,
  294.                 'error'       => true,
  295.                 'msg'     => '\''.$user_id.'\' is not found',
  296.                 'msg_cht' => '找不到\''.$user_id.'\'使用者'
  297.             ));
  298.         }
  299.     });
  300.  
  301.     /*
  302.      * 登入帳號
  303.      * POST http://localhost/api/v2/users/{帳號ID}/login
  304.      */
  305.     $app->post('/:user_id/login', 'login');
  306.  
  307. });
  308.  
  309. $app->group('/tokens', 'APIrequest', function () use ($app, $app_template) {
  310.  
  311.     /*
  312.      * 登入帳號
  313.      * POST http://localhost/api/v2/tokens
  314.      */
  315.     $app->post('/', 'login');
  316.  
  317.     /*
  318.      * 取得已登入的帳號資訊
  319.      * GET http://localhost/api/v2/tokens/{登入Token}
  320.      */
  321.     $app->get('/:token', function ($token) use ($app) {
  322.  
  323.         try {
  324.             // 正常寫法
  325.             $userSession = new User\UserSession();
  326.             $user = $userSession->getUser($token);
  327.  
  328.             $app->render(200,array(
  329.                 'token' => $token,
  330.                 'user' => array(
  331.                     'id'            => $user->getId(),
  332.                     'user_id'            => $user->getId(),
  333.                     'nickname'           => $user->getNickName(),
  334.                     'group_id'           => $user->getGroupID(),
  335.                     'group_name'         => $user->getGroupName(),
  336.                     'class_id'           => $user->getClassId(),
  337.                     'class_name'         => $user->getClassName(),
  338.                     'enable'             => $user->isEnable(),
  339.                     'build_time'         => $user->getCreateTime(),
  340.                     'modify_time'        => $user->getModifyTime(),
  341.                     'learnStyle_mode'    => $user->getLearnStyle(),
  342.                     'material_mode'      => $user->getMaterialStyle(),
  343.                     'enable_noAppoint'   => $user->isEnableNoAppoint(),
  344.                     'realname'           => $user->getRealName(),
  345.                     'email'              => $user->getEmail(),
  346.                     'memo'               => $user->getMemo(),
  347.                 ),
  348.                 'error' => false
  349.             ));
  350.         }
  351.         catch (Exception\LoginTokenNoFoundException $e) {
  352.             $app->render(404,array(
  353.                 'token'   => $token,
  354.                 'error'   => true,
  355.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  356.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  357.                 'substatus'   => 204
  358.             ));
  359.         }
  360.     });
  361.  
  362.     /*
  363.      * 登出此登入階段
  364.      * DELETE http://localhost/api/v2/tokens/{登入Token}
  365.      */
  366.     $app->delete('/:token', function ($token) use ($app) {
  367.  
  368.         try {
  369.             $session = new User\UserSession();
  370.             $user_id = $session->getUserId($token);
  371.             $session->logout($token);
  372.  
  373.             $app->render(204,array(
  374.                 'token'   => $token,
  375.                 'user_id' => $user_id,
  376.                 'error'   => false,
  377.                 'msg'     => '\''.$user_id.'\' this session is logout.',
  378.                 'msg_cht' => '\''.$user_id.'\'此登入階段已登出'
  379.             ));
  380.         }
  381.         catch (Exception\LoginTokenNoFoundException $e) {
  382.             $app->render(404,array(
  383.                 'token'   => $token,
  384.                 'error'   => true,
  385.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  386.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  387.                 'substatus'   => 204
  388.             ));
  389.         }
  390.     });
  391.  
  392.     /*
  393.      * 登出此此使用者其他登入階段
  394.      * DELETE http://localhost/api/v2/tokens/{登入Token}/session/other
  395.      */
  396.     $app->delete('/:token/session/other', function ($token) use ($app) {
  397.  
  398.         try {
  399.             $session = new User\UserSession();
  400.             $user_id = $session->getUserId($token);
  401.             $logoutTotal = $session->logoutOtherSession($token);
  402.             $inLoginTotal = $session->getCurrentLoginTotalByUserId($user_id);
  403.  
  404.             $app->render(204,array(
  405.                 'token'        => $token,
  406.                 'user_id'      => $user_id,
  407.                 'logout_total' => $logoutTotal,
  408.                 'login_total'  => $inLoginTotal,
  409.                 'error'        => false,
  410.                 'msg'          => '\''.$user_id.'\' other session is logout.',
  411.                 'msg_cht'      => '\''.$user_id.'\'此登入階段之外的皆已登出'
  412.             ));
  413.         }
  414.         catch (Exception\LoginTokenNoFoundException $e) {
  415.             $app->render(404,array(
  416.                 'token'   => $token,
  417.                 'error'   => true,
  418.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  419.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  420.                 'substatus'   => 204
  421.             ));
  422.         }
  423.     });
  424.  
  425.     // ------------------------------------------------------------------------
  426.  
  427.     /*
  428.      * 取得可用的學習活動
  429.      * GET http://localhost/api/v2/tokens/{登入Token}/activitys
  430.      */
  431.     $app->get('/:token/activitys', function ($token) use ($app) {
  432.         try {
  433.             $session = new User\UserSession();
  434.             $user_id = $session->getUserId($token);
  435.  
  436.             $studyMgr = new Study\StudyActivityManager();
  437.             $studyList = $studyMgr->getEnableActivityByUserId($user_id);
  438.  
  439.             // TODO: $studyList 分離重新包裝陣列
  440.             $app->render(200,array(
  441.                 'token'           => $token,
  442.                 'user_id'         => $user_id,
  443.                 'enable_activity' => $studyList,
  444.                 'error'           => false,
  445.             ));
  446.         }
  447.         catch (Exception\LoginTokenNoFoundException $e) {
  448.             $app->render(401,array(
  449.                 'token'   => $token,
  450.                 'error'   => true,
  451.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  452.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  453.                 'substatus'   => 204
  454.             ));
  455.         }
  456.     });
  457.  
  458.     /*
  459.      * 開始進行一場學習活動
  460.      * POST http://localhost/api/v2/tokens/{登入Token}/activitys
  461.      */
  462.     $app->post('/:token/activitys', function ($token) use ($app) {
  463.  
  464.         // 取得帶來的參數
  465.         $cType = $app->request->getContentType();
  466.         if($cType == 'application/x-www-form-urlencoded') {
  467.             $themeId          = $_POST['theme_id'];
  468.             $learnTime        = isset($_POST['learn_time'])
  469.                                     ? $_POST['learn_time'] : null;
  470.             $timeForce        = isset($_POST['time_force'])
  471.                                     ? $_POST['time_force'] : null;
  472.             $learnStyle       = isset($_POST['learnStyle_mode'])
  473.                                     ? $_POST['learnStyle_mode'] : null;
  474.             $learnStyle_force = isset($_POST['learnStyle_force'])
  475.                                     ? $_POST['learnStyle_force'] : null;
  476.             $enable_virtual   = isset($_POST['enable_virtual'])
  477.                                     ? $_POST['enable_virtual'] : null;
  478.             $materialMode     = isset($_POST['material_mode'])
  479.                                     ? $_POST['material_mode'] : null;
  480.         }
  481.         else /*if($cType == 'application/json')*/ {
  482.             $postData = $app->request->getBody();
  483.             $postDataArray = json_decode($postData);
  484.             //$user_id          = $postDataArray->user_id;
  485.             $app->render(400, array(
  486.                     'Content-Type'=> $cType,
  487.                     'error'       => true,
  488.                     'msg'     => '',
  489.                     'msg_cht' => '輸入參數的Content-Type不在支援範圍內 或是沒有輸入',
  490.                     'substatus'   => 102
  491.                 )
  492.             );
  493.         }
  494.         /*else {
  495.             $app->render(400, array(
  496.                     'Content-Type'=> $cType,
  497.                     'error'       => true,
  498.                     'msg'     => '',
  499.                     'msg_cht' => '輸入參數的Content-Type不在支援範圍內 或是沒有輸入',
  500.                     'substatus'   => 102
  501.                 )
  502.             );
  503.         }*/
  504.  
  505.         try {
  506.             // 查詢使用者
  507.             $session = new User\UserSession();
  508.             $user_id = $session->getUserId($token);
  509.  
  510.             // 開始進行學習活動
  511.             $studyMgr = new Study\StudyActivityManager();
  512.             $studyId  = $studyMgr->startActivity($user_id, $themeId,
  513.                                                  $learnTime, $timeForce,
  514.                                                  $learnStyle, $learnStyle_force,
  515.                                                  $enable_virtual, $materialMode);
  516.  
  517.             // 取得開始後的學習活動資訊
  518.             $sact = new Study\StudyActivity($studyId);
  519.  
  520.             // 取得此活動的主題
  521.             $tid = $sact->getThemeId();
  522.  
  523.             // 取得主題內所有的標的資訊
  524.             $target_manager = new Target\TargetManager();
  525.             $all_targets = $target_manager->getAllTargetInfoByTheme($tid);
  526.  
  527.             // 取得本次採用的教材風格
  528.             $materialMode = $sact->getMaterialStyle();
  529.  
  530.             // 處理噴出結果
  531.             $output_targets = array();
  532.             foreach($all_targets as $thisTargetArray) {
  533.  
  534.                 // 取得教材路徑
  535.                 $targetObject = new Target\Target($thisTargetArray['target_id']);
  536.                 $materialUrl = $targetObject->getMaterialUrl(true, $materialMode);
  537.                 $virtualMaterialUrl = $targetObject->getMaterialUrl(false, $materialMode);
  538.  
  539.                 $thisOutput = array(
  540.                     'theme_id'      => $thisTargetArray['theme_id'],
  541.                     'target_id'     => $thisTargetArray['target_id'],
  542.                     'weights'       => $thisTargetArray['weights'],
  543.                     'hall_id'       => $thisTargetArray['hall_id'],
  544.                     'hall_name'     => $thisTargetArray['hall_name'],
  545.                     'area_id'       => $thisTargetArray['area_id'],
  546.                     'area_name'     => $thisTargetArray['area_name'],
  547.                     'floor'         => $thisTargetArray['floor'],
  548.                     'area_number'   => $thisTargetArray['area_number'],
  549.                     'target_number' => $thisTargetArray['target_number'],
  550.                     'name'          => $thisTargetArray['name'],
  551.                     'map_url'       => $thisTargetArray['map_url'],
  552.                     'material_url'  => $materialUrl,
  553.                     'virtual_material_url' => $virtualMaterialUrl,
  554.                     'learn_time'    => $thisTargetArray['learn_time'],
  555.                     'PLj'           => $thisTargetArray['PLj'],
  556.                     'Mj'            => $thisTargetArray['Mj'],
  557.                     'S'             => $thisTargetArray['S'],
  558.                     'Fj'            => $thisTargetArray['Fj']
  559.                 );
  560.                 array_push($output_targets, $thisOutput);
  561.             }
  562.  
  563.             // 噴出結果
  564.             $app->render(200,array(
  565.                 'token'       => $token,
  566.                 'user_id'     => $user_id,
  567.                 'activity_id' => $sact->getId(),
  568.                 'activity'    => array(
  569.                     'activity_id'      => $sact->getId(),
  570.                     'theme_id'         => $sact->getThemeId(),
  571.                     'theme_name'       => $sact->getThemeName(),
  572.                     'start_target_id'  => $sact->getStartTargetId(),
  573.                     'start_time'       => $sact->getStartTime(),
  574.                     'expired_time'     => $sact->getExpiredTime(),
  575.                     'have_time'        => $sact->getRealLearnTime(),
  576.                     'learn_time'       => $sact->getLearnTime(),
  577.                     'delay'            => $sact->getDelay(),
  578.                     'remaining_time'   => $sact->getRealLearnTime(),
  579.                     'time_force'       => $sact->isForceLearnTime(),
  580.                     'learnStyle_mode'  => $sact->getLearnStyle(),
  581.                     'learnStyle_force' => $sact->isForceLearnStyle(),
  582.                     'enable_virtual'   => $sact->isEnableVirtual(),
  583.                     'material_mode'    => $sact->getMaterialStyle(),
  584.                     'target_total'     => $sact->getPointTotal(),
  585.                     'learned_total'    => $sact->getLearnedPointTotal()
  586.                 ),
  587.                 'targets'    => $output_targets,
  588.                 'error'            => false
  589.             ));
  590.         }
  591.         catch (Exception\LoginTokenNoFoundException $e) {
  592.             $app->render(401,array(
  593.                 'token'   => $token,
  594.                 'error'   => true,
  595.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  596.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  597.                 'substatus'   => 204
  598.             ));
  599.         }
  600.         catch (Exception\StudyActivityNoFoundException $e) {
  601.             $app->render(500,array(
  602.                 'token'   => $token,
  603.                 'error'   => true,
  604.                 'msg'     => 'Start activity fail.',
  605.                 'msg_cht' => '建立學習活動失敗'
  606.             ));
  607.         }
  608.  
  609.     });
  610.  
  611.     /*
  612.      * 取得學習中狀況資料
  613.      * GET http://localhost/api/v2/tokens/{登入Token}/activitys/{學習中活動編號}
  614.      */
  615.     $app->get('/:token/activitys/:said', function ($token, $saId) use ($app) {
  616.  
  617.         try {
  618.             // 查詢使用者
  619.             $session = new User\UserSession();
  620.             $user_id = $session->getUserId($token);
  621.  
  622.             // 取得開始後的學習活動資訊
  623.             $sact = new Study\StudyActivity($saId);
  624.  
  625.             // TODO: 取得主題內所有的標的資訊
  626.  
  627.             // 確認此學習活動是否為本人所有
  628.             if($sact->getUserId() == $user_id) {
  629.  
  630.                 // 取得此活動的主題
  631.                 $tid = $sact->getThemeId();
  632.  
  633.                 // 取得主題內所有的標的資訊
  634.                 $target_manager = new Target\TargetManager();
  635.                 $all_targets = $target_manager->getAllTargetInfoByTheme($tid);
  636.  
  637.                 // 取得本次採用的教材風格
  638.                 $materialMode = $sact->getMaterialStyle();
  639.  
  640.                 // 處理噴出結果
  641.                 $output_targets = array();
  642.                 foreach($all_targets as $thisTargetArray) {
  643.  
  644.                     // 取得教材路徑
  645.                     $targetObject = new Target\Target($thisTargetArray['target_id']);
  646.                     $materialUrl = $targetObject->getMaterialUrl(true, $materialMode);
  647.                     $virtualMaterialUrl = $targetObject->getMaterialUrl(false, $materialMode);
  648.  
  649.                     $thisOutput = array(
  650.                         'theme_id'      => $thisTargetArray['theme_id'],
  651.                         'target_id'     => $thisTargetArray['target_id'],
  652.                         'weights'       => $thisTargetArray['weights'],
  653.                         'hall_id'       => $thisTargetArray['hall_id'],
  654.                         'hall_name'     => $thisTargetArray['hall_name'],
  655.                         'area_id'       => $thisTargetArray['area_id'],
  656.                         'area_name'     => $thisTargetArray['area_name'],
  657.                         'floor'         => $thisTargetArray['floor'],
  658.                         'area_number'   => $thisTargetArray['area_number'],
  659.                         'target_number' => $thisTargetArray['target_number'],
  660.                         'name'          => $thisTargetArray['name'],
  661.                         'map_url'       => $thisTargetArray['map_url'],
  662.                         'material_url'  => $materialUrl,
  663.                         'virtual_material_url' => $virtualMaterialUrl,
  664.                         'learn_time'    => $thisTargetArray['learn_time'],
  665.                         'PLj'           => $thisTargetArray['PLj'],
  666.                         'Mj'            => $thisTargetArray['Mj'],
  667.                         'S'             => $thisTargetArray['S'],
  668.                         'Fj'            => $thisTargetArray['Fj']
  669.                     );
  670.                     array_push($output_targets, $thisOutput);
  671.                 }
  672.  
  673.                 // 噴出資訊
  674.                 $app->render(200,array(
  675.                     'token'       => $token,
  676.                     'user_id'     => $user_id,
  677.                     'activity_id' => $sact->getId(),
  678.                     'activity'    => array(
  679.                         'activity_id'      => $sact->getId(),
  680.                         'theme_id'         => $sact->getThemeId(),
  681.                         'theme_name'       => $sact->getThemeName(),
  682.                         'start_target_id'  => $sact->getStartTargetId(),
  683.                         'start_time'       => $sact->getStartTime(),
  684.                         'expired_time'     => $sact->getExpiredTime(),
  685.                         'have_time'        => $sact->getRealLearnTime(),
  686.                         'learn_time'       => $sact->getLearnTime(),
  687.                         'delay'            => $sact->getDelay(),
  688.                         'remaining_time'   => $sact->getRemainingTime(),
  689.                         'time_force'       => $sact->isForceLearnTime(),
  690.                         'learnStyle_mode'  => $sact->getLearnStyle(),
  691.                         'learnStyle_force' => $sact->isForceLearnStyle(),
  692.                         'enable_virtual'   => $sact->isEnableVirtual(),
  693.                         'material_mode'    => $sact->getMaterialStyle(),
  694.                         'target_total'     => $sact->getPointTotal(),
  695.                         'learned_total'    => $sact->getLearnedPointTotal()
  696.                     ),
  697.                     'targets'    => $output_targets,
  698.                     'error'            => false
  699.                 ));
  700.             }
  701.             // 若非本人所有,則視同無此活動
  702.             else {
  703.                 throw new Exception\StudyActivityNoFoundException($saId);
  704.             }
  705.  
  706.         }
  707.         catch (Exception\LoginTokenNoFoundException $e) {
  708.             $app->render(401,array(
  709.                 'token'   => $token,
  710.                 'error'   => true,
  711.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  712.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  713.                 'substatus'   => 204
  714.             ));
  715.         }
  716.         catch (Exception\StudyActivityNoFoundException $e) {
  717.             $app->render(404,array(
  718.                 'token'   => $token,
  719.                 'error'   => true,
  720.                 'msg'     => 'No found this activity.',
  721.                 'msg_cht' => '沒有此學習活動'
  722.             ));
  723.         }
  724.     });
  725.  
  726.     /*
  727.      * 結束這場學習活動
  728.      * POST http://localhost/api/v2/tokens/{登入Token}/activitys/{學習中活動編號}/finish
  729.      */
  730.     $app->post('/:token/activitys/:said/finish', function ($token, $saId) use ($app) {
  731.  
  732.         try {
  733.             // 查詢使用者
  734.             $session = new User\UserSession();
  735.             $user_id = $session->getUserId($token);
  736.  
  737.             // 取得開始後的學習活動資訊
  738.             $sact = new Study\StudyActivity($saId);
  739.  
  740.             // 確認此學習活動是否為本人所有
  741.             if($sact->getUserId() == $user_id) {
  742.  
  743.                 // 結束學習活動
  744.  
  745.                 $sact->finishActivity();
  746.  
  747.                 // 噴出學習完畢後的活動資料
  748.                 $app->render(201,array(
  749.                     'token'       => $token,
  750.                     'user_id'     => $user_id,
  751.                     'activity_id' => $sact->getId(),
  752.                     'activity'    => array(
  753.                         'activity_id'      => $sact->getId(),
  754.                         'theme_id'         => $sact->getThemeId(),
  755.                         'theme_name'       => $sact->getThemeName(),
  756.                         'start_time'       => $sact->getStartTime(),
  757.                         'end_time'         => $sact->getEndTime(),
  758.                         'learnStyle_mode'  => $sact->getLearnStyle(),
  759.                         'learnStyle_force' => $sact->isForceLearnStyle(),
  760.                         'enable_virtual'   => $sact->isEnableVirtual(),
  761.                         'material_mode'    => $sact->getMaterialStyle(),
  762.                         'target_total'     => $sact->getPointTotal(),
  763.                         'learned_total'    => $sact->getLearnedPointTotal()
  764.                     ),
  765.                     'error'            => false
  766.                 ));
  767.             }
  768.             // 若非本人所有,則視同無此活動
  769.             else {
  770.                 throw new Exception\StudyActivityNoFoundException($saId);
  771.             }
  772.         }
  773.         catch (Exception\LoginTokenNoFoundException $e) {
  774.             $app->render(401,array(
  775.                 'token'   => $token,
  776.                 'error'   => true,
  777.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  778.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  779.                 'substatus'   => 204
  780.             ));
  781.         }
  782.         catch (Exception\StudyActivityNoFoundException $e) {
  783.             $app->render(404,array(
  784.                 'token'   => $token,
  785.                 'error'   => true,
  786.                 'msg'     => 'No found this activity.',
  787.                 'msg_cht' => '沒有此學習活動'
  788.             ));
  789.         }
  790.         catch (Exception\StudyActivityFinishedException $e) {
  791.             $app->render(405,array(
  792.                 'token'       => $token,
  793.                 'user_id'     => $user_id,
  794.                 'activity_id' => $sact->getId(),
  795.                 'activity'    => array(
  796.                     'activity_id'      => $sact->getId(),
  797.                     'theme_id'         => $sact->getThemeId(),
  798.                     'theme_name'       => $sact->getThemeName(),
  799.                     'start_time'       => $sact->getStartTime(),
  800.                     'end_time'         => $sact->getEndTime(),
  801.                     'learnStyle_mode'  => $sact->getLearnStyle(),
  802.                     'learnStyle_force' => $sact->isForceLearnStyle(),
  803.                     'material_mode'    => $sact->getMaterialStyle(),
  804.                     'target_total'     => $sact->getPointTotal(),
  805.                     'learned_total'    => $sact->getLearnedPointTotal()
  806.                 ),
  807.                 'error'   => true,
  808.                 'msg'     => 'The activity is endded',
  809.                 'msg_cht' => '此活動已經結束了'
  810.             ));
  811.         }
  812.     });
  813.  
  814.     /*
  815.      * 預約學習活動資料
  816.      * GET http://localhost/api/v2/tokens/{登入Token}/will/{預約編號}
  817.      */
  818.     $app->get('/:token/will/:swid', function ($token, $swId) use ($app) {
  819.         // TODO: 學習中狀況資料
  820.     });
  821.  
  822.     // ------------------------------------------------------------------------
  823.  
  824.     /*
  825.      * 取得此活動中所有的標的資料
  826.      * GET http://localhost/api/v2/tokens/{登入Token}/activitys/{學習中活動編號}/points
  827.      */
  828.     $app->get('/:token/activitys/:said/points', function ($token, $saId) use ($app) {
  829.  
  830.         try {
  831.             // 查詢使用者
  832.             $session = new User\UserSession();
  833.             $user_id = $session->getUserId($token);
  834.  
  835.             // 取得開始後的學習活動資訊
  836.             $sact = new Study\StudyActivity($saId);
  837.  
  838.             // 確認此學習活動是否為本人所有
  839.             if($sact->getUserId() == $user_id) {
  840.  
  841.                 // 取得此活動的主題
  842.                 $tid = $sact->getThemeId();
  843.  
  844.                 // 取得主題內所有的標的資訊
  845.                 $target_manager = new Target\TargetManager();
  846.                 $all_targets = $target_manager->getAllTargetInfoByTheme($tid);
  847.  
  848.                 // 取得本次採用的教材風格
  849.                 $materialMode = $sact->getMaterialStyle();
  850.  
  851.                 // 處理噴出結果
  852.                 $output_targets = array();
  853.                 foreach($all_targets as $thisTargetArray) {
  854.  
  855.                     // 取得教材路徑
  856.                     $targetObject = new Target\Target($thisTargetArray['target_id']);
  857.                     $materialUrl = $targetObject->getMaterialUrl(true, $materialMode);
  858.                     $virtualMaterialUrl = $targetObject->getMaterialUrl(false, $materialMode);
  859.  
  860.                     $thisOutput = array(
  861.                         'theme_id'      => $thisTargetArray['theme_id'],
  862.                         'target_id'     => $thisTargetArray['target_id'],
  863.                         'weights'       => $thisTargetArray['weights'],
  864.                         'hall_id'       => $thisTargetArray['hall_id'],
  865.                         'hall_name'     => $thisTargetArray['hall_name'],
  866.                         'area_id'       => $thisTargetArray['area_id'],
  867.                         'area_name'     => $thisTargetArray['area_name'],
  868.                         'floor'         => $thisTargetArray['floor'],
  869.                         'area_number'   => $thisTargetArray['area_number'],
  870.                         'target_number' => $thisTargetArray['target_number'],
  871.                         'name'          => $thisTargetArray['name'],
  872.                         'map_url'       => $thisTargetArray['map_url'],
  873.                         'material_url'  => $materialUrl,
  874.                         'virtual_material_url' => $virtualMaterialUrl,
  875.                         'learn_time'    => $thisTargetArray['learn_time'],
  876.                         'PLj'           => $thisTargetArray['PLj'],
  877.                         'Mj'            => $thisTargetArray['Mj'],
  878.                         'S'             => $thisTargetArray['S'],
  879.                         'Fj'            => $thisTargetArray['Fj']
  880.                     );
  881.                     array_push($output_targets, $thisOutput);
  882.                 }
  883.  
  884.                 // 噴出結果
  885.                 $app->render(200,array(
  886.                     'token'       => $token,
  887.                     'user_id'     => $user_id,
  888.                     'activity_id' => $sact->getId(),
  889.                     'targets'    => $output_targets,
  890.                     'error'            => false
  891.                 ));
  892.  
  893.             }
  894.             // 若非本人所有,則視同無此活動
  895.             else {
  896.                 throw new Exception\StudyActivityNoFoundException($saId);
  897.             }
  898.  
  899.         }
  900.         catch (Exception\LoginTokenNoFoundException $e) {
  901.             $app->render(401,array(
  902.                 'token'   => $token,
  903.                 'error'   => true,
  904.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  905.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  906.                 'substatus'   => 204
  907.             ));
  908.         }
  909.         catch (Exception\StudyActivityNoFoundException $e) {
  910.             $app->render(404,array(
  911.                 'token'   => $token,
  912.                 'error'   => true,
  913.                 'msg'     => 'No found this activity.',
  914.                 'msg_cht' => '沒有此學習活動'
  915.             ));
  916.         }
  917.     });
  918.  
  919.     /*
  920.      * 取得此標的資料
  921.      * GET http://localhost/api/v2/tokens/{登入Token}/activitys/{學習中活動編號}/points/{標的編號}
  922.      */
  923.     $app->get('/:token/activitys/:said/points/:tid', function ($token, $saId, $tId) use ($app) {
  924.  
  925.         try {
  926.             // 查詢使用者
  927.             $session = new User\UserSession();
  928.             $user_id = $session->getUserId($token);
  929.  
  930.             // 取得開始後的學習活動資訊
  931.             $sact = new Study\StudyActivity($saId);
  932.  
  933.             // 確認此學習活動是否為本人所有
  934.             if($sact->getUserId() == $user_id) {
  935.  
  936.                 // 取得此活動的主題
  937.                 $thid = $sact->getThemeId();
  938.  
  939.                 // 取得本次採用的教材風格
  940.                 $materialMode = $sact->getMaterialStyle();
  941.  
  942.                 // 取得主題內所有的標的資訊
  943.                 $target = new Target\Target($thid);
  944.                 $materialUrl = $target->getMaterialUrl(true, $materialMode);
  945.                 $virtualMaterialUrl = $target->getMaterialUrl(false, $materialMode);
  946.  
  947.                 // 處理噴出結果
  948.                 $output_targets = array(
  949.                         'theme_id'      => $thid,
  950.                         'target_id'     => $target->getId(),
  951.                         'hall_id'       => $target->getHallId(),
  952.                         //'hall_name'     => $thisTargetArray['hall_name'],
  953.                         'area_id'       => $target->getAreaId(),
  954.                         //'area_name'     => $thisTargetArray['area_name'],
  955.                         //'floor'         => $thisTargetArray['floor'],
  956.                         //'area_number'   => $thisTargetArray['area_number'],
  957.                         'target_number' => $target->getNumber(),
  958.                         'name'          => $target->getName(),
  959.                         'map_url'       => $target->getMapUrl(),
  960.                         'material_url'  => $materialUrl,
  961.                         'virtual_material_url' => $virtualMaterialUrl,
  962.                         'learn_time'    => $target->getLearnTime(),
  963.                         'PLj'           => $target->getPLj(),
  964.                         'Mj'            => $target->getMj(),
  965.                         'S'             => $target->getS(),
  966.                         'Fj'            => $target->getFj()
  967.                 );
  968.  
  969.                 // 噴出結果
  970.                 $app->render(200,array(
  971.                     'token'       => $token,
  972.                     'user_id'     => $user_id,
  973.                     'activity_id' => $sact->getId(),
  974.                     'target'      => $output_targets,
  975.                     'error'       => false
  976.                 ));
  977.  
  978.             }
  979.             // 若非本人所有,則視同無此活動
  980.             else {
  981.                 throw new Exception\StudyActivityNoFoundException($saId);
  982.             }
  983.  
  984.         }
  985.         catch (Exception\LoginTokenNoFoundException $e) {
  986.             $app->render(401,array(
  987.                 'token'   => $token,
  988.                 'error'   => true,
  989.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  990.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  991.                 'substatus'   => 204
  992.             ));
  993.         }
  994.         catch (Exception\StudyActivityNoFoundException $e) {
  995.             $app->render(404,array(
  996.                 'token'   => $token,
  997.                 'error'   => true,
  998.                 'msg'     => 'No found this activity.',
  999.                 'msg_cht' => '沒有此學習活動'
  1000.             ));
  1001.         }
  1002.     });
  1003.  
  1004.  
  1005.     /*
  1006.      * 進入此學習點
  1007.      * POST http://localhost/api/v2/tokens/{登入Token}/activitys/{學習中活動編號}/points/{標的編號}/toin
  1008.      */
  1009.     $app->post('/:token/activitys/:said/points/:tid/toin', function ($token, $saId, $tId) use ($app) {
  1010.  
  1011.         // 取得帶來的參數
  1012.         $cType = $app->request->getContentType();
  1013.         if($cType == 'application/x-www-form-urlencoded') {
  1014.             $is_entity  = isset($_POST['is_entity']) ? $_POST['is_entity'] : true;
  1015.         }
  1016.         else /*if($cType == 'application/json')*/ {
  1017.             $postData = $app->request->getBody();
  1018.             $postDataArray = json_decode($postData);
  1019.             $is_entity  = isset($postDataArray->is_entity)
  1020.                             ? $postDataArray->is_entity : true;
  1021.         }
  1022.         /*else {
  1023.             $app->render(400, array(
  1024.                     'Content-Type'=> $cType,
  1025.                     'error'       => true,
  1026.                     'msg'     => '',
  1027.                     'msg_cht' => '輸入參數的Content-Type不在支援範圍內 或是沒有輸入',
  1028.                     'substatus'   => 102
  1029.                 )
  1030.             );
  1031.         }*/
  1032.  
  1033.         try {
  1034.             // 查詢使用者
  1035.             $session = new User\UserSession();
  1036.             $user_id = $session->getUserId($token);
  1037.  
  1038.             // 取得開始後的學習活動資訊
  1039.             $sact = new Study\StudyActivity($saId);
  1040.  
  1041.             // 確認此學習活動是否為本人所有
  1042.             if($sact->getUserId() == $user_id) {
  1043.  
  1044.                 // 進入學習點
  1045.                 try{
  1046.                     $sid = $sact->toInTarget($tId, $is_entity);
  1047.  
  1048.                     // 噴出結果
  1049.                     $app->render(200,array(
  1050.                         'token'       => $token,
  1051.                         'user_id'     => $user_id,
  1052.                         'activity_id' => $sact->getId(),
  1053.                         'study_id'    => $sid,
  1054.                         'error'       => false
  1055.                     ));
  1056.                 }
  1057.                 // 若狀態為正在標的內學習時,強制當成離開標的,重新進入
  1058.                 catch (Exception\InLearningException $e) {
  1059.  
  1060.                     // 查詢目前所在的標的
  1061.                     $inTId = $sact->getCurrentInTarget();
  1062.  
  1063.                     // 登記離開此標的
  1064.                     $sact->toOutTarget($inTId);
  1065.  
  1066.                     // 重新登記進入此標的
  1067.                     $sid = $sact->toInTarget($tId, $is_entity);
  1068.  
  1069.                     // 噴出結果
  1070.                     $app->render(200,array(
  1071.                         'token'       => $token,
  1072.                         'user_id'     => $user_id,
  1073.                         'activity_id' => $sact->getId(),
  1074.                         'study_id'    => $sid,
  1075.                         'error'       => false
  1076.                     ));
  1077.                 }
  1078.  
  1079.             }
  1080.             // 若非本人所有,則視同無此活動
  1081.             else {
  1082.                 throw new Exception\StudyActivityNoFoundException($saId);
  1083.             }
  1084.  
  1085.         }
  1086.         catch (Exception\LoginTokenNoFoundException $e) {
  1087.             $app->render(401,array(
  1088.                 'token'   => $token,
  1089.                 'error'   => true,
  1090.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  1091.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  1092.                 'substatus'   => 204
  1093.             ));
  1094.         }
  1095.         catch (Exception\StudyActivityNoFoundException $e) {
  1096.             $app->render(404,array(
  1097.                 'token'   => $token,
  1098.                 'error'   => true,
  1099.                 'msg'     => 'No found this activity.',
  1100.                 'msg_cht' => '沒有此學習活動'
  1101.             ));
  1102.         }
  1103.  
  1104.     });
  1105.  
  1106.     /*
  1107.      * 離開此學習點
  1108.      * POST http://localhost/api/v2/tokens/{登入Token}/activitys/{學習中活動編號}/points/{標的編號}/toout
  1109.      */
  1110.     $app->post('/:token/activitys/:said/points/:tid/toout', function ($token, $saId, $tId) use ($app) {
  1111.  
  1112.         $app = \Slim\Slim::getInstance();
  1113.  
  1114.         // 取得帶來的參數
  1115.         $cType = $app->request->getContentType();
  1116.  
  1117.         if($cType == 'application/json') {
  1118.             $postData = $app->request->getBody();
  1119.             $postDataJson = json_decode($postData);
  1120.  
  1121.             $ans_json = $postDataJson->answers;
  1122.         }
  1123.  
  1124.         try {
  1125.             // 查詢使用者
  1126.             $session = new User\UserSession();
  1127.             $user_id = $session->getUserId($token);
  1128.  
  1129.             // 取得開始後的學習活動資訊
  1130.             $sact = new Study\StudyActivity($saId);
  1131.  
  1132.             // 確認此學習活動是否為本人所有
  1133.             if($sact->getUserId() == $user_id) {
  1134.  
  1135.                 // 離開學習點
  1136.                 try {
  1137.                     $sact->toOutTarget($tId);
  1138.  
  1139.                     // 紀錄回答問題
  1140.                     $db_recommend = new Database\DBQuestion();
  1141.                     foreach($ans_json as $the_ans) {
  1142.                         $db_recommend->insert($saId, $the_ans->target_id, $the_ans->question_time, $the_ans->answer_time, $the_ans->quest_id, $the_ans->answer, $the_ans->correct);
  1143.                     }
  1144.  
  1145.                     // 噴出結果
  1146.                     $app->render(201,array(
  1147.                         'token'       => $token,
  1148.                         'user_id'     => $user_id,
  1149.                         'answers'     => $ans_json,
  1150.                         'activity_id' => $sact->getId(),
  1151.                         'error'       => false
  1152.                     ));
  1153.                 }
  1154.                 // 如果此標的尚未登記為已進入
  1155.                 catch (Exception\NoInLearningException $e) {
  1156.                     // 當作進去此標的
  1157.                     // TODO: 這邊先暫時當成是以實體方式進入,之後要修成Client發出離開訊息時,也一併帶入剛剛的為實體or虛擬
  1158.                     $sact->toInTarget($tId, true);
  1159.                     $sact->toOutTarget($tId);
  1160.  
  1161.                     // 紀錄回答問題
  1162.                     $db_recommend = new Database\DBQuestion();
  1163.                     foreach($ans_json as $the_ans) {
  1164.                         $db_recommend->insert($saId, $the_ans->target_id, $the_ans->question_time, $the_ans->answer_time, $the_ans->quest_id, $the_ans->answer, $the_ans->correct);
  1165.                     }
  1166.  
  1167.                     // 噴出結果
  1168.                     $app->render(201,array(
  1169.                         'token'       => $token,
  1170.                         'user_id'     => $user_id,
  1171.                         'answers'     => $ans_json,
  1172.                         'activity_id' => $sact->getId(),
  1173.                         'error'       => false
  1174.                     ));
  1175.  
  1176.                     // 噴出結果
  1177.                     $app->render(201,array(
  1178.                         'token'       => $token,
  1179.                         'user_id'     => $user_id,
  1180.                         'activity_id' => $sact->getId(),
  1181.                         'error'       => false
  1182.                     ));
  1183.                 }
  1184.  
  1185.             }
  1186.             // 若非本人所有,則視同無此活動
  1187.             else {
  1188.                 throw new Exception\StudyActivityNoFoundException($saId);
  1189.             }
  1190.  
  1191.         }
  1192.         catch (Exception\LoginTokenNoFoundException $e) {
  1193.             $app->render(401,array(
  1194.                 'token'   => $token,
  1195.                 'error'   => true,
  1196.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  1197.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  1198.                 'substatus'   => 204
  1199.             ));
  1200.         }
  1201.         catch (Exception\StudyActivityNoFoundException $e) {
  1202.             $app->render(404,array(
  1203.                 'token'   => $token,
  1204.                 'error'   => true,
  1205.                 'msg'     => 'No found this activity.',
  1206.                 'msg_cht' => '沒有此學習活動'
  1207.             ));
  1208.         }
  1209.  
  1210.     });
  1211.  
  1212.     /*
  1213.      * 推薦學習點
  1214.      * POST http://localhost/api/v2/tokens/{登入Token}/activitys/{學習中活動編號}/recommand?current_point={目前所在的學習點編號}
  1215.      * TODO: 將上方的重複的程式碼片段獨立開來
  1216.      */
  1217.     $app->post('/:token/activitys/:said/recommand', function ($token, $saId) use ($app) {
  1218.         if(isset($_GET['current_point'])) { $currentTId = $_GET['current_point']; }
  1219.  
  1220.         function output_the_target_array($tId, $isEntity, $materialMode) {
  1221.             $thisOutput = array();
  1222.             $target = new Target\Target($tId);
  1223.             $thisOutput = array(
  1224.                 'target_id'     => $target->getId(),
  1225.                 'is_entity'     => $isEntity,
  1226.                 'hall_id'       => $target->getHallId(),
  1227.                 'area_id'       => $target->getAreaId(),
  1228.                 'target_number' => $target->getNumber(),
  1229.                 'name'          => $target->getName(),
  1230.                 'map_url'       => $target->getMapUrl(),
  1231.                 'material_url'  => $target->getMaterialUrl($isEntity, $materialMode),
  1232.                 'learn_time'    => $target->getLearnTime(),
  1233.                 'PLj'           => $target->getPLj(),
  1234.                 'Mj'            => $target->getMj(),
  1235.                 'S'             => $target->getS(),
  1236.                 'Fj'            => $target->getFj()
  1237.             );
  1238.             return $thisOutput;
  1239.         }
  1240.  
  1241.         try {
  1242.             // 查詢使用者
  1243.             $session = new User\UserSession();
  1244.             $user_id = $session->getUserId($token);
  1245.  
  1246.             // 取得開始後的學習活動資訊
  1247.             $sact = new Study\StudyActivity($saId);
  1248.  
  1249.             // 確認此學習活動是否為本人所有
  1250.             if($sact->getUserId() == $user_id) {
  1251.  
  1252.                 // 必填參數有填
  1253.                 if( isset($currentTId) ) {
  1254.  
  1255.                     // 查詢目前所在的標的
  1256.                     $inTId = $sact->getCurrentInTarget();
  1257.                     // 登記離開此標的
  1258.                     if($inTId) {
  1259.                         $sact->toOutTarget($inTId);
  1260.                     }
  1261.  
  1262.                     $currentTId = (int)$currentTId;
  1263.  
  1264.                     $tid = $sact->getThemeId(); // 取得此活動的主題
  1265.                     $maxItemTotal = $sact->getLearnStyle(); // 取得最大推薦數
  1266.  
  1267.                     // 取得本次採用的教材風格
  1268.                     $materialMode = $sact->getMaterialStyle();
  1269.  
  1270.                     // 學習時間已過並設強制結束
  1271.                     if($sact->isForceLearnTime() && $sact->getRemainingTime() <= 0) {
  1272.                         $isEnd = true;
  1273.  
  1274.                         $result_recommand_total = 0;
  1275.                         $output_targets = array();
  1276.                     }
  1277.                     // 是否已經學完了
  1278.                     else if($sact->getRemainingPointTotal() <= 0) {
  1279.                         $isEnd = true;
  1280.  
  1281.                         $result_recommand_total = 0;
  1282.                         $output_targets = array();
  1283.                     }
  1284.                     else {
  1285.                         $isEnd = false;
  1286.  
  1287.                         // 若設定為自由探索
  1288.                         if($maxItemTotal == 0) {
  1289.  
  1290.                             // 取得主題內所有的標的資訊
  1291.                             $target_manager = new Target\TargetManager();
  1292.                             $all_targets = $target_manager->getAllTargetInfoByTheme($tid);
  1293.  
  1294.                             $theme_ids = array();
  1295.                             foreach($all_targets as $the_target) {
  1296.                                 array_push($theme_ids, $the_target['target_id']);
  1297.                             }
  1298.  
  1299.                             // 過濾已學習過標的
  1300.                             $studyMng = new Study\StudyManager();
  1301.                             $learn_ids = $studyMng->getLearnedTargetId($saId);
  1302.  
  1303.                             if(count($learn_ids)>0) {
  1304.                                 $recommandResult = array_diff($theme_ids,$learn_ids);
  1305.                                 $result_recommand_total = count($theme_ids) - count($learn_ids);
  1306.  
  1307.                             }
  1308.                             else {
  1309.                                 $recommandResult = $theme_ids;
  1310.                                 $result_recommand_total = count($theme_ids);
  1311.                             }
  1312.                             $output_targets = array();
  1313.                             foreach($recommandResult as $theresult) {
  1314.                                 array_push($output_targets, output_the_target_array($theresult, true, $materialMode));
  1315.                             }
  1316.  
  1317.                         }
  1318.                         else {
  1319.                             // 取得推薦的學習點
  1320.                             $recommand = new Recommand\RecommandPoint();
  1321.                             $recommandResult = $recommand->recommand($currentTId, $saId);
  1322.                             $recommandTotal = count($recommandResult);
  1323.                             if($recommandTotal > $maxItemTotal) {
  1324.                                 $result_recommand_total = $maxItemTotal;
  1325.                             }
  1326.                             else {
  1327.                                 $result_recommand_total = $recommandTotal;
  1328.                             }
  1329.  
  1330.                             // 製作
  1331.                             $output_targets = array();
  1332.                             $output_target_ids = array();
  1333.                             for($i=0; $i<$result_recommand_total; $i++) {
  1334.                                 $target_id = $recommandResult[$i]['nextPoint'];
  1335.                                 $isEntity = $recommandResult[$i]['isEntity'];
  1336.                                 array_push($output_targets, output_the_target_array($target_id, $isEntity, $materialMode));
  1337.                                 array_push($output_target_ids, $target_id);
  1338.  
  1339.                                 // TODO: 標的進出資料多增加行進中、確實進入的欄位
  1340.                                 if($maxItemTotal == 1) {
  1341.                                     $sid = $sact->enteringInTarget($target_id, true);
  1342.                                 }
  1343.  
  1344.                             }
  1345.  
  1346.                             // 紀錄所有推薦進歷程
  1347.                             $recommand->insertRecommandHistory($saId, $output_target_ids);
  1348.                         }
  1349.  
  1350.                     }
  1351.  
  1352.  
  1353.                     // 噴出結果
  1354.                     $app->render(201,array(
  1355.                         'token'             => $token,
  1356.                         'user_id'           => $user_id,
  1357.                         'activity_id'       => $sact->getId(),
  1358.                         'current_target_id' => $currentTId,
  1359.                         'is_end'            => $isEnd,
  1360.                         'recommand_total'   => $result_recommand_total,
  1361.                         'recommand_target'  => $output_targets,
  1362.                         'error'             => false
  1363.                     ));
  1364.  
  1365.                 }
  1366.                 else {
  1367.                     $app->render(400,array(
  1368.                         'token'   => $token,
  1369.                         'error'   => true,
  1370.                         'msg'     => 'No input \'current_point\' param.',
  1371.                         'msg_cht' => '缺少 \'current_point\' 參數'
  1372.                     ));
  1373.                 }
  1374.  
  1375.             }
  1376.             // 若非本人所有,則視同無此活動
  1377.             else {
  1378.                 throw new Exception\StudyActivityNoFoundException($saId);
  1379.             }
  1380.  
  1381.         }
  1382.         catch (Exception\LoginTokenNoFoundException $e) {
  1383.             $app->render(401,array(
  1384.                 'token'   => $token,
  1385.                 'error'   => true,
  1386.                 'msg'     => 'No \''.$token.'\' session. Please login again.',
  1387.                 'msg_cht' => '沒有\''.$token.'\'登入階段,請重新登入',
  1388.                 'substatus'   => 204
  1389.             ));
  1390.         }
  1391.         catch (Exception\StudyActivityNoFoundException $e) {
  1392.             $app->render(404,array(
  1393.                 'token'   => $token,
  1394.                 'error'   => true,
  1395.                 'msg'     => 'No found this activity.',
  1396.                 'msg_cht' => '沒有此學習活動'
  1397.             ));
  1398.         }
  1399.     });
  1400. });
  1401.  
  1402. // ============================================================================
  1403.  
  1404. /*
  1405.  * 輸入所有紀錄
  1406.  * GET http://localhost/api/v2/logs
  1407.  */
  1408. $app->post('/logs', 'APIrequest', function () use ($app) {
  1409.     $app = \Slim\Slim::getInstance();
  1410.  
  1411.     // 取得帶來的參數
  1412.     $cType = $app->request->getContentType();
  1413.  
  1414.     if($cType == 'application/json') {
  1415.         $postData = $app->request->getBody();
  1416.         $postDataJson = json_decode($postData);
  1417.  
  1418.         $logs_json = $postDataJson->logs_data;
  1419.     }
  1420.  
  1421.     $log_utils = new Log\Log();
  1422.  
  1423.     for($i=0; $i<count($logs_json); $i++) {
  1424.         $lid = $logs_json[$i]->LID;
  1425.         $uid = $logs_json[$i]->UID;
  1426.         $date = $logs_json[$i]->Date;
  1427.         if(isset($logs_json[$i]->SaID)) {
  1428.             $said = $logs_json[$i]->SaID;
  1429.         } else {
  1430.             $said = null;
  1431.         }
  1432.         $actiongroup = $logs_json[$i]->ActionGroup;
  1433.         $encode = $logs_json[$i]->Encode;
  1434.         if(isset($logs_json[$i]->TID)) {
  1435.             $tid = $logs_json[$i]->TID;
  1436.         } else {
  1437.             $tid = null;
  1438.         }
  1439.         if(isset($logs_json[$i]->QID)) {
  1440.             $qid = $logs_json[$i]->QID;
  1441.         } else {
  1442.             $qid = null;
  1443.         }
  1444.         if(isset($logs_json[$i]->Answer)) {
  1445.             $answer = $logs_json[$i]->Answer;
  1446.         } else {
  1447.             $answer = null;
  1448.         }
  1449.         if(isset($logs_json[$i]->Other)) {
  1450.             $other = $logs_json[$i]->Other;
  1451.         } else {
  1452.             $other = null;
  1453.         }
  1454.  
  1455.         // 新增此筆記錄到資料庫裡
  1456.         $log_utils->insert( array(  'LID' => $lid,
  1457.                                     'UID' => $uid,
  1458.                                     'Date' => $date,
  1459.                                     'SaID' => $said,
  1460.                                     'TID' => $tid,
  1461.                                     'ActionGroup' => $actiongroup,
  1462.                                     'Encode' => $encode,
  1463.                                     'QID' => $qid,
  1464.                                     'Answer' => $answer,
  1465.                                     'Other' => $other)
  1466.  
  1467.         );
  1468.     }
  1469.  
  1470.     $app->render(201,array(
  1471.         'error'      => false
  1472.     ));
  1473. });
  1474.  
  1475. // ============================================================================
  1476.  
  1477. /*
  1478.  * 取得館場資訊
  1479.  * GET http://localhost/api/v2/info
  1480.  */
  1481. $app->get('/info', 'APIrequest', function () use ($app) {
  1482.  
  1483.     $db = new Database\DBInfo();
  1484.     $placeInfoResult = $db->queryAllPlaceInfo();
  1485.     $placeMapResult = $db->queryALLPlaceMap();
  1486.  
  1487.     // 噴出結果
  1488.     $app->render(200,array(
  1489.         'place_info' => $placeInfoResult,
  1490.         'place_map'  => $placeMapResult,
  1491.         'error'      => false
  1492.     ));
  1493. });
  1494.  
  1495. // ============================================================================
  1496.  
  1497. // 取得Client要求的格式
  1498. $requestType = $app->request->headers->get('Accept');
  1499. // 若要求網頁版
  1500. if(strpos($requestType, 'text/html') !== false) {
  1501.  
  1502.     // API首頁
  1503.     $app->get('/', function () use ($app) {
  1504.         include('html/index.html');
  1505.     });
  1506.  
  1507.     // 沒有此功能
  1508.     $app->notFound(function () use ($app) {
  1509.         include('html/404.html');
  1510.     });
  1511. }
  1512. // 要求其他格式時,將以JSON為主
  1513. else {
  1514.  
  1515.     // API首頁
  1516.     $app->get('/', 'APIrequest', function () use ($app) {
  1517.  
  1518.         //取得現在時間,用字串的形式
  1519.         $nowDate = date("Y-m-d H:i:s");
  1520.  
  1521.         $app->render(200, array(
  1522.             'title'   => '',
  1523.             'version' => '2.0',
  1524.             'current_time' => $nowDate,
  1525.             'error'   => false,
  1526.         ));
  1527.     });
  1528.  
  1529.     // 沒有此功能
  1530.     $app->notFound(function () use ($app) {
  1531.         $app->view(new \JsonApiView());
  1532.         $app->add(new \JsonApiMiddleware());
  1533.  
  1534.         $app->render(404,array(
  1535.             'error'       => true,
  1536.             'msg'     => 'No this function.',
  1537.             'msg_cht' => '沒有此功能'
  1538.         ));
  1539.     });
  1540. }
  1541.  
  1542. // 內部出錯
  1543. $app->error(function (\Exception $e) use ($app) {
  1544.     //$app->render('error.php');
  1545. });
  1546.  
  1547.  
  1548. $app->run();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement