create_audio.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * This file allows creating audio files from a text.
  6. *
  7. * @package chamilo.document
  8. *
  9. * @author Juan Carlos Raña Trabado
  10. * @since 8/January/2011
  11. * TODO:clean all file
  12. */
  13. require_once __DIR__.'/../inc/global.inc.php';
  14. $this_section = SECTION_COURSES;
  15. $nameTools = get_lang('CreateAudio');
  16. api_protect_course_script();
  17. api_block_anonymous_users();
  18. $groupRights = Session::read('group_member_with_upload_rights');
  19. $groupId = api_get_group_id();
  20. if (api_get_setting('enabled_text2audio') === 'false') {
  21. api_not_allowed(true);
  22. }
  23. $document_data = DocumentManager::get_document_data_by_id(
  24. $_REQUEST['id'],
  25. api_get_course_id()
  26. );
  27. if (empty($document_data)) {
  28. if (api_is_in_group()) {
  29. $group_properties = GroupManager::get_group_properties(
  30. $groupId
  31. );
  32. $document_id = DocumentManager::get_document_id(
  33. api_get_course_info(),
  34. $group_properties['directory']
  35. );
  36. $document_data = DocumentManager::get_document_data_by_id(
  37. $document_id,
  38. api_get_course_id()
  39. );
  40. }
  41. }
  42. $document_id = $document_data['id'];
  43. $dir = $document_data['path'];
  44. //jquery textareaCounter
  45. $htmlHeadXtra[] = api_get_js('textareacounter/jquery.textareaCounter.plugin.js');
  46. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  47. // Please, do not modify this dirname formatting
  48. if (strstr($dir, '..')) {
  49. $dir = '/';
  50. }
  51. if ($dir[0] == '.') {
  52. $dir = substr($dir, 1);
  53. }
  54. if ($dir[0] != '/') {
  55. $dir = '/'.$dir;
  56. }
  57. if ($dir[strlen($dir) - 1] != '/') {
  58. $dir .= '/';
  59. }
  60. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  61. if (!is_dir($filepath)) {
  62. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  63. $dir = '/';
  64. }
  65. //groups //TODO: clean
  66. if (!empty($groupId)) {
  67. $interbreadcrumb[] = array(
  68. "url" => "../group/group_space.php?".api_get_cidreq(),
  69. "name" => get_lang('GroupSpace')
  70. );
  71. $group = GroupManager:: get_group_properties($groupId);
  72. $path = explode('/', $dir);
  73. if ('/'.$path[1] != $group['directory']) {
  74. api_not_allowed(true);
  75. }
  76. }
  77. $interbreadcrumb[] = array(
  78. "url" => "./document.php?curdirpath=".urlencode($dir)."&".api_get_cidreq(),
  79. "name" => get_lang('Documents')
  80. );
  81. if (!api_is_allowed_in_course()) {
  82. api_not_allowed(true);
  83. }
  84. if (!($is_allowed_to_edit || $groupRights ||
  85. DocumentManager::is_my_shared_folder(
  86. api_get_user_id(),
  87. Security::remove_XSS($dir),
  88. api_get_session_id()
  89. ))
  90. ) {
  91. api_not_allowed(true);
  92. }
  93. /* Header */
  94. Event::event_access_tool(TOOL_DOCUMENT);
  95. $display_dir = $dir;
  96. if (isset ($group)) {
  97. $display_dir = explode('/', $dir);
  98. unset($display_dir[0]);
  99. unset($display_dir[1]);
  100. $display_dir = implode('/', $display_dir);
  101. }
  102. // Copied from document.php
  103. $dir_array = explode('/', $dir);
  104. $array_len = count($dir_array);
  105. $dir_acum = '';
  106. for ($i = 0; $i < $array_len; $i++) {
  107. $url_dir = 'document.php?&curdirpath='.$dir_acum.$dir_array[$i];
  108. //Max char 80
  109. $url_to_who = cut($dir_array[$i], 80);
  110. $interbreadcrumb[] = array('url' => $url_dir, 'name' => $url_to_who);
  111. $dir_acum .= $dir_array[$i].'/';
  112. }
  113. $service = isset($_GET['service']) ? $_GET['service'] : 'pediaphon';
  114. Display:: display_header($nameTools, 'Doc');
  115. echo '<div class="actions">';
  116. echo '<a href="document.php?id='.$document_id.'">'.
  117. Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('DocumentsOverview'), '',
  118. ICON_SIZE_MEDIUM).'</a>';
  119. echo '<a href="create_audio.php?'.api_get_cidreq().'&id='.$document_id.'&service=pediaphon">'.
  120. Display::return_icon('pediaphon.png', get_lang('Pediaphon'), '', ICON_SIZE_MEDIUM).'</a>';
  121. echo '<a href="create_audio.php?'.api_get_cidreq().'&id='.$document_id.'&service=google">'.
  122. Display::return_icon('google.png', get_lang('GoogleAudio'), '', ICON_SIZE_MEDIUM).'</a>';
  123. echo '</div>';
  124. ?>
  125. <!-- javascript and styles for textareaCounter-->
  126. <script>
  127. var info;
  128. $(document).ready(function () {
  129. var options = {
  130. 'maxCharacterSize': 100,
  131. 'originalStyle': 'originalTextareaInfo',
  132. 'warningStyle': 'warningTextareaInfo',
  133. 'warningNumber': 20,
  134. 'displayFormat': '#input/#max'
  135. };
  136. $('#textarea_google').textareaCount(options, function (data) {
  137. $('#textareaCallBack').html(data);
  138. });
  139. });
  140. </script>
  141. <style>
  142. .overview {
  143. background: #FFEC9D;
  144. padding: 10px;
  145. width: 90%;
  146. border: 1px solid #CCCCCC;
  147. }
  148. .originalTextareaInfo {
  149. font-size: 12px;
  150. color: #000000;
  151. text-align: right;
  152. }
  153. .warningTextareaInfo {
  154. color: #FF0000;
  155. font-weight: bold;
  156. text-align: right;
  157. }
  158. #showData {
  159. height: 70px;
  160. width: 200px;
  161. border: 1px solid #CCCCCC;
  162. padding: 10px;
  163. margin: 10px;
  164. }
  165. </style>
  166. <div id="textareaCallBack"></div>
  167. <?php
  168. if (isset($_POST['text2voice_mode']) && $_POST['text2voice_mode'] == 'google') {
  169. downloadMP3_google($filepath, $dir);
  170. } elseif (isset($_POST['text2voice_mode']) && $_POST['text2voice_mode'] == 'pediaphon') {
  171. downloadMP3_pediaphon($filepath, $dir);
  172. }
  173. $tbl_admin_languages = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  174. $sql_select = "SELECT * FROM $tbl_admin_languages";
  175. $result_select = Database::query($sql_select);
  176. $options = $options_pedia = array();
  177. $selected_language = null;
  178. while ($row = Database::fetch_array($result_select)) {
  179. $options[$row['isocode']] = $row['original_name'].' ('.$row['english_name'].')';
  180. if (in_array($row['isocode'], array('de', 'en', 'es', 'fr'))) {
  181. $options_pedia[$row['isocode']] = $row['original_name'].' ('.$row['english_name'].')';
  182. }
  183. }
  184. if ($service == 'google') {
  185. $selected_language = api_get_language_isocode(); //lang default is the course language
  186. $form = new FormValidator('form1', 'post', api_get_self().'?'.api_get_cidreq(), '', array('id' => 'form1'));
  187. $form->addHeader(get_lang('HelpText2Audio'));
  188. $form->addElement('hidden', 'text2voice_mode', 'google');
  189. $form->addElement('hidden', 'id', $document_id);
  190. $form->addElement('text', 'title', get_lang('Title'));
  191. $form->addElement('select', 'lang', get_lang('Language'), $options);
  192. $form->addElement('textarea', 'text', get_lang('InsertText2Audio'), array('id' => 'textarea_google'));
  193. $form->addButtonSave(get_lang('SaveMP3'));
  194. $defaults = array();
  195. $defaults['lang'] = $selected_language;
  196. $form->setDefaults($defaults);
  197. $form->display();
  198. }
  199. if ($service == 'pediaphon') {
  200. //lang default is a default message
  201. $selected_language = "defaultmessage";
  202. $options_pedia['defaultmessage'] = get_lang('FirstSelectALanguage');
  203. $options['defaultmessage'] = get_lang('FirstSelectALanguage');
  204. $form = new FormValidator('form2', 'post', api_get_self().'?'.api_get_cidreq(), '', array('id' => 'form2'));
  205. $form->addHeader(get_lang('HelpText2Audio'));
  206. $form->addElement('hidden', 'text2voice_mode', 'pediaphon');
  207. $form->addElement('hidden', 'id', $document_id);
  208. $form->addElement('text', 'title', get_lang('Title'));
  209. $form->addSelect('lang', get_lang('Language'), $options_pedia, array('class' => 'lang'));
  210. $form->addSelect('voices', get_lang('Voice'), array(get_lang('FirstSelectALanguage')), array('id' => 'voices'));
  211. $speed_options = array();
  212. $speed_options['1'] = get_lang('Normal');
  213. $speed_options['0.75'] = get_lang('GoFaster');
  214. $speed_options['0.8'] = get_lang('Fast');
  215. $speed_options['1.2'] = get_lang('Slow');
  216. $speed_options['1.6'] = get_lang('SlowDown');
  217. $form->addElement('select', 'speed', get_lang('Speed'), $speed_options, array());
  218. $form->addElement('textarea', 'text', get_lang('InsertText2Audio'), array('id' => 'textarea_pediaphon'));
  219. //echo Display::return_icon('info3.gif', get_lang('HelpPediaphon'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
  220. $form->addButtonSave(get_lang('SaveMP3'));
  221. $defaults = array();
  222. $defaults['lang'] = $selected_language;
  223. $form->setDefaults($defaults);
  224. $form->display();
  225. ?>
  226. <!-- javascript form name form2 update voices -->
  227. <script>
  228. var langslist = document.form2.lang
  229. var voiceslist = document.form2.voices
  230. var voices = new Array()
  231. <!--German -->
  232. voices['de'] = ["<?php echo get_lang('Female').' (de1)'; ?>|de1", "<?php echo get_lang('Male').' (de2)'; ?>|de2", "<?php echo get_lang('Female').' (de3)'; ?>|de3", "<?php echo get_lang('Male').' (de4)'; ?>|de4", "<?php echo get_lang('Female').' (de5)'; ?>|de5", "<?php echo get_lang('Male').' (de6)'; ?>|de6", "<?php echo get_lang('Female').' (de7)'; ?>|de7", "<?php echo get_lang('Female').' (de8 HQ)'; ?>|de8"]
  233. <!--English -->
  234. voices['en'] = ["<?php echo get_lang('Male').' (en1)'; ?>|en1", "<?php echo get_lang('Male').' (en2 HQ)'; ?>|en2", "<?php echo get_lang('Female').' (us1)'; ?>|us1", "<?php echo get_lang('Male').' (us2)'; ?>|us2", "<?php echo get_lang('Male').' (us3)'; ?>|us3", "<?php echo get_lang('Female').'(us4 HQ)'; ?>|us4"]
  235. <!--Spanish -->
  236. voices['es'] = ["<?php echo get_lang('Male').' (es5 HQ)'; ?>|es5"]
  237. <!--French -->
  238. voices['fr'] = ["<?php echo get_lang('Female').' (fr8 HQ)'; ?>|fr8"]
  239. $(document).ready(function () {
  240. $('.lang').on('change', function () {
  241. var selectedvoicegroup = this.value;
  242. $('#voices').empty();
  243. for (i = 0; i < voices[selectedvoicegroup].length; i++) {
  244. var value = voices[selectedvoicegroup][i].split("|")[1];
  245. var text = voices[selectedvoicegroup][i].split("|")[0];
  246. var newOption = $('<option value="' + value + '">' + text + '</option>');
  247. $('#voices').append(newOption);
  248. $('#voices').selectpicker('refresh');
  249. }
  250. });
  251. });
  252. </script>
  253. <?php
  254. }//end pediaphon
  255. Display:: display_footer();
  256. /**
  257. * This function save a post into a file mp3 from google services
  258. *
  259. * @param $filepath
  260. * @param $dir
  261. * @author Juan Carlos Raña Trabado <herodoto@telefonica.net>
  262. * @version january 2011, chamilo 1.8.8
  263. */
  264. function downloadMP3_google($filepath, $dir)
  265. {
  266. $location = 'create_audio.php?'.api_get_cidreq().'&id='.intval($_POST['id']).'&service=google';
  267. //security
  268. if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
  269. echo '<script>window.location.href="'.$location.'"</script>';
  270. return;
  271. }
  272. $_course = api_get_course_info();
  273. $_user = api_get_user_info();
  274. $clean_title = trim($_POST['title']);
  275. $clean_text = trim($_POST['text']);
  276. if (empty($clean_title) || empty($clean_text)) {
  277. echo '<script>window.location.href="'.$location.'"</script>';
  278. return;
  279. }
  280. $clean_title = Security::remove_XSS($clean_title);
  281. $clean_title = Database::escape_string($clean_title);
  282. $clean_title = str_replace(' ', '_', $clean_title); //compound file names
  283. $clean_text = Security::remove_XSS($clean_text);
  284. $clean_lang = Security::remove_XSS($_POST['lang']);
  285. $extension = 'mp3';
  286. $audio_filename = $clean_title.'.'.$extension;
  287. $audio_title = str_replace('_', ' ', $clean_title);
  288. //prevent duplicates
  289. if (file_exists($filepath.'/'.$clean_title.'.'.$extension)) {
  290. $i = 1;
  291. while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) {
  292. $i++;
  293. }
  294. $audio_filename = $clean_title.'_'.$i.'.'.$extension;
  295. $audio_title = $clean_title.'_'.$i.'.'.$extension;
  296. $audio_title = str_replace('_', ' ', $audio_title);
  297. }
  298. $documentPath = $filepath.'/'.$audio_filename;
  299. $clean_text = api_replace_dangerous_char($clean_text);
  300. // adding the file
  301. // add new file to disk
  302. $proxySettings = api_get_configuration_value('proxy_settings');
  303. $key = api_get_configuration_value('translate_app_google_key');
  304. $url = "https://www.googleapis.com/language/translate/v2?key=$key&".$clean_lang."&target=$clean_lang&q=".urlencode($clean_text)."";
  305. if (empty($proxySettings)) {
  306. $content = file_get_contents($url);
  307. } else {
  308. if (!empty($proxySettings['stream_context_create'])) {
  309. $context = stream_context_create($proxySettings['stream_context_create']);
  310. } else {
  311. $context = stream_context_create();
  312. }
  313. $content = file_get_contents($url, false, $context);
  314. }
  315. file_put_contents(
  316. $documentPath,
  317. $content
  318. );
  319. // add document to database
  320. $current_session_id = api_get_session_id();
  321. $groupId = api_get_group_id();
  322. $groupInfo = GroupManager::get_group_properties($groupId);
  323. $relativeUrlPath = $dir;
  324. $doc_id = add_document(
  325. $_course,
  326. $relativeUrlPath.$audio_filename,
  327. 'file',
  328. filesize($documentPath),
  329. $audio_title
  330. );
  331. api_item_property_update(
  332. $_course,
  333. TOOL_DOCUMENT,
  334. $doc_id,
  335. 'DocumentAdded',
  336. $_user['user_id'],
  337. $groupInfo,
  338. null,
  339. null,
  340. null,
  341. $current_session_id
  342. );
  343. echo Display::return_message(get_lang('DocumentCreated'), 'confirm');
  344. //return to location
  345. echo '<script>window.location.href="'.$location.'"</script>';
  346. }
  347. /**
  348. * This function save a post into a file mp3 from pediaphon services
  349. *
  350. * @param $filepath
  351. * @param $dir
  352. * @author Juan Carlos Raña Trabado <herodoto@telefonica.net>
  353. * @version january 2011, chamilo 1.8.8
  354. */
  355. function downloadMP3_pediaphon($filepath, $dir)
  356. {
  357. $location = 'create_audio.php?'.api_get_cidreq().'&id='.intval($_POST['id']).'&service=pediaphon';
  358. //security
  359. if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
  360. echo '<script>window.location.href="'.$location.'"</script>';
  361. return;
  362. }
  363. $_course = api_get_course_info();
  364. $_user = api_get_user_info();
  365. $clean_title = trim($_POST['title']);
  366. $clean_title = Database::escape_string($clean_title);
  367. $clean_text = trim($_POST['text']);
  368. $clean_voices = Security::remove_XSS($_POST['voices']);
  369. if (empty($clean_title) || empty($clean_text) || empty($clean_voices)) {
  370. echo '<script>window.location.href="'.$location.'"</script>';
  371. return;
  372. }
  373. $clean_title = Security::remove_XSS($clean_title);
  374. $clean_title = Database::escape_string($clean_title);
  375. $clean_title = str_replace(' ', '_', $clean_title); //compound file names
  376. $clean_text = Security::remove_XSS($clean_text);
  377. $clean_lang = Security::remove_XSS($_POST['lang']);
  378. $clean_speed = Security::remove_XSS($_POST['speed']);
  379. $extension = 'mp3';
  380. $audio_filename = $clean_title.'.'.$extension;
  381. $audio_title = str_replace('_', ' ', $clean_title);
  382. //prevent duplicates
  383. if (file_exists($filepath.'/'.$clean_title.'.'.$extension)) {
  384. $i = 1;
  385. while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) {
  386. $i++;
  387. }
  388. $audio_filename = $clean_title.'_'.$i.'.'.$extension;
  389. $audio_title = $clean_title.'_'.$i.'.'.$extension;
  390. $audio_title = str_replace('_', ' ', $audio_title);
  391. }
  392. $documentPath = $filepath.'/'.$audio_filename;
  393. $clean_text = api_replace_dangerous_char($clean_text);
  394. //adding the file
  395. if ($clean_lang == 'de') {
  396. $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice.cgi';
  397. $find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/(.*)\.mp3\"/';
  398. } else {
  399. $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice_'.$clean_lang.'.cgi'; //en, es, fr
  400. $find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/'.$clean_lang.'\/(.*)\.mp3\"/';
  401. }
  402. $data = "stimme=".$clean_voices."&inputtext=".$clean_text."&speed=".$clean_speed."&go=speak";
  403. $opts = array(
  404. 'http' =>
  405. array(
  406. 'method' => 'POST',
  407. 'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
  408. "Content-Length: ".strlen($data)."\r\n",
  409. 'content' => $data
  410. )
  411. );
  412. $context = stream_context_create($opts);
  413. // Download the whole HTML page
  414. $previous_returntext2voice = file_get_contents($url_pediaphon, false, $context);
  415. //extract the audio file path
  416. $search_source = preg_match($find_t2v, $previous_returntext2voice, $hits);
  417. $souce_end = substr($hits[0], 0, -1);
  418. //download file
  419. $returntext2voice = file_get_contents($souce_end);
  420. //save file
  421. $f = @file_put_contents($documentPath, $returntext2voice);
  422. if ($f === false && !empty($php_errormsg)) {
  423. error_log($php_errormsg);
  424. }
  425. //add document to database
  426. $current_session_id = api_get_session_id();
  427. $groupId = api_get_group_id();
  428. $groupInfo = GroupManager::get_group_properties($groupId);
  429. $relativeUrlPath = $dir;
  430. $doc_id = add_document(
  431. $_course,
  432. $relativeUrlPath.$audio_filename,
  433. 'file',
  434. filesize($documentPath),
  435. $audio_title
  436. );
  437. api_item_property_update(
  438. $_course,
  439. TOOL_DOCUMENT,
  440. $doc_id,
  441. 'DocumentAdded',
  442. $_user['user_id'],
  443. $groupInfo,
  444. null,
  445. null,
  446. null,
  447. $current_session_id
  448. );
  449. echo Display::return_message(get_lang('DocumentCreated'), 'confirm');
  450. //return to location
  451. echo '<script>window.location.href="'.$location.'"</script>';
  452. }