Преглед на файлове

Merge pull request #411 from danbarretodev/BT8274

Complete WebODF feature - refs BT#8274
Yannick Warnier преди 10 години
родител
ревизия
5e42b3d932

+ 21 - 0
main/document/document.inc.php

@@ -486,6 +486,9 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
     $is_certificate_mode = DocumentManager::is_certificate_mode($path);
     $curdirpath = urlencode($curdirpath);
     $extension = pathinfo($path, PATHINFO_EXTENSION);
+    $usePpt2lp = api_get_setting('service_ppt2lp', 'active') == 'true';
+    $formatTypeList = DocumentManager::getFormatTypeListConvertor('from', $extension);
+    $formatType = current($formatTypeList);
 
     // Build URL-parameters for table-sorting
     $sort_params = array();
@@ -619,6 +622,24 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
                 }
             }
         }
+
+        // Add action to covert to PDF, will create a new document whit same filename but .pdf extension
+        // @TODO: add prompt to select a format target
+        if (in_array($path, DocumentManager::get_system_folders())) {
+            // nothing to do
+        } else {
+            if ($usePpt2lp && $formatType) {
+                $modify_icons .= '&nbsp;<a class="convertAction" href="#" ' .
+                    'data-documentId = ' . $document_id .
+                    ' data-formatType = ' . $formatType . '>' .
+                    Display::return_icon(
+                        'convert.png',
+                        get_lang('Convert'),
+                        array(),
+                        ICON_SIZE_SMALL
+                    ) . '</a>';
+            }
+        }
     }
 
     if ($type == 'file' && ($extension == 'html' || $extension == 'htm')) {

+ 166 - 7
main/document/document.php

@@ -49,11 +49,21 @@ api_protect_course_script(true);
 
 DocumentManager::removeGeneratedAudioTempFile();
 
-if (isset($_SESSION['temp_realpath_image'])
-    && !empty($_SESSION['temp_realpath_image'])
-    && is_file($_SESSION['temp_realpath_image'])) {
+if(
+    isset($_SESSION['temp_realpath_image']) &&
+    !empty($_SESSION['temp_realpath_image']) &&
+    file_exists($_SESSION['temp_realpath_image'])
+) {
     unlink($_SESSION['temp_realpath_image']);
 }
+$courseInfo = api_get_course_info();
+$course_dir = $courseInfo['directory'] . '/document';
+$sys_course_path = api_get_path(SYS_COURSE_PATH);
+$base_work_dir = $sys_course_path . $course_dir;
+$http_www = api_get_path(WEB_COURSE_PATH) .
+    $courseInfo['directory'] . '/document';
+$document_path = $base_work_dir;
+$usePpt2lp = api_get_setting('service_ppt2lp', 'active') == 'true';
 
 $courseInfo = api_get_course_info();
 $course_dir = $courseInfo['directory'].'/document';
@@ -404,6 +414,94 @@ switch ($action) {
             Session::write('message', $message);
         }
         break;
+    case 'convertToPdf':
+        // PDF format as target by default
+        $formatTarget = $_REQUEST['formatTarget'] ?
+            strtolower(Security::remove_XSS($_REQUEST['formatTarget'])) :
+            'pdf';
+        $formatType = $_REQUEST['formatType'] ?
+            strtolower(Security::remove_XSS($_REQUEST['formatType'])) :
+            'text';
+        // Get the document data from the ID
+        $document_info = DocumentManager::get_document_data_by_id(
+            $document_id,
+            api_get_course_id(),
+            true,
+            $session_id
+        );
+        $file = $sys_course_path . $courseInfo['directory'] .
+            '/document' . $document_info['path'];
+        $fileInfo = pathinfo($file);
+        if ($fileInfo['extension'] == $formatTarget) {
+            $message = Display::return_message(
+                get_lang('ErrorSameFormat'),
+                'warning'
+            );
+        } elseif (
+            !(
+                in_array(
+                    $fileInfo['extension'],
+                    DocumentManager::getJodconverterExtensionList(
+                        'from',
+                        $formatType
+                    )
+                )
+            ) || !(
+                in_array(
+                    $formatTarget,
+                    DocumentManager::getJodconverterExtensionList(
+                        'to',
+                        $formatType
+                    )
+                )
+            )
+        ) {
+            $message = Display::return_message(
+                get_lang('FormatNotSupported'),
+                'warning'
+            );
+        } else {
+            $convertedFile = $fileInfo['dirname'] . DIRECTORY_SEPARATOR .
+                $fileInfo['filename'] . '_from_' . $fileInfo['extension'] .
+                '.' . $formatTarget;
+            $convertedTitle = $document_info['title'];
+            $obj = new OpenofficePresentation(true);
+            if (file_exists($convertedFile)) {
+                $message = Display::return_message(
+                    get_lang('FileExists'),
+                    'error'
+                );
+            } else {
+                $result = $obj->convertCopyDocument(
+                    $file,
+                    $convertedFile,
+                    $convertedTitle
+                );
+                if (empty($result)) {
+                    $message = Display::return_message(
+                        get_lang('CopyFailed'),
+                        'error'
+                    );
+                } else {
+                    $cidReq = Security::remove_XSS($_GET['cidReq']);
+                    $id_session = api_get_session_id();
+                    $gidReq = Security::remove_XSS($_GET['gidReq']);
+                    $file_link = Display::url(
+                        get_lang('SeeFile'),
+                        api_get_path(WEB_CODE_PATH) .
+                        'document/showinframes.php?' . 'cidReq=' . $cidReq .
+                        '&id_session=' . $id_session . '&' .
+                        'gidReq=' . $gidReq . '&id=' . current($result)
+                    );
+                    $message = Display::return_message(
+                        get_lang('CopyMade') . ' ' . $file_link,
+                        'confirmation',
+                        false
+                    );
+                }
+            }
+        }
+        break;
 }
 
 // I'm in the certification module?
@@ -588,15 +686,39 @@ if ($tool_visibility == '0' && $groupId == '0' && !($is_allowed_to_edit || $grou
     api_not_allowed(true);
 }
 
-$htmlHeadXtra[] = "<script>
+$htmlHeadXtra[] = '<script>
 function confirmation (name) {
-    if (confirm(\" ".get_lang("AreYouSureToDelete")." \"+ name + \" ?\")) {
+    if (confirm(" '.get_lang('AreYouSureToDelete').' "+ name + " ?")) {
         return true;
     } else {
         return false;
     }
 }
-</script>";
+
+$(document).ready(function() {
+    $(".convertAction").click(function() {
+        var id = $(this).attr("data-documentId");
+        var format = $(this).attr("data-formatType");
+        convertModal(id, format);
+    });
+});
+function convertModal (id, format) {
+    $("#convertModal").modal("show");
+    $("." + format + "FormatType").show();
+    $("#convertSelect").change(function() {
+        var formatTarget = $(this).val();
+        window.location.href = "'.
+            api_get_self() . '?' . api_get_cidreq() .
+            '&curdirpath=' . $curdirpath .
+            '&action=convertToPdf&formatTarget=' .
+            '" + formatTarget + "&id=" + id + "' .
+            $req_gid . '&formatType=" + format;
+    });
+    $("#convertModal").on("hidden", function(){
+        $("." + format + "FormatType").hide();
+    });
+}
+</script>';
 
 // If they are looking at group documents they can't see the root
 if ($groupId != 0 && $curdirpath == '/') {
@@ -1759,7 +1881,6 @@ if (count($documentAndFolders) > 1) {
         $form_action['set_invisible'] = get_lang('SetInvisible');
         $form_action['set_visible'] = get_lang('SetVisible');
         $form_action['delete'] = get_lang('Delete');
-
         $portfolio_actions = Portfolio::actions();
         foreach ($portfolio_actions as $action) {
             $form_action[$action->get_name()] = $action->get_title();
@@ -1811,5 +1932,43 @@ if (!empty($table_footer)) {
     Display::display_warning_message($table_footer);
 }
 
+echo '
+    <div id="convertModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
+      <div class="modal-dialog">
+        <div class="modal-content">
+          <div class="modal-header" style="text-align: center;">
+            <button type="button" class="close" data-dismiss="modal">
+              <span aria-hidden="true">&times;</span>
+              <span class="sr-only">' . get_lang('Close') . '</span>
+            </button>
+            <h4 class="modal-title">' . get_lang('PleaseSelectConvertFormat') . '</h4>
+          </div>
+          <div class="modal-body" style="text-align: center;">
+            <p>' . get_lang('ConvertFormats') . '&hellip;</p>
+            <select id="convertSelect" class="input-lg text-center">
+                <option value="">
+                    ' . get_lang('SelectConvertFormat') . '
+                </option>
+                <option value="pdf">
+                    PDF - Portable Document File
+                </option>
+                <option value="odt" style="display:none;" class="textFormatType">
+                    ODT - Open Document Text
+                </option>
+                <option value="odp" style="display:none;" class="presentationFormatType">
+                    ODP - Open Document Portable
+                </option>
+                <option value="ods" style="display:none;" class="spreadsheetFormatType">
+                    ODS - Open Document Spreadsheet
+                </option>
+            </select>
+          </div>
+          <div class="modal-footer">
+            <button type="button" class="btn btn-default" data-dismiss="modal">' . get_lang('Close') . '</button>
+          </div>
+        </div>
+      </div>
+    </div>';
+
 // Footer
 Display::display_footer();

+ 11 - 7
main/document/showinframes.php

@@ -189,6 +189,8 @@ if (api_get_setting('show_glossary_in_documents') == 'ismanual') {
 
 
 $web_odf_supported_files = DocumentManager::get_web_odf_extension_list();
+// PDF should be displayed with viewerJS
+$web_odf_supported_files[] = 'pdf';
 if (in_array(strtolower($pathinfo['extension']), $web_odf_supported_files)) {
     $show_web_odf  = true;
     /*
@@ -208,13 +210,16 @@ if (in_array(strtolower($pathinfo['extension']), $web_odf_supported_files)) {
     */
     $htmlHeadXtra[] = '
     <script charset="utf-8">
-        resizeIframe = function(obj) {
+        resizeIframe = function() {
                 var bodyHeight = $("body").height();
                 var topbarHeight = $("#topbar").height();
-                obj.style.height = (bodyHeight - topbarHeight) + "px";
-
+                $("#viewerJSContent").height((bodyHeight - topbarHeight));
             }
-    </script>';
+        $(document).ready(function() {
+            $(window).resize(resizeIframe());
+        });
+    </script>'
+    ;
 }
 
 $execute_iframe = true;
@@ -307,9 +312,8 @@ if (!$is_nanogong_available) {
 
 if ($show_web_odf) {
     //echo Display::url(get_lang('Show'), api_get_path(WEB_CODE_PATH).'document/edit_odf.php?id='.$document_data['id'], array('class' => 'btn'));
-
-    echo '<div id="viewerJSContent">';
-    echo '<iframe frameborder="0" allowfullscreen="allowfullscreen" onload="resizeIframe(this)" style="width:100%;"
+    echo '<div id="viewerJS">';
+    echo '<iframe id="viewerJSContent" frameborder="0" allowfullscreen="allowfullscreen" style="width:100%;"
         src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file_url.'">
         </iframe>';
     echo '</div>';

BIN
main/img/icons/128/convert.png


BIN
main/img/icons/16/convert.png


BIN
main/img/icons/22/convert.png


BIN
main/img/icons/32/convert.png


BIN
main/img/icons/48/convert.png


BIN
main/img/icons/64/convert.png


+ 157 - 1
main/inc/lib/document.lib.php

@@ -3900,6 +3900,155 @@ class DocumentManager
         return array('ods', 'odt', 'odp');
     }
 
+    /**
+     * Set of extension allowed to use Jodconverter
+     * @param $mode 'from'
+     *              'to'
+     *              'all'
+     * @param $format   'text'
+     *                  'spreadsheet'
+     *                  'presentation'
+     *                  'drawing'
+     *                  'all'
+     * @return array
+     */
+    public static function getJodconverterExtensionList($mode, $format)
+    {
+        $extensionList = array();
+        $extensionListFromText = array(
+            'odt',
+            'sxw',
+            'rtf',
+            'doc',
+            'docx',
+            'wpd',
+            'txt',
+        );
+        $extensionListToText = array(
+            'pdf',
+            'odt',
+            'sxw',
+            'rtf',
+            'doc',
+            'docx',
+            'txt',
+        );
+        $extensionListFromSpreadsheet = array(
+            'ods',
+            'sxc',
+            'xls',
+            'xlsx',
+            'csv',
+            'tsv',
+        );
+        $extensionListToSpreadsheet = array(
+            'pdf',
+            'ods',
+            'sxc',
+            'xls',
+            'xlsx',
+            'csv',
+            'tsv',
+        );
+        $extensionListFromPresentation = array(
+            'odp',
+            'sxi',
+            'ppt',
+            'pptx',
+        );
+        $extensionListToPresentation = array(
+            'pdf',
+            'swf',
+            'odp',
+            'sxi',
+            'ppt',
+            'pptx',
+        );
+        $extensionListFromDrawing = array('odg');
+        $extensionListToDrawing = array('svg', 'swf');
+
+        if ($mode === 'from') {
+            if ($format === 'text') {
+                $extensionList = array_merge($extensionList, $extensionListFromText);
+            } elseif ($format === 'spreadsheet') {
+                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
+            } elseif ($format === 'presentation') {
+                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
+            } elseif ($format === 'drawing') {
+                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
+            } elseif ($format === 'all') {
+                $extensionList = array_merge($extensionList, $extensionListFromText);
+                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
+                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
+                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
+            }
+        } elseif ($mode === 'to') {
+            if ($format === 'text') {
+                $extensionList = array_merge($extensionList, $extensionListToText);
+            } elseif ($format === 'spreadsheet') {
+                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
+            } elseif ($format === 'presentation') {
+                $extensionList = array_merge($extensionList, $extensionListToPresentation);
+            } elseif ($format === 'drawing') {
+                $extensionList = array_merge($extensionList, $extensionListToDrawing);
+            } elseif ($format === 'all') {
+                $extensionList = array_merge($extensionList, $extensionListToText);
+                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
+                $extensionList = array_merge($extensionList, $extensionListToPresentation);
+                $extensionList = array_merge($extensionList, $extensionListToDrawing);
+            }
+        } elseif ($mode === 'all') {
+            if ($format === 'text') {
+                $extensionList = array_merge($extensionList, $extensionListFromText);
+                $extensionList = array_merge($extensionList, $extensionListToText);
+            } elseif ($format === 'spreadsheet') {
+                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
+                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
+            } elseif ($format === 'presentation') {
+                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
+                $extensionList = array_merge($extensionList, $extensionListToPresentation);
+            } elseif ($format === 'drawing') {
+                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
+                $extensionList = array_merge($extensionList, $extensionListToDrawing);
+            } elseif ($format === 'all') {
+                $extensionList = array_merge($extensionList, $extensionListFromText);
+                $extensionList = array_merge($extensionList, $extensionListToText);
+                $extensionList = array_merge($extensionList, $extensionListFromSpreadsheet);
+                $extensionList = array_merge($extensionList, $extensionListToSpreadsheet);
+                $extensionList = array_merge($extensionList, $extensionListFromPresentation);
+                $extensionList = array_merge($extensionList, $extensionListToPresentation);
+                $extensionList = array_merge($extensionList, $extensionListFromDrawing);
+                $extensionList = array_merge($extensionList, $extensionListToDrawing);
+            }
+        }
+        return $extensionList;
+    }
+
+    /**
+     * Get Format type list by extension and mode
+     * @param string $mode Mode to search format type list
+     * @example 'from'
+     * @example 'to'
+     * @param string $extension file extension to check file type
+     * @return array
+     */
+    public static function getFormatTypeListConvertor($mode = 'from', $extension)
+    {
+        $formatTypesList = array();
+        $formatTypes = array('text', 'spreadsheet', 'presentation', 'drawing');
+        foreach ($formatTypes as $formatType) {
+            if (
+                in_array(
+                    $extension,
+                    self::getJodconverterExtensionList($mode, $formatType)
+                )
+            ) {
+                $formatTypesList[] = $formatType;
+            }
+        }
+        return $formatTypesList;
+    }
+
     /**
      * @param string $path
      * @param bool $is_certificate_mode
@@ -3949,7 +4098,14 @@ class DocumentManager
         if (api_get_setting('show_chat_folder') == 'false') {
             $foldersToAvoid[] = '/chat_files';
         }
-        return in_array($path, $foldersToAvoid);
+
+        if (is_array($foldersToAvoid)) {
+
+            return in_array($path, $foldersToAvoid);
+        } else {
+
+            return false;
+        }
     }
 
     /**

+ 16 - 9
main/lang/english/document.inc.php

@@ -231,14 +231,14 @@ $FileExistsChangeToSave = "This file name already exists, choose another to save
 $FileSavedAs = "File saved as";
 $FileExportAs = "File export as";
 $UserFolder = "User folder";
-$HelpUsersFolder = "INFORMATION VISIBLE TO THE TEACHER ONLY:\nThe users folder contains a folder for each user who has accessed it through the documents tool, or when any file has been sent in the course through the online editor. If neither circumstances has occurred, then no user folder will have been created. In the case of groups, files that are sent through the editor will be added in the folder of each group, which is only accessible by students from this group.
-<br /><br />
-The users folder and each of the included folders will be hidden by default in for all students, but each student can see the contents of his/her directory through the online editor. However, if a student knows the address of a file or folder of another student, he may be able to access it.
-<br /><br />
-If the folder of a student is visible, other students can see what it contains. In this case, the student that owns the folder can also (from the documents tool and only in his/her folder): create and edit web documents, convert a document into a template for personal use, create and edit drawings in SVG and PNG formats, record audio files in WAV format, make audio files in MP3 from a text, make snapshops from a webcam, send documents, create folders, move folders and files, delete folders and files, and download backup of his/her folder.
-<br /><br />
-Moreover, the documents tool is synchronized with the file manager of the online editor, so changes in the documents triggered in any one of these will affect both.
-<br /><br />
+$HelpUsersFolder = "INFORMATION VISIBLE TO THE TEACHER ONLY:\nThe users folder contains a folder for each user who has accessed it through the documents tool, or when any file has been sent in the course through the online editor. If neither circumstances has occurred, then no user folder will have been created. In the case of groups, files that are sent through the editor will be added in the folder of each group, which is only accessible by students from this group.
+<br /><br />
+The users folder and each of the included folders will be hidden by default in for all students, but each student can see the contents of his/her directory through the online editor. However, if a student knows the address of a file or folder of another student, he may be able to access it.
+<br /><br />
+If the folder of a student is visible, other students can see what it contains. In this case, the student that owns the folder can also (from the documents tool and only in his/her folder): create and edit web documents, convert a document into a template for personal use, create and edit drawings in SVG and PNG formats, record audio files in WAV format, make audio files in MP3 from a text, make snapshops from a webcam, send documents, create folders, move folders and files, delete folders and files, and download backup of his/her folder.
+<br /><br />
+Moreover, the documents tool is synchronized with the file manager of the online editor, so changes in the documents triggered in any one of these will affect both.
+<br /><br />
 As such, the user folder is not only a place to deposit files, it becomes a complete manager of the documents students use during the course. Also, remember that any user can copy a file that is visible from any folder in the documents tool (whether or not he is the owner) to his/her portfolios or personal documents area of social network, which will be available to him/her for use in other courses.";
 $HelpFolderChat = "INFORMATION VISIBLE TO THE TEACHER ONLY:\nThis folder contains all sessions that have been opened in the chat. Although the chat sessions can often be trivial, others can be really interesting and worthy of being incorporated as an additional work document. To do this without changing the visibility of this folder, make the file visible and link it from where you deem appropriate. It is not recommended to make this folder visible to all.";
 $HelpFolderCertificates = "INFORMATION VISIBLE TO THE TEACHER ONLY:\nThis folder contains the various certificates templates that have been created for the rating tool. It is not recommended to make this folder visible to all.";
@@ -274,4 +274,11 @@ $NoSVGImagesInImagesGalleryPath = "There are no SVG images in your images galler
 $NoSVGImages = "No SVG image";
 $WamiNeedFilename = "Before you activate recording it is necessary a file name.";
 $SelectAnAudioFileFromDocuments = "Select an audio file from documents";
-?>
+$ConvertedFromX = "Converted from %s";
+$PleaseSelectConvertFormat = "Please, Select a format for conversion";
+$ConvertFormats = "Formats for conversion";
+$SelectConvertFormat = "Select target format";
+$ConvertedFromXToY = "Converted from %s to %s";
+$Convert = "Convert";
+$FormatNotSupported = "Conversion format is not supported";
+$ErrorSameFormat = "Target format and origin format for conversion do not match same format type";

+ 16 - 9
main/lang/spanish/document.inc.php

@@ -231,14 +231,14 @@ $FileExistsChangeToSave = "Este nombre de archivo ya existe, escoja otro para gu
 $FileSavedAs = "Archivo guardado como";
 $FileExportAs = "Archivo exportado como";
 $UserFolder = "Carpeta del usuario";
-$HelpUsersFolder = "INFORMACIÓN SOLO VISIBLE POR EL PROFESORADO:\nLa carpeta de los usuarios contiene una carpeta de cada usuario que haya accedido a ella a través de la herramienta documentos, o bien que haya enviado algún fichero al curso a través del editor, salvo desde la herramienta grupos. Si ninguna de las dos circuntancias se ha producido la carpeta del usuario no estará creada. En el caso de los grupos, los archivos que se envíen a través del editor se depositarán en la carpeta de cada grupo, la cual sólo será accesible por los alumnos desde la herramienta grupos.
-
-La carpeta de los usuarios y las carpetas que contiene de cada uno de ellos, se mantendrán por ocultas por defecto, si bien cada alumno podrá ver el contenido de la suya cuando acceda a inspeccionar los archivos del servidor a través del editor. No obstante, si un alumno conoce la dirección de un archivo de la carpeta de otro alumno podrá visualizarlo.
-
-Si se hace visible la carpeta de los usuarios y la carpeta de uno o más alumnos, el resto de los alumnos podrán ver todo su contenido. En este caso, el alumno propietario de la carpeta también podrá desde la herramienta documentos (sólo dentro de su carpeta): crear y editar documentos web, convertir un documento web en una plantilla para uso personal, crear y editar dibujos SVG y PNG, grabar archivos de audio en formato WAV, convertir texto en audio en formato MP3, realizar capturas a través de su webcam, enviar documentos, crear carpetas, mover carpetas y archivos, borrar carpetas y archivos, y descargar copias de seguridad de su carpeta.
-
-Por otra parte, la herramienta documentos se sincroniza con el gestor de archivos del editor web, así que los cambios en la gestión de los documentos realizados en una u otra afectarán a ambas. 
-
+$HelpUsersFolder = "INFORMACIÓN SOLO VISIBLE POR EL PROFESORADO:\nLa carpeta de los usuarios contiene una carpeta de cada usuario que haya accedido a ella a través de la herramienta documentos, o bien que haya enviado algún fichero al curso a través del editor, salvo desde la herramienta grupos. Si ninguna de las dos circuntancias se ha producido la carpeta del usuario no estará creada. En el caso de los grupos, los archivos que se envíen a través del editor se depositarán en la carpeta de cada grupo, la cual sólo será accesible por los alumnos desde la herramienta grupos.
+
+La carpeta de los usuarios y las carpetas que contiene de cada uno de ellos, se mantendrán por ocultas por defecto, si bien cada alumno podrá ver el contenido de la suya cuando acceda a inspeccionar los archivos del servidor a través del editor. No obstante, si un alumno conoce la dirección de un archivo de la carpeta de otro alumno podrá visualizarlo.
+
+Si se hace visible la carpeta de los usuarios y la carpeta de uno o más alumnos, el resto de los alumnos podrán ver todo su contenido. En este caso, el alumno propietario de la carpeta también podrá desde la herramienta documentos (sólo dentro de su carpeta): crear y editar documentos web, convertir un documento web en una plantilla para uso personal, crear y editar dibujos SVG y PNG, grabar archivos de audio en formato WAV, convertir texto en audio en formato MP3, realizar capturas a través de su webcam, enviar documentos, crear carpetas, mover carpetas y archivos, borrar carpetas y archivos, y descargar copias de seguridad de su carpeta.
+
+Por otra parte, la herramienta documentos se sincroniza con el gestor de archivos del editor web, así que los cambios en la gestión de los documentos realizados en una u otra afectarán a ambas. 
+
 Así pues, la carpeta de usuario no sólo es un lugar para depositar los archivos, sino que se convierte en un completo gestor de los documentos que los estudiantes utilizan durante el curso. Además, recuerde que cualquier usuario podrá copiar un archivo, que sea visible, de cualquier carpeta de la herramienta documentos (sea o no la suya) a su portafolios o área personal de documentos de la red social, donde estará disponible para que lo pueda usar en otros cursos.";
 $HelpFolderChat = "INFORMACIÓN SOLO VISIBLE POR EL PROFESORADO:\nEsta carpeta contiene todas las sesiones que se han realizado en el chat. Aunque muchas veces las sesiones en el chat pueden ser triviales, en otras pueden ser dignas de ser tratadas como un documento más de trabajo. Para ello, sin cambiar la visibilidad de esta carpeta, haga visible el archivo y enlácelo donde considere oportuno. No se recomienda hacer visible esta carpeta.";
 $HelpFolderCertificates = "INFORMACIÓN SOLO VISIBLE POR EL PROFESORADO:\nEsta carpeta contiene los distintos modelos de certificados que se han creado para la herramienta Evaluaciones. No se recomienda hacer visible esta carpeta.";
@@ -274,4 +274,11 @@ $NoSVGImagesInImagesGalleryPath = "No existen imágenes SVG en su carpeta de gal
 $NoSVGImages = "No hay imágenes SVG";
 $WamiNeedFilename = "Antes de activar la grabación es necesario dar un nombre al archivo.";
 $SelectAnAudioFileFromDocuments = "Seleccionar un archivo de audio desde los documentos";
-?>
+$ConvertedFromX = "Convertido desde %s";
+$PleaseSelectConvertFormat = "Por favor, Seleccione un formato de conversión";
+$ConvertFormats = "Formatos de conversión";
+$SelectConvertFormat = "Seleccione el formato de conversión";
+$ConvertedFromXToY = "Convertido desde %s a %s";
+$Convert = "Convertir";
+$FormatNotSupported = "Formatos de conversión no soportados";
+$ErrorSameFormat = "El formato de destino es el mismo del formato de origen";

+ 113 - 0
main/newscorm/openoffice_document.class.php

@@ -211,4 +211,117 @@ abstract class OpenofficeDocument extends learnpath
     abstract function add_docs_to_visio();
 
     abstract function add_command_parameters();
+
+    /**
+     * Used to convert copied from document
+     * @param string $originalPath
+     * @param string $convertedPath
+     * @param string $convertedTitle
+     * @return bool
+     */
+    function convertCopyDocument($originalPath, $convertedPath, $convertedTitle){
+        global $_course;
+        $ids = array();
+        $originalPathInfo = pathinfo($originalPath);
+        $convertedPathInfo = pathinfo($convertedPath);
+        $this->base_work_dir = $originalPathInfo['dirname'];
+        $this->file_path = $originalPathInfo['basename'];
+        $this->created_dir = $convertedPathInfo['basename'];
+        $ppt2lpHost = api_get_setting('service_ppt2lp', 'host');
+        $permissionFile = api_get_permissions_for_new_files();
+        $permissionFolder = api_get_permissions_for_new_directories();
+        if (file_exists($this->base_work_dir . '/' . $this->created_dir)) {
+
+            return $ids;
+        }
+
+        if ($ppt2lpHost == 'localhost') {
+            if (IS_WINDOWS_OS) { // IS_WINDOWS_OS has been defined in main_api.lib.php
+                $converterPath = str_replace('/', '\\', api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png');
+                $classPath = $converterPath . ';' . $converterPath . '/jodconverter-2.2.2.jar;' . $converterPath . '/jodconverter-cli-2.2.2.jar';
+                $cmd = 'java -Dfile.encoding=UTF-8 -jar "' . $classPath . '/jodconverter-2.2.2.jar"';
+            } else {
+                $converterPath = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png';
+                $classPath = ' -Dfile.encoding=UTF-8 -jar jodconverter-cli-2.2.2.jar';
+                $cmd = 'cd ' . $converterPath . ' && java ' . $classPath . ' ';
+            }
+
+            $cmd .= ' -p ' . api_get_setting('service_ppt2lp', 'port');
+            // Call to the function implemented by child.
+            $cmd .= ' "' . $this->base_work_dir . '/' . $this->file_path . '"  "' . $this->base_work_dir . '/' . $this->created_dir . '"';
+            // To allow openoffice to manipulate docs.
+            @chmod($this->base_work_dir, $permissionFolder);
+            @chmod($this->base_work_dir . '/' . $this->file_path, $permissionFile);
+
+            $locale = $this->original_locale; // TODO: Improve it because we're not sure this locale is present everywhere.
+            putenv('LC_ALL=' . $locale);
+
+            $files = array();
+            $return = 0;
+            $shell = exec($cmd, $files, $return);
+            // TODO: Chown is not working, root keep user privileges, should be www-data
+            @chown($this->base_work_dir . '/' . $this->created_dir, 'www-data');
+            @chmod($this->base_work_dir . '/' . $this->created_dir, $permissionFile);
+
+            if ($return != 0) { // If the java application returns an error code.
+                switch ($return) {
+                    // Can't connect to openoffice.
+                    case 1: $this->error = get_lang('CannotConnectToOpenOffice');
+                        break;
+                    // Conversion failed in openoffice.
+                    case 2: $this->error = get_lang('OogieConversionFailed');
+                        break;
+                    // Conversion can't be launch because command failed.
+                    case 255: $this->error = get_lang('OogieUnknownError');
+                        break;
+                }
+                DocumentManager::delete_document($_course, $this->created_dir, $this->base_work_dir);
+                return false;
+            }
+        } else {
+            /*
+             * @TODO Create method to use webservice
+            // get result from webservices
+            $result = $this->_get_remote_ppt2lp_files($file);
+            $result = unserialize(base64_decode($result));
+
+            // Save remote images to server
+            chmod($this->base_work_dir.$this->created_dir, api_get_permissions_for_new_directories());
+            if (!empty($result['images'])) {
+                foreach ($result['images'] as $image => $img_data) {
+                    $image_path = $this->base_work_dir.$this->created_dir;
+                    @file_put_contents($image_path . '/' . $image, base64_decode($img_data));
+                    @chmod($image_path . '/' . $image, 0777);
+                }
+            }
+
+            // files info
+            $files = $result['files'];
+            */
+        }
+
+        if (file_exists($this->base_work_dir . '/' . $this->created_dir)) {
+
+            // Register Files to Document tool
+            $ids[] = add_document(
+                $_course,
+                '/' . $this->created_dir,
+                'file',
+                filesize($this->base_work_dir . '/' . $this->created_dir),
+                $convertedTitle,
+                sprintf(
+                    get_lang('ConvertedFromXToY'),
+                    strtoupper($originalPathInfo['extension']),
+                    strtoupper($convertedPathInfo['extension'])
+                ),
+                0,
+                true,
+                null,
+                api_get_session_id()
+            );
+            chmod($this->base_work_dir, $permissionFolder);
+        }
+
+        return $ids;
+    }
 }