create_audio.php 18 KB

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