Added the cloud file links feature to be able to add links to cloud hostings as if they were documents.

pull/2487/head
Aquilino Blanco 8 years ago
parent a7a1cb02d7
commit cbd785478c
  1. 45
      app/Migrations/Schema/V111/Version20171127103000.php
  2. 182
      main/document/add_link.php
  3. 87
      main/document/document.php
  4. 69
      main/document/edit_document.php
  5. BIN
      main/img/clouddoc.png
  6. BIN
      main/img/clouddoc_new.png
  7. BIN
      main/img/icons/22/clouddoc.png
  8. BIN
      main/img/icons/22/clouddoc_new.png
  9. BIN
      main/img/icons/32/clouddoc_new.png
  10. 128
      main/inc/lib/document.lib.php
  11. 56
      main/inc/lib/urlUtils.lib.php
  12. 8
      main/install/data.sql
  13. 16
      main/lang/english/trad4all.inc.php
  14. 16
      main/lang/galician/trad4all.inc.php
  15. 16
      main/lang/spanish/trad4all.inc.php

@ -0,0 +1,45 @@
<?php
/* For licensing terms, see /license.txt */
namespace Application\Migrations\Schema\V111;
use Application\Migrations\AbstractMigrationChamilo,
Doctrine\DBAL\Schema\Schema,
Doctrine\DBAL\Types\Type;
/**
* Class Version20171127103000
*
* Adding cloud files' link document type and enabling/disabling option
*
* @package Application\Migrations\Schema\V111
*/
class Version20171127103000 extends AbstractMigrationChamilo
{
/**
* @param \Doctrine\DBAL\Schema\Schema $schema
*/
public function up(Schema $schema)
{
$this->addSql("ALTER TABLE c_document CHANGE filetype filetype SET('file','folder','link');");
$this->addSql("INSERT INTO `settings_options` (`variable`, `value`, `display_text`) VALUES
('enable_add_file_link', 'true', 'Yes'),
('enable_add_file_link', 'false', 'No');");
$this->addSql("INSERT INTO `settings_current`
(`variable`, `subkey`, `type`, `category`, `selected_value`, `title`, `comment`, `scope`, `subkeytext`, `access_url`, `access_url_changeable`, `access_url_locked`)
VALUES ('enable_add_file_link', NULL, 'radio', 'Tools', 'false', 'enable_add_file_link_title', 'enable_add_file_link_comment', NULL, NULL, 1, 0, 0);");
}
/**
* @param \Doctrine\DBAL\Schema\Schema $schema
*/
public function down(Schema $schema)
{
$this->addSql("ALTER TABLE c_document CHANGE filetype filetype SET('file','folder');");
$this->addSql("DELETE FROM `settings_options` WHERE `variable` = 'enable_add_file_link'");
$this->addSql("DELETE FROM `settings_current` WHERE `variable` = 'enable_add_file_link'");
}
}

@ -0,0 +1,182 @@
<?php
/* For licensing terms, see /license.txt */
/**
* This script allows to add cloud file links to the document structure
* @package chamilo.document
*/
/**
* Code
*/
// Including the global initialization file
require_once '../inc/global.inc.php';
// Including additional libraries
require_once '../inc/lib/document.lib.php';
require_once '../inc/lib/urlUtils.lib.php';
if (api_get_setting('enable_add_file_link') == 'false') {
api_not_allowed(true);
}
$course_info = api_get_course_info();
if (empty($course_info)) {
api_not_allowed(true);
}
$document_data = DocumentManager::get_document_data_by_id($_REQUEST['id'], api_get_course_id(), true);
if (empty($document_data)) {
$document_id = $parent_id = 0;
$path = '/';
} else {
if ($document_data['filetype'] == 'folder') {
$document_id = $document_data['id'];
$path = $document_data['path']."/";
$parent_id = DocumentManager::get_document_id(api_get_course_info(), dirname($path));
}
}
$is_allowed_to_edit = api_is_allowed_to_edit(null, true);
if (api_get_group_id()) {
// If the group id is set, check if the user has the right to be here
// Needed for group related stuff
require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
// Get group info
$group_properties = GroupManager::get_group_properties(api_get_group_id());
if ($is_allowed_to_edit || GroupManager::is_user_in_group($_user['user_id'], api_get_group_id())) { // Only courseadmin or group members allowed
$to_group_id = api_get_group_id();
$req_gid = '&amp;gidReq='.api_get_group_id();
$interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq='.api_get_group_id(), 'name' => get_lang('GroupSpace'));
} else {
api_not_allowed(true);
}
} elseif ($is_allowed_to_edit || DocumentManager::is_my_shared_folder(api_get_user_id(), $path, api_get_session_id())) {
// Admin for "regular" upload, no group documents. And check if is my shared folder
$to_group_id = 0;
$req_gid = '';
} else { // No course admin and no group member...
api_not_allowed(true);
}
// Group docs can only be uploaded in the group directory
if ($to_group_id != 0 && $path == '/') {
$path = $group_properties['directory'] . "/";
}
// Breadcrumbs
if ($is_certificate_mode) {
$interbreadcrumb[] = array('url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('Gradebook'));
} else {
$interbreadcrumb[] = array('url' => './document.php?id='.$document_id.$req_gid, 'name'=> get_lang('Documents'));
}
// Interbreadcrumb for the current directory root path
if (empty($document_data['parents'])) {
// Hack in order to not add the document to the breadcrumb in case it is a link
if ($document_data['filetype'] != 'link') {
$interbreadcrumb[] = array('url' => '#', 'name' => $document_data['title']);
}
} else {
foreach ($document_data['parents'] as $document_sub_data) {
// Hack in order to not add the document to the breadcrumb in case it is a link
if ($document_data['filetype'] != 'link') {
$interbreadcrumb[] = array('url' => $document_sub_data['document_url'], 'name' => $document_sub_data['title']);
}
}
}
$this_section = SECTION_COURSES;
$nameTools = get_lang('LinkAdd');
// Display the header
Display::display_header($nameTools, 'Doc');
/* Here we do all the work */
// Actions
echo '<div class="actions">';
// Link back to the documents overview
if ($is_certificate_mode) {
echo '<a href="document.php?id='.$document_id.'&selectcat=' . $selectcat.'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('CertificateOverview'), '', ICON_SIZE_MEDIUM).'</a>';
} else {
echo '<a href="document.php?id='.$document_id.'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('DocumentsOverview'), '', ICON_SIZE_MEDIUM).'</a>';
}
echo '</div>';
// Form to select directory
$folders = DocumentManager::get_all_document_folders(
$_course,
$groupIid,
$is_allowed_to_edit
);
if (!$is_certificate_mode) {
echo DocumentManager::build_directory_selector(
$folders,
$document_id,
(isset($group_properties['directory']) ? $group_properties['directory'] : array())
);
}
$action = api_get_self().'?'.api_get_cidreq().'&id='.$document_id;
// URLs in whitelist
$urlWL = URLUtils::getFileHostingsWL();
sort($urlWL);
$urlWLRegEx = '/(\/\/|\.)('.implode('|', $urlWL).')/i'; //Matches any of the whitelisted urls preceded by // or .
$urlWLText = "\n\t* ".implode("\n\t* ", $urlWL);
$urlWLHTML = "<ul><li>".implode("</li><li>", $urlWL)."</li></ul>";
$form = new FormValidator('upload', 'POST', $action, '', array('enctype' => 'multipart/form-data'));
$form->addElement('hidden', 'linkid', $document_id);
$form->addElement('hidden', 'curdirpath', $path);
$form->addElement('text', 'name', get_lang('LinkName'), array('id' => 'name_link'));
$form->addElement('text', 'url', get_lang('Url'), array('id' => 'url_link'));
$form->addElement('static', 'info', '', '<span class="text-primary" data-toggle="tooltip" title="'.$urlWLHTML.'">'.get_lang('ValidDomainsList').' <span class="glyphicon glyphicon-question-sign"></span></span>');
$form->addButtonSend(get_lang('AddCloudLink'), 'submitDocument');
$form->addRule('name', get_lang('PleaseEnterCloudLinkName'), 'required', null, 'client');
$form->addRule('name', get_lang('PleaseEnterCloudLinkName'), 'required', null, 'server');
$form->addRule('url', get_lang('langGiveURL'), 'required', null, 'client');
$form->addRule('url', get_lang('langGiveURL'), 'required', null, 'server');
// Well formed url pattern (must have the protocol)
$urlRegEx = URLUtils::getWellformedUrlRegex();
$form->addRule('url', get_lang('MalformedUrl'), 'regex', $urlRegEx, 'client');
$form->addRule('url', get_lang('MalformedUrl'), 'regex', $urlRegEx, 'server');
$form->addRule('url', get_lang('NotValidDomain').$urlWLText, 'regex', $urlWLRegEx, 'client');
$form->addRule('url', get_lang('NotValidDomain').$urlWLHTML, 'regex', $urlWLRegEx, 'server');
if ($form->validate()) {
if (isset($_REQUEST['linkid'])) {
$doc_id = DocumentManager::addCloudLink($course_info, $path, $_REQUEST['url'], $_REQUEST['name']);
if ($doc_id) {
Display::display_confirmation_message(get_lang('CloudLinkAdded') . '<br />', false);
} else {
if (DocumentManager::cloudLinkExists($course_info, $path, $_REQUEST['url'])) {
Display::display_error_message(get_lang('UrlAlreadyExists'), false);
} else {
Display::display_error_message(get_lang('ErrorAddCloudLink'), false);
}
}
}
}
// Add tooltip and correctly parse its inner HTML
echo '<script>
$(document).ready(function() {
$("[data-toggle=\'tooltip\']").tooltip(
{
content:
function() {
return $(this).attr("title");
}
}
);
});
</script>';
echo $form->return_form();
Display::display_footer();

@ -252,6 +252,7 @@ switch ($action) {
// Check whether the document is in the database. // Check whether the document is in the database.
if (!empty($documentInfo)) { if (!empty($documentInfo)) {
if ($documentInfo['filetype'] != 'link') {
$deleteDocument = DocumentManager::delete_document( $deleteDocument = DocumentManager::delete_document(
$courseInfo, $courseInfo,
null, null,
@ -260,6 +261,10 @@ switch ($action) {
$_GET['deleteid'], $_GET['deleteid'],
$groupIid $groupIid
); );
} else {
// Cloud Links
$deleteDocument = DocumentManager::deleteCloudLink($_course, $_GET['deleteid']);
}
if ($deleteDocument) { if ($deleteDocument) {
$certificateId = isset($_GET['delete_certificate_id']) ? $_GET['delete_certificate_id'] : null; $certificateId = isset($_GET['delete_certificate_id']) ? $_GET['delete_certificate_id'] : null;
@ -267,10 +272,24 @@ switch ($action) {
api_get_course_id(), api_get_course_id(),
$certificateId $certificateId
); );
if ($documentInfo['filetype'] != 'link') {
Display::addFlash(Display::return_message( Display::addFlash(Display::return_message(
get_lang('DocDeleted').': '.$documentInfo['title'], get_lang('DocDeleted').': '.$documentInfo['title'],
'success' 'success'
)); ));
} else {
if ($documentInfo['filetype'] != 'link') {
Display::addFlash(Display::return_message(
get_lang('CloudLinkDeleted').': '.$data['title'],
'success'
));
} else {
Display::addFlash(Display::return_message(
get_lang('CloudLinkDeleteError').': '.$data['title'],
'error'
));
}
}
} else { } else {
Display::addFlash(Display::return_message(get_lang('DocDeleteError'), 'warning')); Display::addFlash(Display::return_message(get_lang('DocDeleteError'), 'warning'));
} }
@ -574,6 +593,11 @@ if (isset($document_id) && empty($action)) {
if ($document_data) { if ($document_data) {
$parent_id = $document_data['parent_id']; $parent_id = $document_data['parent_id'];
// Hack in order to clean the document id in case of false positive from links
if ($document_data['filetype'] == 'link') {
$document_id = null;
}
$visibility = DocumentManager::check_visibility_tree( $visibility = DocumentManager::check_visibility_tree(
$document_id, $document_id,
api_get_course_id(), api_get_course_id(),
@ -582,7 +606,7 @@ if (isset($document_id) && empty($action)) {
$groupIid $groupIid
); );
if (!empty($document_data['filetype']) && $document_data['filetype'] == 'file') { if (!empty($document_data['filetype']) && $document_data['filetype'] == 'file' || $document_data['filetype'] == "link") {
if ($visibility && api_is_allowed_to_session_edit()) { if ($visibility && api_is_allowed_to_session_edit()) {
$url = api_get_path(WEB_COURSE_PATH). $url = api_get_path(WEB_COURSE_PATH).
$courseInfo['path'].'/document'.$document_data['path'].'?' $courseInfo['path'].'/document'.$document_data['path'].'?'
@ -898,11 +922,14 @@ if (empty($document_data['parents'])) {
'name' => $document_data['title'], 'name' => $document_data['title'],
); );
} else { } else {
// Hack in order to not add the document to the breadcrumb in case it is a link
if ($document_data['filetype'] != 'link') {
$interbreadcrumb[] = array( $interbreadcrumb[] = array(
'url' => '#', 'url' => '#',
'name' => $document_data['title'] 'name' => $document_data['title']
); );
} }
}
} else { } else {
$counter = 0; $counter = 0;
foreach ($document_data['parents'] as $document_sub_data) { foreach ($document_data['parents'] as $document_sub_data) {
@ -1110,6 +1137,33 @@ if ($isAllowedToEdit || $group_member_with_upload_rights ||
// Security fix: make sure they can't move files that are not in the document table // Security fix: make sure they can't move files that are not in the document table
if (!empty($document_to_move)) { if (!empty($document_to_move)) {
if ($document_to_move['filetype'] == 'link') {
$real_path_target = $base_work_dir.$_POST['move_to'].'/';
if (!DocumentManager::cloudLinkExists($_course, $_POST['move_to'], $document_to_move['comment'])) {
$doc_id = $_POST['move_file'];
DocumentManager::updateDBInfoCloudLink($document_to_move['path'], $_POST['move_to'].'/', $doc_id);
//update database item property
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FileMoved', api_get_user_id(), $to_group_id, null, null, null, $session_id);
Display::addFlash(
Display::return_message(
get_lang('CloudLinkMoved'),
'success'
)
);
} else {
Display::addFlash(
Display::return_message(
get_lang('UrlAlreadyExists'),
'error'
)
);
}
// Set the current path
$curdirpath = $_POST['move_to'];
$curdirpathurl = urlencode($_POST['move_to']);
} else {
$real_path_target = $base_work_dir.$moveTo.'/'.basename($document_to_move['path']); $real_path_target = $base_work_dir.$moveTo.'/'.basename($document_to_move['path']);
$fileExist = false; $fileExist = false;
if (file_exists($real_path_target)) { if (file_exists($real_path_target)) {
@ -1174,6 +1228,7 @@ if ($isAllowedToEdit || $group_member_with_upload_rights ||
Display::addFlash(Display::return_message(get_lang('Impossible'), 'error')); Display::addFlash(Display::return_message(get_lang('Impossible'), 'error'));
} }
} }
}
} else { } else {
Display::addFlash(Display::return_message(get_lang('Impossible'), 'error')); Display::addFlash(Display::return_message(get_lang('Impossible'), 'error'));
} }
@ -1275,7 +1330,8 @@ if ($isAllowedToEdit ||
} }
$readonlyAlreadyChecked = true; $readonlyAlreadyChecked = true;
} }
if ($data['filetype'] != 'link') {
// Files and folders
$deleteDocument = DocumentManager::delete_document( $deleteDocument = DocumentManager::delete_document(
$courseInfo, $courseInfo,
null, null,
@ -1290,6 +1346,20 @@ if ($isAllowedToEdit ||
'confirmation' 'confirmation'
); );
} }
} else {
// Cloud Links
if (DocumentManager::deleteCloudLink($_course, $documentId)) {
$messages .= Display::return_message(
get_lang('CloudLinkDeleted'),
'confirmation'
);
} else {
$messages .= Display::return_message(
get_lang('CloudLinkDeleteError'),
'error'
);
}
}
break; break;
} }
} }
@ -1741,6 +1811,14 @@ if ($isAllowedToEdit ||
api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq().'&id='.$document_id.'&createdir=1' api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq().'&id='.$document_id.'&createdir=1'
); );
} }
// "Add cloud link" icon
if (api_get_setting('enable_add_file_link') == 'true') {
$actionsLeft .= Display::url(
Display::return_icon('clouddoc_new.png', get_lang('AddCloudLink'), '', ICON_SIZE_MEDIUM),
api_get_path(WEB_CODE_PATH).'document/add_link.php?'.api_get_cidreq().'&id='.$document_id
);
}
} }
require 'document_slideshow.inc.php'; require 'document_slideshow.inc.php';
if (!isset($_GET['keyword'])) { if (!isset($_GET['keyword'])) {
@ -1845,6 +1923,11 @@ if (isset($documentAndFolders) && is_array($documentAndFolders)) {
} }
} }
// Hack in order to avoid the download icon appearing on cloud links
if ($document_data['filetype'] == 'link') {
$size = 0;
}
// Icons (clickable) // Icons (clickable)
$row[] = DocumentManager::create_document_link( $row[] = DocumentManager::create_document_link(
$document_data, $document_data,

@ -28,6 +28,7 @@ use ChamiloSession as Session;
*/ */
require_once __DIR__.'/../inc/global.inc.php'; require_once __DIR__.'/../inc/global.inc.php';
require_once '../inc/lib/urlUtils.lib.php';
$groupRights = Session::read('group_member_with_upload_rights'); $groupRights = Session::read('group_member_with_upload_rights');
@ -91,6 +92,7 @@ if (isset($_GET['id'])) {
$dir_original = $dir; $dir_original = $dir;
$doc = basename($file); $doc = basename($file);
$readonly = $document_data['readonly']; $readonly = $document_data['readonly'];
$file_type = $document_data['filetype'];
} }
if (empty($document_data)) { if (empty($document_data)) {
@ -213,6 +215,12 @@ if (isset($_POST['comment'])) {
} }
if (!empty($document_id)) { if (!empty($document_id)) {
$linkExists = false;
if ($file_type == 'link') {
$linkExists = DocumentManager::cloudLinkExists($course_info, $file, $_POST['comment']);
}
if (!$linkExists || $linkExists == $document_id) {
$params = [ $params = [
'comment' => $comment, 'comment' => $comment,
'title' => $title, 'title' => $title,
@ -222,7 +230,15 @@ if (isset($_POST['comment'])) {
$params, $params,
['c_id = ? AND id = ?' => [$course_id, $document_id]] ['c_id = ? AND id = ?' => [$course_id, $document_id]]
); );
if ($file_type != 'link') {
Display::addFlash(Display::return_message(get_lang('fileModified'))); Display::addFlash(Display::return_message(get_lang('fileModified')));
} else {
Display::addFlash(Display::return_message(get_lang('CloudLinkModified')));
}
} else {
Display::addFlash(Display::return_message(get_lang('UrlAlreadyExists'), 'warning'));
}
} }
} }
@ -245,7 +261,9 @@ if ($is_allowed_to_edit) {
if (empty($filename)) { if (empty($filename)) {
Display::addFlash(Display::return_message(get_lang('NoFileName'), 'warning')); Display::addFlash(Display::return_message(get_lang('NoFileName'), 'warning'));
} else { } else {
if ($file_type != 'link') {
$file_size = filesize($document_data['absolute_path']); $file_size = filesize($document_data['absolute_path']);
}
if ($read_only_flag == 0) { if ($read_only_flag == 0) {
if (!empty($content)) { if (!empty($content)) {
@ -380,9 +398,10 @@ if ($owner_id == api_get_user_id() ||
$form->addElement('hidden', 'showedit'); $form->addElement('hidden', 'showedit');
$form->addElement('hidden', 'origin'); $form->addElement('hidden', 'origin');
$form->addElement('hidden', 'origin_opt'); $form->addElement('hidden', 'origin_opt');
$key_label_title = ($file_type != 'link' ? 'Title' : 'LinkName');
$form->addText( $form->addText(
'title', 'title',
get_lang('Title'), get_lang($key_label_title),
true, true,
array('cols-size' => [2, 10, 0], 'autofocus') array('cols-size' => [2, 10, 0], 'autofocus')
); );
@ -412,24 +431,54 @@ if ($owner_id == api_get_user_id() ||
} }
} }
if ($file_type != 'link') {
if (!$group_document && !DocumentManager::is_my_shared_folder(api_get_user_id(), $currentDirPath, $sessionId)) { if (!$group_document && !DocumentManager::is_my_shared_folder(api_get_user_id(), $currentDirPath, $sessionId)) {
// Updated on field // Updated on field
$display_date = date_to_str_ago($last_edit_date). $display_date = date_to_str_ago($last_edit_date).
' <span class="dropbox_date">'.api_format_date(api_get_local_time($last_edit_date)).'</span>'; ' <span class="dropbox_date">'.api_format_date(api_get_local_time($last_edit_date)).'</span>';
$form->addElement('static', null, get_lang('UpdatedOn'), $display_date); $form->addElement('static', null, get_lang('UpdatedOn'), $display_date);
} }
}
if ($file_type == 'link') {
// URLs in whitelist
$urlWL = URLUtils::getFileHostingsWL();
sort($urlWL);
$urlWLRegEx = '/(\/\/|\.)('.implode('|', $urlWL).')/i'; //Matches any of the whitelisted urls preceded by // or .
$urlWLText = "\n\t* ".implode("\n\t* ", $urlWL);
$urlWLHTML = "<ul><li>".implode("</li><li>", $urlWL)."</li></ul>";
$form->addText('comment', get_lang('Url'));
$form->addElement('static', 'info', '', '<span class="text-primary" data-toggle="tooltip" title="'.$urlWLHTML.'">'.get_lang('ValidDomainsList').' <span class="glyphicon glyphicon-question-sign"></span></span>');
} else {
$form->addElement('textarea', 'comment', get_lang('Comment'), ['cols-size' => [2, 10, 0]]); $form->addElement('textarea', 'comment', get_lang('Comment'), ['cols-size' => [2, 10, 0]]);
}
if ($file_type != 'link') {
if ($owner_id == api_get_user_id() || api_is_platform_admin()) { if ($owner_id == api_get_user_id() || api_is_platform_admin()) {
$checked = & $form->addElement('checkbox', 'readonly', null, get_lang('ReadOnly')); $checked = & $form->addElement('checkbox', 'readonly', null, get_lang('ReadOnly'));
if ($readonly == 1) { if ($readonly == 1) {
$checked->setChecked(true); $checked->setChecked(true);
} }
} }
}
if ($file_type == 'link') {
$form->addRule('title', get_lang('PleaseEnterCloudLinkName'), 'required', null, 'client');
$form->addRule('title', get_lang('PleaseEnterCloudLinkName'), 'required', null, 'server');
$form->addRule('comment', get_lang('langGiveURL'), 'required', null, 'client');
$form->addRule('comment', get_lang('langGiveURL'), 'required', null, 'server');
// Good formed url pattern (must have the protocol)
$urlRegEx = URLUtils::getWellformedUrlRegex();
$form->addRule('comment', get_lang('MalformedUrl'), 'regex', $urlRegEx, 'client');
$form->addRule('comment', get_lang('MalformedUrl'), 'regex', $urlRegEx, 'server');
$form->addRule('comment', get_lang('NotValidDomain').$urlWLText,'regex', $urlWLRegEx, 'client');
$form->addRule('comment', get_lang('NotValidDomain').$urlWLHTML,'regex', $urlWLRegEx, 'server');
}
if ($is_certificate_mode) { if ($is_certificate_mode) {
$form->addButtonUpdate(get_lang('SaveCertificate')); $form->addButtonUpdate(get_lang('SaveCertificate'));
} elseif ($file_type == 'link') {
$form->addButtonUpdate(get_lang('SaveLink'));
} else { } else {
$form->addButtonUpdate(get_lang('SaveDocument')); $form->addButtonUpdate(get_lang('SaveDocument'));
} }
@ -473,6 +522,7 @@ if ($owner_id == api_get_user_id() ||
if ($extension == 'svg' && !api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') { if ($extension == 'svg' && !api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
echo Display::return_message(get_lang('BrowserDontSupportsSVG'), 'warning'); echo Display::return_message(get_lang('BrowserDontSupportsSVG'), 'warning');
} }
if ($file_type != 'link') {
// HTML-editor // HTML-editor
echo '<div class="page-create"> echo '<div class="page-create">
<div class="row" style="overflow:hidden"> <div class="row" style="overflow:hidden">
@ -487,6 +537,23 @@ if ($owner_id == api_get_user_id() ||
'.$form->returnForm().' '.$form->returnForm().'
</div> </div>
</div></div>'; </div></div>';
} else {
// Add tooltip and correctly parse its inner HTML
echo '<script>
$(document).ready(function() {
$("[data-toggle=\'tooltip\']").tooltip(
{
content:
function() {
return $(this).attr("title");
}
}
);
});
</script>';
echo $form->return_form();
}
} }
Display::display_footer(); Display::display_footer();

Binary file not shown.

After

Width:  |  Height:  |  Size: 927 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 997 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 927 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 997 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

@ -5351,7 +5351,7 @@ class DocumentManager
// Get the title or the basename depending on what we're using // Get the title or the basename depending on what we're using
if ($document_data['title'] != '') { if ($document_data['title'] != '') {
$title = $document_data['title']; $title = htmlspecialchars($document_data['title']);
} else { } else {
$title = basename($document_data['path']); $title = basename($document_data['path']);
} }
@ -5406,6 +5406,12 @@ class DocumentManager
$tooltip_title = $title; $tooltip_title = $title;
$tooltip_title_alt = $tooltip_title; $tooltip_title_alt = $tooltip_title;
if ($filetype == 'link') {
$tooltip_title_alt = $title;
$url = $document_data['comment'].'" target="_blank';
}
if ($path == '/shared_folder') { if ($path == '/shared_folder') {
$tooltip_title_alt = get_lang('UserFolders'); $tooltip_title_alt = get_lang('UserFolders');
} elseif (strstr($path, 'shared_folder_session_')) { } elseif (strstr($path, 'shared_folder_session_')) {
@ -5655,6 +5661,9 @@ class DocumentManager
if ($type == 'file') { if ($type == 'file') {
$icon = choose_image($basename); $icon = choose_image($basename);
$basename = substr(strrchr($basename, '.'), 1); $basename = substr(strrchr($basename, '.'), 1);
} elseif ($type == 'link') {
$icon = 'clouddoc.png';
$basename = 'Cloud link';
} else { } else {
if ($path == '/shared_folder') { if ($path == '/shared_folder') {
$icon = 'folder_users.png'; $icon = 'folder_users.png';
@ -5992,11 +6001,19 @@ class DocumentManager
$is_read_only = $document_data['readonly']; $is_read_only = $document_data['readonly'];
$path = $document_data['path']; $path = $document_data['path'];
if ($type == 'link') {
$parent_id = self::get_document_id(
api_get_course_info(),
rtrim($path,'/'),
0
);
} else {
$parent_id = self::get_document_id( $parent_id = self::get_document_id(
api_get_course_info(), api_get_course_info(),
dirname($path), dirname($path),
0 0
); );
}
if (empty($parent_id) && !empty($sessionId)) { if (empty($parent_id) && !empty($sessionId)) {
$parent_id = self::get_document_id( $parent_id = self::get_document_id(
@ -6684,4 +6701,113 @@ class DocumentManager
return $result; return $result;
} }
/**
* Adds a cloud link to the database
*
* @author - Aquilino Blanco Cores <aqblanco@gmail.com>
* @param array $_course
* @param string $path
* @param string $url
* @return int id of document or 0 if already exists or there was a problem creating it
*/
public static function addCloudLink($_course, $path, $url, $name)
{
require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
$file_path = $path;
if (!self::cloudLinkExists($_course, $path, $url)) {
$doc_id = add_document($_course, $file_path, "link", 0, $name, $url);
if ($doc_id) {
// Update document item_property
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), api_get_group_id(), api_get_user_id(), null, null, api_get_session_id());
}
// If the file is in a folder, we need to update all parent folders
item_property_update_on_folder($_course, $file_path, api_get_user_id());
return $doc_id;
} else {
return 0;
}
}
/**
* Deletes a cloud link from the database
*
* @author - Aquilino Blanco Cores <aqblanco@gmail.com>
* @param array $_course
* @param string $id
* @param string $url
* @return boolean true if success / false if an error occurred
*/
public static function deleteCloudLink($_course, $id)
{
if (empty($id)) {
return false;
}
$document_id = $id;
$file_deleted_from_db = false;
if ($document_id) {
self::deleteDocumentFromDb($document_id, array(), 0, true);
//checking
$TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
$sql = "SELECT * FROM $TABLE_DOCUMENT WHERE id = $document_id";
$result = Database::query($sql);
$exists = Database::num_rows($result) > 0;
$file_deleted_from_db = !$exists ;
}
return $file_deleted_from_db;
}
/**
* Gets the id of a cloud link with a given path
*
* @author - Aquilino Blanco Cores <aqblanco@gmail.com>
* @param array $_course
* @param string $path
* @param string $url
* @return int id of link / false if no link found
* @deprecated
*/
public static function getCloudLinkId($_course, $path, $url)
{
$TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
$course_id = $_course['real_id'];
$path = Database::escape_string($path);
if (substr($path, -1) != '/') {
// Add final slash to path if not present
$path .= '/';
}
if (!empty($course_id) && !empty($path)) {
$sql = "SELECT id FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND path LIKE BINARY '$path' AND comment = '$url' AND filetype = 'link' LIMIT 1";
$result = Database::query($sql);
if ($result && Database::num_rows($result)) {
$row = Database::fetch_array($result);
return intval($row[0]);
}
}
return false;
}
/**
* Checks if a cloud link exists
*
* @author - Aquilino Blanco Cores <aqblanco@gmail.com>
* @param array $_course
* @param string $path
* @param string $url
* @return boolean true if it exists false in other case
*/
public static function cloudLinkExists($_course, $path, $url)
{
$exists = self::getCloudLinkId($_course, $path, $url);
return $exists;
}
} }

@ -0,0 +1,56 @@
<?php
/* For licensing terms, see /license.txt */
/**
* Class URLUtils
* This class contains some utilities to work with urls
*
* @package chamilo.library
*/
class URLUtils
{
/**
* Construct
*/
private function __construct()
{
}
/**
* Gets the wellformed URLs regular expression in order to use it on forms' verifications
*
* @author Aquilino Blanco Cores <aqblanco@gmail.com>
* @return the wellformed URLs regular expressions string
*/
public static function getWellformedUrlRegex()
{
return '/\(?((http|https|ftp):\/\/)(?:((?:[^\W\s]|\.|-|[:]{1})+)@{1})?((?:www.)?(?:[^\W\s]|\.|-)+[\.][^\W\s]{2,4}|localhost(?=\/)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d*))?([\/]?[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}\#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.\#]*)?([\.]{1}[^\s\?\#]*)?)?(?:\?{1}([^\s\n\#\[\]]*))?([\#][^\s\n]*)?\)?/i';
}
/**
* Gets the files hosting sites' whitelist
*
* @author Aquilino Blanco Cores <aqblanco@gmail.com>
* @return array the sites list.
*/
public static function getFileHostingsWL()
{
return array(
"asuswebstorage.com",
"dropbox.com",
"dropboxusercontent.com",
"fileserve.com",
"drive.google.com",
"icloud.com",
"mediafire.com",
"mega.nz",
"onedrive.live.com",
"slideshare.net",
"scribd.com",
"wetransfer.com",
"box.com",
"livefilestore.com" // OneDrive
);
}
}

@ -1961,3 +1961,11 @@ INSERT INTO settings_current (variable, type, category, selected_value, title, c
VALUES ('allow_download_documents_by_api_key', 'radio', 'WebServices', 'false', 'AllowDownloadDocumentsByApiKeyTitle', 'AllowDownloadDocumentsByApiKeyComment', '', NULL, 1); VALUES ('allow_download_documents_by_api_key', 'radio', 'WebServices', 'false', 'AllowDownloadDocumentsByApiKeyTitle', 'AllowDownloadDocumentsByApiKeyComment', '', NULL, 1);
INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_download_documents_by_api_key', 'true', 'Yes'); INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_download_documents_by_api_key', 'true', 'Yes');
INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_download_documents_by_api_key', 'false', 'No'); INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_download_documents_by_api_key', 'false', 'No');
-- Cloud File Links
INSERT INTO `settings_options` (`variable`, `value`, `display_text`) VALUES
('enable_add_file_link', 'true', 'Yes'),
('enable_add_file_link', 'false', 'No');
INSERT INTO `settings_current` (`variable`, `subkey`, `type`, `category`, `selected_value`, `title`, `comment`, `scope`, `subkeytext`, `access_url`, `access_url_changeable`, `access_url_locked`) VALUES
('enable_add_file_link', NULL, 'radio', 'Tools', 'false', 'enable_add_file_link_title', 'enable_add_file_link_comment', NULL, NULL, 1, 0, 0);

@ -8067,4 +8067,20 @@ $ThisEmailWasSentViaCourseX = "This e-mail was sent via course %s";
$ThisEmailWasSentViaCourseXInSessionX = "This e-mail was sent via course %s in session %s"; $ThisEmailWasSentViaCourseXInSessionX = "This e-mail was sent via course %s in session %s";
$Diagram = "Diagram"; $Diagram = "Diagram";
$CareerXDoesntHaveADiagram = "Career %s doesn't have a diagram."; $CareerXDoesntHaveADiagram = "Career %s doesn't have a diagram.";
// Cloud files in documents strings
$enable_add_file_link_title = 'Enable adding cloud files links';
$enable_add_file_link_comment = 'Tool for adding cloud files\' links from external storage sites (Dropbox, Google Drive...) at Documents.';
$UrlAlreadyExists = "It already exists one equal URL in this folder.";
$ErrorAddLink = "There was an error adding the link.";
$AddCloudLink = "Add cloud file link";
$CloudLinkDeleted = "Cloud file link deleted.";
$CloudLinkMoved = "Cloud file link moved.";
$CloudLinkDeleteError = "Error deleting cloud file link.";
$CloudLinkAdded = "Cloud file link added.";
$PleaseEnterCloudLinkName = "Please, enter a name for the cloud file link.";
$MalformedUrl = "URL field format not valid. Expected format example: http://dropbox.com/sh/loremipsum/loremipsum?dl=0";
$CloudLinkModified = "Cloud file link modified.";
$NotValidDomain = "Not valid domain. It must be one of these:";
$ValidDomainsList = "Valid domain list";
?> ?>

@ -7295,4 +7295,20 @@ $CourseImagesInCoursesListTitle = "Iconas de cursos personalizados";
$CourseImagesInCoursesListComment = "Usar as imaxes de cursos como iconas nas listas de cursos (no canto da icona verde por defecto)"; $CourseImagesInCoursesListComment = "Usar as imaxes de cursos como iconas nas listas de cursos (no canto da icona verde por defecto)";
$StudentPublicationSelectionForGradebookTitle = "Tarefas consideradas para avaliación"; $StudentPublicationSelectionForGradebookTitle = "Tarefas consideradas para avaliación";
$StudentPublicationSelectionForGradebookComment = "Na ferramenta de tarefas, os estudantes poden subir máis dun arquivo. No caso de haber máis dun arquivo do mesmo estudante para unha soa tarefa, cal destes debe ser considerado para a nota nas avaluacións? Isto depende da súa metodoloxía. Seleccione 'primeiro' para poñer o acento sobre a atención ao detalle (como entregar a tempo e o traballo finalizado a primeira vez). Use 'último' para poner o acento sobre o traballo colaborativo e a adaptabilidade."; $StudentPublicationSelectionForGradebookComment = "Na ferramenta de tarefas, os estudantes poden subir máis dun arquivo. No caso de haber máis dun arquivo do mesmo estudante para unha soa tarefa, cal destes debe ser considerado para a nota nas avaluacións? Isto depende da súa metodoloxía. Seleccione 'primeiro' para poñer o acento sobre a atención ao detalle (como entregar a tempo e o traballo finalizado a primeira vez). Use 'último' para poner o acento sobre o traballo colaborativo e a adaptabilidade.";
// Cloud files in documents strings
$enable_add_file_link_title = 'Permitir engadir enlaces a ficheiros na nube';
$enable_add_file_link_comment = 'Ferramenta para engadir enlaces a ficheiros situados en sitios de almacenamento externo (Dropbox, Google Drive, etc...) en Documentos.';
$UrlAlreadyExists = "Xa existe unha URL igual neste directorio.";
$ErrorAddLink = "Produciuse un erro engadindo o enlace.";
$AddCloudLink = "Engadir enlace a un ficheiro na nube";
$CloudLinkDeleted = "Enlace a ficheiro na nube eliminado.";
$CloudLinkMoved = "Enlace a ficheiro na nube movido.";
$CloudLinkDeleteError = "Erro ao eliminar o enlace ao ficheiro na nube.";
$CloudLinkAdded = "Enlace a ficheiro na nube engadido.";
$PleaseEnterCloudLinkName = "Por favor, introduza un nome para o enlace ao ficheiro na nube.";
$MalformedUrl = "Formato do campo URL non válido. Exemplo do formato esperado: http://dropbox.com/sh/loremipsum/loremipsum?dl=0";
$CloudLinkModified = "Enlace a ficheiro na nube modificado.";
$NotValidDomain = "Dominio non válido. Debe ser un dos seguintes:";
$ValidDomainsList = "Lista de dominios válidos";
?> ?>

@ -8081,4 +8081,20 @@ $OralExpressionHelpText = "Cuando lanza la grabación, puede pausar cuando lo de
$BestScoreInLearningPath = "Mejor nota en las lecciones"; $BestScoreInLearningPath = "Mejor nota en las lecciones";
$BestScoreNotInLearningPath = "Mejor nota fuera de lecciones"; $BestScoreNotInLearningPath = "Mejor nota fuera de lecciones";
$StudentXHadEnoughSkillsToGetSkillXToAssignClickHereX = "El alumno %s tiene suficiente competencias secundarias para obtener la competencia %s. Para asignar esta competencia, es posible ir aquí : %s"; $StudentXHadEnoughSkillsToGetSkillXToAssignClickHereX = "El alumno %s tiene suficiente competencias secundarias para obtener la competencia %s. Para asignar esta competencia, es posible ir aquí : %s";
// Cloud files in documents strings
$enable_add_file_link_title = 'Permitir añadir enlaces a ficheros en la nube';
$enable_add_file_link_comment = 'Herramienta para añadir enlaces a ficheros situados en sitios de almacenamiento externo (Dropbox, Google Drive, etc...) en Documentos.';
$UrlAlreadyExists = "Ya existe una URL igual en este directorio.";
$ErrorAddCloudLink = "Se produjo un error añadiendo el enlace al fichero en la nube.";
$AddCloudLink = "Añadir enlace a un fichero en la nube";
$CloudLinkDeleted = "Enlace a fichero en la nube eliminado.";
$CloudLinkMoved = "Enlace a fichero en la nube movido.";
$CloudLinkDeleteError = "Error al eliminar el enlace al fichero en la nube.";
$CloudLinkAdded = "Enlace a fichero en la nube añadido.";
$PleaseEnterCloudLinkName = "Por favor, introduzca un nombre para el enlace al fichero en la nube.";
$MalformedUrl = "Formato del campo URL no válido. Ejemplo del formato esperado: http://dropbox.com/sh/loremipsum/loremipsum?dl=0";
$CloudLinkModified = "Enlace a fichero en la nube modificado.";
$NotValidDomain = "Dominio no válido. Debe de ser uno de los siguientes:";
$ValidDomainsList = "Lista de dominios válidos";
?> ?>
Loading…
Cancel
Save