record_audio.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\PluginBundle\Entity\WhispeakAuth\LogEvent;
  4. use Chamilo\UserBundle\Entity\User;
  5. use FFMpeg\FFMpeg;
  6. use FFMpeg\Format\Audio\Wav;
  7. $cidReset = true;
  8. require_once __DIR__.'/../../../main/inc/global.inc.php';
  9. $action = isset($_POST['action']) ? $_POST['action'] : 'enrollment';
  10. $isEnrollment = 'enrollment' === $action;
  11. $isAuthentify = 'authentify' === $action;
  12. $isAllowed = false;
  13. if ($isEnrollment) {
  14. api_block_anonymous_users(false);
  15. $isAllowed = !empty($_FILES['audio']);
  16. } elseif ($isAuthentify) {
  17. $userId = api_get_user_id();
  18. $user2fa = ChamiloSession::read(WhispeakAuthPlugin::SESSION_2FA_USER, 0);
  19. if (!empty($user2fa) || !empty($userId)) {
  20. $isAllowed = !empty($_FILES['audio']);
  21. } else {
  22. $isAllowed = !empty($_POST['username']) && !empty($_FILES['audio']);
  23. }
  24. }
  25. if (!$isAllowed) {
  26. WhispeakAuthPlugin::displayNotAllowedMessage();
  27. }
  28. $plugin = WhispeakAuthPlugin::create();
  29. $plugin->protectTool(false);
  30. $failedLogins = 0;
  31. $maxAttempts = 0;
  32. if ($isAuthentify) {
  33. $failedLogins = ChamiloSession::read(WhispeakAuthPlugin::SESSION_FAILED_LOGINS, 0);
  34. $maxAttempts = $plugin->getMaxAttempts();
  35. $em = Database::getManager();
  36. if (!empty($user2fa)) {
  37. $user = api_get_user_entity($user2fa);
  38. } elseif (!empty($userId)) {
  39. $user = api_get_user_entity($userId);
  40. } else {
  41. /** @var User|null $user */
  42. $user = UserManager::getRepository()->findOneBy(['username' => $_POST['username']]);
  43. }
  44. } else {
  45. /** @var User $user */
  46. $user = api_get_user_entity(api_get_user_id());
  47. }
  48. if (empty($user)) {
  49. echo Display::return_message(get_lang('NoUser'), 'error');
  50. exit;
  51. }
  52. $path = api_upload_file('whispeakauth', $_FILES['audio'], $user->getId());
  53. if (false === $path) {
  54. echo Display::return_message(get_lang('UploadError'), 'error');
  55. exit;
  56. }
  57. $newFullPath = $originFullPath = api_get_path(SYS_UPLOAD_PATH).'whispeakauth'.$path['path_to_save'];
  58. $fileType = mime_content_type($originFullPath);
  59. if ('wav' !== substr($fileType, -3)) {
  60. $directory = dirname($originFullPath);
  61. $newFullPath = $directory.'/audio.wav';
  62. try {
  63. $ffmpeg = FFMpeg::create();
  64. $audio = $ffmpeg->open($originFullPath);
  65. $audio->save(new Wav(), $newFullPath);
  66. } catch (Exception $exception) {
  67. echo Display::return_message($exception->getMessage(), 'error');
  68. exit;
  69. }
  70. }
  71. if ($isEnrollment) {
  72. $license = !empty($_POST['license']) ? true : false;
  73. try {
  74. $wsid = WhispeakAuthRequest::whispeakId($plugin);
  75. $wsid = WhispeakAuthRequest::license($plugin, $wsid, $license);
  76. $text = ChamiloSession::read(WhispeakAuthPlugin::SESSION_SENTENCE_TEXT);
  77. $enrollmentResult = WhispeakAuthRequest::enrollment($plugin, $user, $wsid, $text, $newFullPath);
  78. } catch (Exception $exception) {
  79. echo Display::return_message($plugin->get_lang('EnrollmentFailed'));
  80. exit;
  81. }
  82. $reliability = (int) $enrollmentResult['reliability'];
  83. $qualityNote = !empty($enrollmentResult['quality']) ? explode('|', $enrollmentResult['quality']) : [];
  84. $qualityNote = array_map('ucfirst', $qualityNote);
  85. $message = $plugin->get_lang('EnrollmentSignature0');
  86. if ($reliability > 0) {
  87. ChamiloSession::erase(WhispeakAuthPlugin::SESSION_SENTENCE_TEXT);
  88. $plugin->saveEnrollment($user, $enrollmentResult['wsid']);
  89. $message = '<strong>'.$plugin->get_lang('EnrollmentSuccess').'</strong>';
  90. $message .= PHP_EOL;
  91. $message .= $plugin->get_lang("EnrollmentSignature$reliability");
  92. }
  93. foreach ($qualityNote as $note) {
  94. $message .= PHP_EOL.'<br>'.$plugin->get_lang("AudioQuality$note");
  95. }
  96. echo Display::return_message(
  97. $message,
  98. $reliability <= 0 ? 'error' : 'success',
  99. false
  100. );
  101. }
  102. if ($isAuthentify) {
  103. if ($maxAttempts && $failedLogins >= $maxAttempts) {
  104. echo Display::return_message($plugin->get_lang('MaxAttemptsReached'), 'warning');
  105. exit;
  106. }
  107. $wsid = WhispeakAuthPlugin::getAuthUidValue($user->getId());
  108. if (empty($wsid)) {
  109. echo Display::return_message($plugin->get_lang('SpeechAuthNotEnrolled'), 'warning');
  110. exit;
  111. }
  112. try {
  113. $text = ChamiloSession::read(WhispeakAuthPlugin::SESSION_SENTENCE_TEXT);
  114. $authentifyResult = WhispeakAuthRequest::authentify($plugin, $wsid->getValue(), $text, $newFullPath);
  115. } catch (Exception $exception) {
  116. echo Display::return_message($plugin->get_lang('TryAgain'), 'error');
  117. exit;
  118. }
  119. $success = (bool) $authentifyResult['result'];
  120. $qualityNote = !empty($authentifyResult['quality']) ? explode('|', $authentifyResult['quality']) : [];
  121. $qualityNote = array_map('ucfirst', $qualityNote);
  122. /** @var array $lpItemInfo */
  123. $lpItemInfo = ChamiloSession::read(WhispeakAuthPlugin::SESSION_LP_ITEM, []);
  124. /** @var array $quizQuestionInfo */
  125. $quizQuestionInfo = ChamiloSession::read(WhispeakAuthPlugin::SESSION_QUIZ_QUESTION, []);
  126. $message = $plugin->get_lang('AuthentifySuccess');
  127. if (!$success) {
  128. if (!empty($lpItemInfo)) {
  129. $plugin->addAttemptInLearningPath(
  130. LogEvent::STATUS_FAILED,
  131. $user->getId(),
  132. $lpItemInfo['lp_item'],
  133. $lpItemInfo['lp']
  134. );
  135. }
  136. if (!empty($quizQuestionInfo)) {
  137. $plugin->addAttemptInQuiz(
  138. LogEvent::STATUS_FAILED,
  139. $user->getId(),
  140. $quizQuestionInfo['question'],
  141. $quizQuestionInfo['quiz']
  142. );
  143. }
  144. $message = $plugin->get_lang('AuthentifyFailed');
  145. ChamiloSession::write(WhispeakAuthPlugin::SESSION_FAILED_LOGINS, ++$failedLogins);
  146. if ($maxAttempts && $failedLogins >= $maxAttempts) {
  147. $message .= PHP_EOL
  148. .'<span data-reach-attempts="true">'.$plugin->get_lang('MaxAttemptsReached').'</span>'
  149. .PHP_EOL
  150. .'<br><strong>'
  151. .$plugin->get_lang('LoginWithUsernameAndPassword')
  152. .'</strong>';
  153. if (!empty($user2fa)) {
  154. Display::addFlash(
  155. Display::return_message($message, 'warning', false)
  156. );
  157. }
  158. } else {
  159. $message .= PHP_EOL.$plugin->get_lang('TryAgain');
  160. if ('true' === api_get_setting('allow_lostpassword')) {
  161. $message .= '<br>'
  162. .Display::url(
  163. get_lang('LostPassword'),
  164. api_get_path(WEB_CODE_PATH).'auth/lostPassword.php',
  165. ['target' => $lpItemInfo ? '_top' : '_self']
  166. );
  167. }
  168. }
  169. }
  170. foreach ($qualityNote as $note) {
  171. $message .= '<br>'.PHP_EOL.$plugin->get_lang("AudioQuality$note");
  172. }
  173. echo Display::return_message(
  174. $message,
  175. $success ? 'success' : 'warning',
  176. false
  177. );
  178. if (!$success && $maxAttempts && $failedLogins >= $maxAttempts) {
  179. ChamiloSession::erase(WhispeakAuthPlugin::SESSION_FAILED_LOGINS);
  180. if (!empty($lpItemInfo)) {
  181. echo '<script>window.location.href = "'
  182. .api_get_path(WEB_PLUGIN_PATH)
  183. .'whispeakauth/authentify_password.php";</script>';
  184. exit;
  185. }
  186. if (!empty($quizQuestionInfo)) {
  187. $url = api_get_path(WEB_CODE_PATH).'exercise/exercise_submit.php?'.$quizQuestionInfo['url_params'];
  188. ChamiloSession::write(WhispeakAuthPlugin::SESSION_AUTH_PASSWORD, true);
  189. echo "<script>window.location.href = '".$url."';</script>";
  190. exit;
  191. }
  192. echo '<script>window.location.href = "'.api_get_path(WEB_PATH).'";</script>';
  193. exit;
  194. }
  195. if ($success) {
  196. ChamiloSession::erase(WhispeakAuthPlugin::SESSION_SENTENCE_TEXT);
  197. ChamiloSession::erase(WhispeakAuthPlugin::SESSION_FAILED_LOGINS);
  198. if (!empty($lpItemInfo)) {
  199. ChamiloSession::erase(WhispeakAuthPlugin::SESSION_LP_ITEM);
  200. ChamiloSession::erase(WhispeakAuthPlugin::SESSION_2FA_USER);
  201. $plugin->addAttemptInLearningPath(
  202. LogEvent::STATUS_SUCCESS,
  203. $user->getId(),
  204. $lpItemInfo['lp_item'],
  205. $lpItemInfo['lp']
  206. );
  207. echo '<script>window.location.href = "'.$lpItemInfo['src'].'";</script>';
  208. exit;
  209. }
  210. if (!empty($quizQuestionInfo)) {
  211. $quizQuestionInfo['passed'] = true;
  212. $url = api_get_path(WEB_CODE_PATH).'exercise/exercise_submit.php?'.$quizQuestionInfo['url_params'];
  213. ChamiloSession::write(WhispeakAuthPlugin::SESSION_QUIZ_QUESTION, $quizQuestionInfo);
  214. $plugin->addAttemptInQuiz(
  215. LogEvent::STATUS_SUCCESS,
  216. $user->getId(),
  217. $quizQuestionInfo['question'],
  218. $quizQuestionInfo['quiz']
  219. );
  220. echo '<script>window.location.href = "'.$url.'";</script>';
  221. exit;
  222. }
  223. $loggedUser = [
  224. 'user_id' => $user->getId(),
  225. 'status' => $user->getStatus(),
  226. 'uidReset' => true,
  227. ];
  228. if (empty($user2fa)) {
  229. ChamiloSession::write(WhispeakAuthPlugin::SESSION_2FA_USER, $user->getId());
  230. }
  231. ChamiloSession::erase(WhispeakAuthPlugin::SESSION_FAILED_LOGINS);
  232. ChamiloSession::write('_user', $loggedUser);
  233. Login::init_user($user->getId(), true);
  234. echo '<script>window.location.href = "'.api_get_path(WEB_PATH).'";</script>';
  235. }
  236. }