Browse Source

Replace add_document with DocumentManager::addDocument

Julio Montoya 6 years ago
parent
commit
58434eb7b1

+ 2 - 2
main/document/create_audio.php

@@ -298,10 +298,10 @@ function downloadAudioGoogle($dir)
 
         return;
     }
-    
+
     // add document to database
     $relativeUrlPath = $dir;
-    add_document(
+    DocumentManager::addDocument(
         $_course,
         $relativeUrlPath.$audio_filename,
         'file',

+ 1 - 1
main/document/create_document.php

@@ -526,7 +526,7 @@ if ($form->validate()) {
         );
         $save_file_path = $dir.$filename.'.'.$extension;
 
-        $document = add_document(
+        $document = DocumentManager::addDocument(
             $_course,
             $save_file_path,
             'file',

+ 11 - 21
main/document/downloadfolder.inc.php

@@ -32,7 +32,6 @@ $documentInfo = DocumentManager::get_document_data_by_id(
 if (!empty($sessionId)) {
     /* If no data found and session id exists
        try to look the file inside the session */
-
     if (empty($documentInfo)) {
         $documentInfo = DocumentManager::get_document_data_by_id(
             $_GET['id'],
@@ -55,7 +54,6 @@ if (($path == '/shared_folder' ||
     (!api_is_allowed_to_edit() || !api_is_platform_admin())
 ) {
     api_not_allowed(true);
-    exit;
 }
 
 // Creating a ZIP file.
@@ -121,6 +119,7 @@ if (!empty($groupId)) {
 } else {
     $groupCondition = " (props.to_group_id = 0 OR props.to_group_id IS NULL ) ";
 }
+$tblDocument = Database::get_course_table(TABLE_DOCUMENT);
 
 // Admins are allowed to download invisible files
 if (api_is_allowed_to_edit()) {
@@ -134,31 +133,25 @@ if (api_is_allowed_to_edit()) {
 
     // Search for all files that are not deleted => visibility != 2
     $sql = "SELECT
-                path,
+                docs.path,
                 docs.session_id,
                 docs.id,
-                props.to_group_id,
                 docs.c_id
-            FROM $doc_table AS docs
-            INNER JOIN $prop_table AS props
-            ON
-                docs.id = props.ref AND
-                docs.c_id = props.c_id
-                $groupJoin
-			WHERE
-			    props.tool ='".TOOL_DOCUMENT."' AND
+            FROM resource_node AS n
+            INNER JOIN $tblDocument AS docs
+            ON (docs.resource_node_id = n.id)
+            INNER JOIN resource_link l
+            ON (l.resource_node_id = n.id)                
+            WHERE	
+                docs.c_id = $courseId AND
                 docs.path LIKE '".$querypath."/%' AND
-                docs.filetype = 'file' AND
-                props.visibility <> '2' AND
-                $groupCondition AND
-                (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
-                docs.c_id = ".$courseId." ";
+                docs.filetype = 'file'";
 
     $sql .= DocumentManager::getSessionFolderFilters($querypath, $sessionId);
 
     $result = Database::query($sql);
     $files = [];
-    while ($row = Database::fetch_array($result)) {
+    while ($row = Database::fetch_array($result, 'ASSOC')) {
         $files[$row['path']] = $row;
     }
 
@@ -175,8 +168,6 @@ if (api_is_allowed_to_edit()) {
                 }
             }
         }
-        //error_log($sysCoursePath.$courseInfo['path'].'/document'.$not_deleted_file['path']);
-        //error_log($sysCoursePath.$courseInfo['path'].'/document'.$remove_dir);
         $zip->add(
             $sysCoursePath.$courseInfo['path'].'/document'.$not_deleted_file['path'],
             PCLZIP_OPT_REMOVE_PATH,
@@ -189,7 +180,6 @@ if (api_is_allowed_to_edit()) {
     Session::erase('doc_files_to_download');
 } else {
     // For other users, we need to create a zip  file with only visible files and folders
-
     if ($path == '/') {
         $querypath = ''; // To prevent ...path LIKE '//%'... in query
     } else {

+ 11 - 17
main/document/save_pixlr.php

@@ -140,8 +140,14 @@ if (empty($temp_file_2delete)) {
     // Add new document to disk
     file_put_contents($documentPath, $contents);
     // Add document to database
-    $documentId = add_document($courseInfo, $paintDir.$paintFileName, 'file', filesize($documentPath), $title);
-    if ($documentId) {
+    $document = DocumentManager::addDocument(
+        $courseInfo,
+        $paintDir.$paintFileName,
+        'file',
+        filesize($documentPath),
+        $title
+    );
+    if ($document) {
         Display::addFlash(Display::return_message(get_lang('Saved')));
     }
 } else {
@@ -171,27 +177,15 @@ if (empty($temp_file_2delete)) {
             $sessionId
         );
     } else {
-        //add a new document
-        $documentId = add_document(
+        // add a new document
+        $document = DocumentManager::addDocument(
             $courseInfo,
             $paintDir.$paintFileName,
             'file',
             filesize($documentPath),
             $title
         );
-        if ($documentId) {
-            api_item_property_update(
-                $courseInfo,
-                TOOL_DOCUMENT,
-                $documentId,
-                'DocumentAdded',
-                api_get_user_id(),
-                $groupInfo,
-                null,
-                null,
-                null,
-                $sessionId
-            );
+        if ($document) {
             Display::addFlash(Display::return_message(get_lang('Updated')));
         }
     }

+ 1 - 14
main/document/webcam_receiver.php

@@ -76,25 +76,12 @@ if (!$content) {
 }
 
 //add document to database
-$doc_id = add_document(
+$doc_id = DocumentManager::addDocument(
     $_course,
     $webcamdir.'/'.$webcamname_to_save,
     'file',
     filesize($documentPath),
     $title_to_save
 );
-api_item_property_update(
-    $_course,
-    TOOL_DOCUMENT,
-    $doc_id,
-    'DocumentAdded',
-    $_user['user_id'],
-    $groupInfo,
-    null,
-    null,
-    null,
-    $current_session_id
-);
-///
 $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI']).'/'.$documentPath;
 echo get_lang('ClipSent');

+ 1 - 1
main/exercise/exercise.class.php

@@ -1367,7 +1367,7 @@ class Exercise
                 $result = Database::query($sql);
 
                 if (!Database::num_rows($result)) {
-                    add_document(
+                    DocumentManager::addDocument(
                         $this->course,
                         str_replace($documentPath, '', $audioPath).'/'.$this->sound,
                         'file',

+ 6 - 6
main/exercise/hotpotatoes.php

@@ -56,7 +56,7 @@ if ($finish == 2 && isset($_POST['imgparams'])) {
 if (api_is_allowed_to_edit(null, true)) {
     if (hotpotatoes_init($document_sys_path.$uploadPath)) {
         // If the directory doesn't exist, create the "HotPotatoes" directory.
-        add_document(
+        DocumentManager::addDocument(
             $_course,
             '/HotPotatoes_files',
             'folder',
@@ -64,7 +64,7 @@ if (api_is_allowed_to_edit(null, true)) {
             get_lang('HotPotatoesFiles')
         );
         // Update properties in dbase (in any case).
-        api_item_property_update(
+        /*api_item_property_update(
             $_course,
             TOOL_DOCUMENT,
             $doc_id,
@@ -78,7 +78,7 @@ if (api_is_allowed_to_edit(null, true)) {
             $doc_id,
             'invisible',
             api_get_user_id()
-        );
+        );*/
     }
 }
 
@@ -131,14 +131,14 @@ if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2)))
                 $filename = api_replace_dangerous_char(trim($_FILES['userFile']['name']));
                 $fld = GenerateHpFolder($document_sys_path.$uploadPath.'/');
                 @mkdir($document_sys_path.$uploadPath.'/'.$fld, api_get_permissions_for_new_directories());
-                $doc_id = add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
-                api_item_property_update(
+                $doc_id = DocumentManager::addDocument($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
+                /*api_item_property_update(
                     $_course,
                     TOOL_DOCUMENT,
                     $doc_id,
                     'FolderCreated',
                     api_get_user_id()
-                );
+                );*/
             } else {
                 // It is not the first step... get the filename directly from the system params.
                 $filename = $_FILES['userFile']['name'];

+ 5 - 19
main/exercise/question.class.php

@@ -706,7 +706,7 @@ abstract class Question
             $pictureFilename = self::generatePictureName();
             $img = new Image($picture);
             $img->send_image($picturePath.'/'.$pictureFilename, -1, 'jpg');
-            $document_id = add_document(
+            $document = DocumentManager::addDocument(
                 $this->course,
                 '/images/'.$pictureFilename,
                 'file',
@@ -714,21 +714,13 @@ abstract class Question
                 $pictureFilename
             );
 
-            if ($document_id) {
-                $this->picture = $document_id;
+            if ($document) {
+                $this->picture = $document->getId();
 
                 if (!file_exists($picturePath.'/'.$pictureFilename)) {
                     return false;
                 }
 
-                api_item_property_update(
-                    $this->course,
-                    TOOL_DOCUMENT,
-                    $document_id,
-                    'DocumentAdded',
-                    api_get_user_id()
-                );
-
                 $this->resizePicture('width', 800);
 
                 return true;
@@ -840,7 +832,7 @@ abstract class Question
                 WHERE c_id = $course_id AND id='".intval($questionId)."'";
         Database::query($sql);
 
-        $documentId = add_document(
+        $documentId = DocumentManager::addDocument(
             $courseInfo,
             '/images/'.$picture,
             'file',
@@ -852,13 +844,7 @@ abstract class Question
             return false;
         }
 
-        return api_item_property_update(
-            $courseInfo,
-            TOOL_DOCUMENT,
-            $documentId,
-            'DocumentAdded',
-            api_get_user_id()
-        );
+        return true;
     }
 
     /**

+ 4 - 86
main/inc/lib/CourseChatUtils.php

@@ -132,7 +132,7 @@ class CourseChatUtils
         $absoluteFilePath = $chat_path.$fileTitle;
 
         if (!file_exists($absoluteFilePath)) {
-            $doc_id = add_document(
+            $doc_id = DocumentManager::addDocument(
                 $courseInfo,
                 $filePath,
                 'file',
@@ -146,24 +146,6 @@ class CourseChatUtils
                 0,
                 false
             );
-            $documentLogTypes = ['DocumentAdded', 'invisible'];
-
-            foreach ($documentLogTypes as $logType) {
-                api_item_property_update(
-                    $courseInfo,
-                    TOOL_DOCUMENT,
-                    $doc_id,
-                    $logType,
-                    $this->userId,
-                    $group_info,
-                    null,
-                    null,
-                    null,
-                    $this->sessionId
-                );
-            }
-
-            item_property_update_on_folder($courseInfo, $basepath_chat, $this->userId);
         } else {
             $doc_id = DocumentManager::get_document_id($courseInfo, $filePath);
         }
@@ -476,7 +458,7 @@ class CourseChatUtils
                 @mkdir($chat_path, api_get_permissions_for_new_directories());
                 // Save chat files document for group into item property
                 if ($this->groupId) {
-                    $doc_id = add_document(
+                    DocumentManager::addDocument(
                         $courseInfo,
                         $basepath_chat,
                         'folder',
@@ -490,17 +472,6 @@ class CourseChatUtils
                         0,
                         false
                     );
-                    api_item_property_update(
-                        $courseInfo,
-                        TOOL_DOCUMENT,
-                        $doc_id,
-                        'FolderCreated',
-                        null,
-                        $group_info,
-                        null,
-                        null,
-                        null
-                    );
                 }
             }
         }
@@ -522,7 +493,7 @@ class CourseChatUtils
         if (!file_exists($chat_path.$filename_chat)) {
             @fclose(fopen($chat_path.$filename_chat, 'w'));
             if (!api_is_anonymous()) {
-                $doc_id = add_document(
+                DocumentManager::addDocument(
                     $courseInfo,
                     $basepath_chat.'/'.$filename_chat,
                     'file',
@@ -536,33 +507,6 @@ class CourseChatUtils
                     0,
                     false
                 );
-                if ($doc_id) {
-                    api_item_property_update(
-                        $courseInfo,
-                        TOOL_DOCUMENT,
-                        $doc_id,
-                        'DocumentAdded',
-                        $this->userId,
-                        $group_info,
-                        null,
-                        null,
-                        null,
-                        $this->sessionId
-                    );
-                    api_item_property_update(
-                        $courseInfo,
-                        TOOL_DOCUMENT,
-                        $doc_id,
-                        'invisible',
-                        $this->userId,
-                        $group_info,
-                        null,
-                        null,
-                        null,
-                        $this->sessionId
-                    );
-                    item_property_update_on_folder($courseInfo, $basepath_chat, $this->userId);
-                }
             }
         }
 
@@ -588,7 +532,7 @@ class CourseChatUtils
             @rename($chat_path.$basename_chat.'.log.html', $chat_path.$basename_chat.'-'.$i.'.log.html');
             @fclose(fopen($chat_path.$basename_chat.'.log.html', 'w'));
 
-            $doc_id = add_document(
+            $doc_id = DocumentManager::addDocument(
                 $courseInfo,
                 $basepath_chat.'/'.$basename_chat.'-'.$i.'.log.html',
                 'file',
@@ -602,32 +546,6 @@ class CourseChatUtils
                 0,
                 false
             );
-
-            api_item_property_update(
-                $courseInfo,
-                TOOL_DOCUMENT,
-                $doc_id,
-                'DocumentAdded',
-                $this->userId,
-                $group_info,
-                null,
-                null,
-                null,
-                $this->sessionId
-            );
-            api_item_property_update(
-                $courseInfo,
-                TOOL_DOCUMENT,
-                $doc_id,
-                'invisible',
-                $this->userId,
-                $group_info,
-                null,
-                null,
-                null,
-                $this->sessionId
-            );
-            item_property_update_on_folder($courseInfo, $basepath_chat, $this->userId);
             $doc_id = DocumentManager::get_document_id(
                 $courseInfo,
                 $basepath_chat.'/'.$basename_chat.'.log.html'

+ 1 - 1
main/inc/lib/add_course.lib.inc.php

@@ -946,7 +946,7 @@ class AddCourse
      */
     public static function insertDocument($courseInfo, $counter, $file, $authorId = 0)
     {
-        add_document(
+        DocumentManager::addDocument(
             $courseInfo,
             $file['path'],
             $file['filetype'],

+ 216 - 26
main/inc/lib/document.lib.php

@@ -1,8 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+use Chamilo\CoreBundle\Entity\Resource\ResourceFile;
 use Chamilo\CoreBundle\Entity\Resource\ResourceLink;
+use Chamilo\CoreBundle\Entity\Resource\ResourceRight;
+use Chamilo\CoreBundle\Framework\Container;
+use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
 use Chamilo\CourseBundle\Entity\CDocument;
+use Symfony\Component\HttpFoundation\File\UploadedFile;
 use Chamilo\UserBundle\Entity\User;
 use ChamiloSession as Session;
 
@@ -2051,7 +2056,7 @@ class DocumentManager
                 $id = self::get_document_id_of_directory_certificate();
 
                 if (empty($id)) {
-                    add_document(
+                    self::addDocument(
                         $courseInfo,
                         $dir_name,
                         'folder',
@@ -2674,8 +2679,8 @@ class DocumentManager
                                             $filepath_dir
                                         );
 
-                                        //Add to item properties to the new folder
-                                        add_document(
+                                        // Add to item properties to the new folder
+                                        self::addDocument(
                                             $destination_course_info,
                                             $filepath_to_add,
                                             'folder',
@@ -2696,7 +2701,7 @@ class DocumentManager
                                         $size = filesize($destination_filepath);
 
                                         // Add to item properties to the file
-                                        add_document(
+                                        self::addDocument(
                                             $destination_course_info,
                                             $filepath_to_add,
                                             'file',
@@ -4402,7 +4407,7 @@ class DocumentManager
         $path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
         if (!is_dir($path.'audio')) {
             mkdir($path.'audio', api_get_permissions_for_new_directories());
-            add_document($_course, '/audio', 'folder', 0, 'Audio');
+            self::addDocument($_course, '/audio', 'folder', 0, 'Audio');
         }
 
         return $audioId;
@@ -4470,7 +4475,7 @@ class DocumentManager
             }
         }
 
-        $document = add_document(
+        $document = self::addDocument(
             $courseData,
             $saveFilePath,
             $fileType,
@@ -6207,27 +6212,9 @@ class DocumentManager
     {
         $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()
-                );
-            }
+            $doc = self::addDocument($_course, $file_path, 'link', 0, $name, $url);
 
-            // 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;
+            return $doc->getId();
         } else {
             return 0;
         }
@@ -6837,4 +6824,207 @@ class DocumentManager
 
         return $btn;
     }
+
+
+    /**
+     * Adds a new document to the database.
+     *
+     * @param array  $courseInfo
+     * @param string $path
+     * @param string $fileType
+     * @param int    $fileSize
+     * @param string $title
+     * @param string $comment
+     * @param int    $readonly
+     * @param int    $visibility       see ResourceLink constants
+     * @param int    $group_id         group.id
+     * @param int    $sessionId        Session ID, if any
+     * @param int    $userId           creator user id
+     * @param bool   $sendNotification
+     * @param string $content
+     * @param int    $parentId
+     *
+     * @return CDocument|false
+     */
+    public static function addDocument(
+        $courseInfo,
+        $path,
+        $fileType,
+        $fileSize,
+        $title,
+        $comment = null,
+        $readonly = 0,
+        $visibility = null,
+        $group_id = 0,
+        $sessionId = 0,
+        $userId = 0,
+        $sendNotification = true,
+        $content = '',
+        $parentId = 0
+    ) {
+        $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
+        $userId = empty($userId) ? api_get_user_id() : $userId;
+        $userEntity = api_get_user_entity($userId);
+        $courseEntity = api_get_course_entity(api_get_course_int_id());
+        $session = api_get_session_entity($sessionId);
+        $group = api_get_group_entity($group_id);
+        $readonly = (int) $readonly;
+
+        $em = Database::getManager();
+        $documentRepo = $em->getRepository('ChamiloCourseBundle:CDocument');
+
+        $parentNode = null;
+        if (!empty($parentId)) {
+            $parent = $documentRepo->find($parentId);
+            $parentNode = $parent->getResourceNode();
+        }
+
+        $document = new CDocument();
+        $document
+            ->setCourse($courseEntity)
+            ->setPath($path)
+            ->setFiletype($fileType)
+            ->setSize($fileSize)
+            ->setTitle($title)
+            ->setComment($comment)
+            ->setReadonly($readonly)
+            ->setSession($session)
+        ;
+
+        $em->persist($document);
+        $em->flush();
+
+        $resourceNode = $documentRepo->addResourceNode($document, $userEntity);
+        $resourceNode->setParent($parentNode);
+        $document->setResourceNode($resourceNode);
+
+        // Only create a ResourseFile and Media if there's a file involved
+        if ($fileType === 'file') {
+            $mediaManager = Container::$container->get('sonata.media.manager.media');
+            /** @var \Chamilo\MediaBundle\Entity\Media $media */
+            $media = $mediaManager->create();
+            $media->setName($title);
+
+            $fileName = basename($path);
+            $extension = pathinfo($fileName, PATHINFO_EXTENSION);
+            $media->setContext('default');
+
+            $provider = 'sonata.media.provider.image';
+            if (!in_array($extension, ['jpeg', 'jpg', 'gif', 'png'])) {
+                $provider = 'sonata.media.provider.file';
+            }
+
+            $media->setProviderName($provider);
+            $media->setEnabled(true);
+
+            if ($content instanceof UploadedFile) {
+                $file = $content;
+                $media->setSize($file->getSize());
+            } else {
+                $handle = tmpfile();
+                fwrite($handle, $content);
+                $file = new \Sonata\MediaBundle\Extra\ApiMediaFile($handle);
+                $file->setMimetype($media->getContentType());
+            }
+
+            $media->setBinaryContent($file);
+            $mediaManager->save($media, true);
+
+            $resourceFile = new ResourceFile();
+            $resourceFile->setMedia($media);
+            $resourceFile->setName($title);
+            $em->persist($resourceFile);
+
+            $resourceNode->setResourceFile($resourceFile);
+            $em->persist($resourceNode);
+        }
+
+        // By default visibility is published
+        // @todo change visibility
+        //$newVisibility = ResourceLink::VISIBILITY_PUBLISHED;
+
+        if (is_null($visibility)) {
+            $visibility = ResourceLink::VISIBILITY_PUBLISHED;
+        }
+
+        $link = new ResourceLink();
+        $link
+            ->setCourse($courseEntity)
+            ->setSession($session)
+            ->setGroup($group)
+            //->setUser($toUser)
+            ->setResourceNode($resourceNode)
+            ->setVisibility($visibility)
+        ;
+
+        $rights = [];
+        switch ($visibility) {
+            case ResourceLink::VISIBILITY_PENDING:
+            case ResourceLink::VISIBILITY_DRAFT:
+                $editorMask = ResourceNodeVoter::getEditorMask();
+                $resourceRight = new ResourceRight();
+                $resourceRight
+                    ->setMask($editorMask)
+                    ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
+                ;
+                $rights[] = $resourceRight;
+
+                break;
+        }
+
+        if (!empty($rights)) {
+            foreach ($rights as $right) {
+                $link->addResourceRight($right);
+            }
+        }
+
+        $em->persist($link);
+        $em->persist($document);
+        $em->flush();
+
+        $documentId = $document->getIid();
+        if ($documentId) {
+            $table = Database::get_course_table(TABLE_DOCUMENT);
+            $sql = "UPDATE $table SET id = iid WHERE iid = $documentId";
+            Database::query($sql);
+
+            /*if ($saveVisibility) {
+                api_set_default_visibility(
+                    $documentId,
+                    TOOL_DOCUMENT,
+                    $group_id,
+                    $courseInfo,
+                    $sessionId,
+                    $userId
+                );
+            }*/
+
+            $allowNotification = api_get_configuration_value('send_notification_when_document_added');
+            if ($sendNotification && $allowNotification) {
+                $courseTitle = $courseInfo['title'];
+                if (!empty($sessionId)) {
+                    $sessionInfo = api_get_session_info($sessionId);
+                    $courseTitle .= ' ( '.$sessionInfo['name'].') ';
+                }
+
+                $url = api_get_path(WEB_CODE_PATH).
+                    'document/showinframes.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&id='.$documentId;
+                $link = Display::url(basename($title), $url, ['target' => '_blank']);
+                $userInfo = api_get_user_info($userId);
+
+                $message = sprintf(
+                    get_lang('DocumentXHasBeenAddedToDocumentInYourCourseXByUserX'),
+                    $link,
+                    $courseTitle,
+                    $userInfo['complete_name']
+                );
+                $subject = sprintf(get_lang('NewDocumentAddedToCourseX'), $courseTitle);
+                MessageManager::sendMessageToAllUsersInCourse($subject, $message, $courseInfo, $sessionId);
+            }
+
+            return $document;
+        }
+
+        return false;
+    }
 }

+ 5 - 212
main/inc/lib/fileUpload.lib.php

@@ -1,13 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-use Chamilo\CoreBundle\Entity\Resource\ResourceFile;
-use Chamilo\CoreBundle\Entity\Resource\ResourceLink;
-use Chamilo\CoreBundle\Entity\Resource\ResourceRight;
 use Chamilo\CoreBundle\Framework\Container;
-use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
 use Chamilo\CourseBundle\Entity\CDocument;
-use Symfony\Component\HttpFoundation\File\UploadedFile;
 
 /**
  * FILE UPLOAD LIBRARY.
@@ -433,7 +428,7 @@ function handle_uploaded_document(
                                 // There might be cases where the file exists on disk but there is no registration of
                                 // that in the database
                                 // In this case, and if we are in overwrite mode, overwrite and create the db record
-                                $documentId = add_document(
+                                $documentId = DocumentManager::addDocument(
                                     $courseInfo,
                                     $filePath,
                                     'file',
@@ -489,7 +484,7 @@ function handle_uploaded_document(
                             return $filePath;
                         } else {
                             // Put the document data in the database
-                            $documentId = add_document(
+                            $documentId = DocumentManager::addDocument(
                                 $courseInfo,
                                 $filePath,
                                 'file',
@@ -582,7 +577,7 @@ function handle_uploaded_document(
                     if (true) {
                         ///chmod($fullPath, $filePermissions);
                         // Put the document data in the database
-                        $document = add_document(
+                        $document = DocumentManager::addDocument(
                             $courseInfo,
                             $filePath,
                             'file',
@@ -654,7 +649,7 @@ function handle_uploaded_document(
                             //chmod($fullPath, $filePermissions);
 
                             // Put the document data in the database
-                            $documentId = add_document(
+                            $documentId = DocumentManager::addDocument(
                                 $courseInfo,
                                 $filePath,
                                 'file',
@@ -1300,208 +1295,6 @@ function filter_extension(&$filename)
     }
 }
 
-/**
- * Adds a new document to the database.
- *
- * @param array  $courseInfo
- * @param string $path
- * @param string $fileType
- * @param int    $fileSize
- * @param string $title
- * @param string $comment
- * @param int    $readonly
- * @param int    $visibility       see ResourceLink constants
- * @param int    $group_id         group.id
- * @param int    $sessionId        Session ID, if any
- * @param int    $userId           creator user id
- * @param bool   $sendNotification
- * @param string $content
- * @param int    $parentId
- *
- * @return CDocument|false
- */
-function add_document(
-    $courseInfo,
-    $path,
-    $fileType,
-    $fileSize,
-    $title,
-    $comment = null,
-    $readonly = 0,
-    $visibility = null,
-    $group_id = 0,
-    $sessionId = 0,
-    $userId = 0,
-    $sendNotification = true,
-    $content = '',
-    $parentId = 0
-) {
-    $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
-    $userId = empty($userId) ? api_get_user_id() : $userId;
-    $userEntity = api_get_user_entity($userId);
-    $courseEntity = api_get_course_entity(api_get_course_int_id());
-    $session = api_get_session_entity($sessionId);
-    $group = api_get_group_entity($group_id);
-    $readonly = (int) $readonly;
-
-    $em = Database::getManager();
-    $documentRepo = $em->getRepository('ChamiloCourseBundle:CDocument');
-
-    $parentNode = null;
-    if (!empty($parentId)) {
-        $parent = $documentRepo->find($parentId);
-        $parentNode = $parent->getResourceNode();
-    }
-
-    $document = new CDocument();
-    $document
-        ->setCourse($courseEntity)
-        ->setPath($path)
-        ->setFiletype($fileType)
-        ->setSize($fileSize)
-        ->setTitle($title)
-        ->setComment($comment)
-        ->setReadonly($readonly)
-        ->setSession($session)
-    ;
-
-    $em->persist($document);
-    $em->flush();
-
-    $resourceNode = $documentRepo->addResourceNode($document, $userEntity);
-    $resourceNode->setParent($parentNode);
-    $document->setResourceNode($resourceNode);
-
-    // Only create a ResourseFile and Media if there's a file involved
-    if ($fileType === 'file') {
-        $mediaManager = Container::$container->get('sonata.media.manager.media');
-        /** @var \Chamilo\MediaBundle\Entity\Media $media */
-        $media = $mediaManager->create();
-        $media->setName($title);
-
-        $fileName = basename($path);
-        $extension = pathinfo($fileName, PATHINFO_EXTENSION);
-        $media->setContext('default');
-
-        $provider = 'sonata.media.provider.image';
-        if (!in_array($extension, ['jpeg', 'jpg', 'gif', 'png'])) {
-            $provider = 'sonata.media.provider.file';
-        }
-
-        $media->setProviderName($provider);
-        $media->setEnabled(true);
-
-        if ($content instanceof UploadedFile) {
-            $file = $content;
-            $media->setSize($file->getSize());
-        } else {
-            $handle = tmpfile();
-            fwrite($handle, $content);
-            $file = new \Sonata\MediaBundle\Extra\ApiMediaFile($handle);
-            $file->setMimetype($media->getContentType());
-        }
-
-        $media->setBinaryContent($file);
-        $mediaManager->save($media, true);
-
-        $resourceFile = new ResourceFile();
-        $resourceFile->setMedia($media);
-        $resourceFile->setName($title);
-        $em->persist($resourceFile);
-
-        $resourceNode->setResourceFile($resourceFile);
-        $em->persist($resourceNode);
-    }
-
-    // By default visibility is published
-    // @todo change visibility
-    //$newVisibility = ResourceLink::VISIBILITY_PUBLISHED;
-
-    if (is_null($visibility)) {
-        $visibility = ResourceLink::VISIBILITY_PUBLISHED;
-    }
-
-    $link = new ResourceLink();
-    $link
-        ->setCourse($courseEntity)
-        ->setSession($session)
-        ->setGroup($group)
-        //->setUser($toUser)
-        ->setResourceNode($resourceNode)
-        ->setVisibility($visibility)
-    ;
-
-    $rights = [];
-    switch ($visibility) {
-        case ResourceLink::VISIBILITY_PENDING:
-        case ResourceLink::VISIBILITY_DRAFT:
-            $editorMask = ResourceNodeVoter::getEditorMask();
-            $resourceRight = new ResourceRight();
-            $resourceRight
-                ->setMask($editorMask)
-                ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
-            ;
-            $rights[] = $resourceRight;
-
-            break;
-    }
-
-    if (!empty($rights)) {
-        foreach ($rights as $right) {
-            $link->addResourceRight($right);
-        }
-    }
-
-    $em->persist($link);
-    $em->persist($document);
-    $em->flush();
-
-    $documentId = $document->getIid();
-    if ($documentId) {
-        $table = Database::get_course_table(TABLE_DOCUMENT);
-        $sql = "UPDATE $table SET id = iid WHERE iid = $documentId";
-        Database::query($sql);
-
-        /*if ($saveVisibility) {
-            api_set_default_visibility(
-                $documentId,
-                TOOL_DOCUMENT,
-                $group_id,
-                $courseInfo,
-                $sessionId,
-                $userId
-            );
-        }*/
-
-        $allowNotification = api_get_configuration_value('send_notification_when_document_added');
-        if ($sendNotification && $allowNotification) {
-            $courseTitle = $courseInfo['title'];
-            if (!empty($sessionId)) {
-                $sessionInfo = api_get_session_info($sessionId);
-                $courseTitle .= ' ( '.$sessionInfo['name'].') ';
-            }
-
-            $url = api_get_path(WEB_CODE_PATH).
-                'document/showinframes.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&id='.$documentId;
-            $link = Display::url(basename($title), $url, ['target' => '_blank']);
-            $userInfo = api_get_user_info($userId);
-
-            $message = sprintf(
-                get_lang('DocumentXHasBeenAddedToDocumentInYourCourseXByUserX'),
-                $link,
-                $courseTitle,
-                $userInfo['complete_name']
-            );
-            $subject = sprintf(get_lang('NewDocumentAddedToCourseX'), $courseTitle);
-            MessageManager::sendMessageToAllUsersInCourse($subject, $message, $courseInfo, $sessionId);
-        }
-
-        return $document;
-    }
-
-    return false;
-}
-
 /**
  * Updates an existing document in the database
  * as the file exists, we only need to change the size.
@@ -1796,7 +1589,7 @@ function create_unexisting_directory(
 
             $rs = Database::query($sql);
             if (Database::num_rows($rs) == 0) {
-                $document = add_document(
+                $document = DocumentManager::addDocument(
                     $_course,
                     $systemFolderName,
                     'folder',

+ 2 - 26
main/inc/lib/javascript/svgedit/extensions/savefile_config.php

@@ -93,25 +93,13 @@ file_put_contents($documentPath, $contents);
 
 if (empty($drawFileNameFromSession)) {
     //add document to database
-    $doc_id = add_document(
+    $doc_id = DocumentManager::addDocument(
         $_course,
         $relativeUrlPath.'/'.$drawFileName,
         'file',
         filesize($documentPath),
         $title
     );
-    api_item_property_update(
-        $_course,
-        TOOL_DOCUMENT,
-        $doc_id,
-        'DocumentAdded',
-        api_get_user_id(),
-        $groupInfo,
-        null,
-        null,
-        null,
-        $sessionId
-    );
 } else {
     if ($drawFileNameFromSession == $drawFileName) {
         $document_id = DocumentManager::get_document_id(
@@ -138,25 +126,13 @@ if (empty($drawFileNameFromSession)) {
         );
     } else {
         //add a new document
-        $doc_id = add_document(
+        $doc_id = DocumentManager::addDocument(
             $_course,
             $relativeUrlPath.'/'.$drawFileName,
             'file',
             filesize($documentPath),
             $title
         );
-        api_item_property_update(
-            $_course,
-            TOOL_DOCUMENT,
-            $doc_id,
-            'DocumentAdded',
-            api_get_user_id(),
-            $groupInfo,
-            null,
-            null,
-            null,
-            $sessionId
-        );
     }
 }
 

+ 5 - 11
main/inc/lib/nanogong/receiver.php

@@ -66,18 +66,12 @@ if (!file_exists($documentPath)) {
     $groupId = $nano_group_id;
     $file_size = filesize($documentPath);
     $relativeUrlPath = $dir;
-    $doc_id = add_document($_course, $relativeUrlPath . $filename, 'file', filesize($documentPath), $title);
-    api_item_property_update(
+    $doc_id = DocumentManager::addDocument(
         $_course,
-        TOOL_DOCUMENT,
-        $doc_id,
-        'DocumentAdded',
-        $nano_user_id,
-        $groupInfo,
-        null,
-        null,
-        null,
-        $current_session_id
+        $relativeUrlPath.$filename,
+        'file',
+        filesize($documentPath),
+        $title
     );
 } else {
     return get_lang('FileExistRename');

+ 1 - 9
main/inc/lib/pdf.lib.php

@@ -831,7 +831,7 @@ class PDF
             $courseDirectory
         );
 
-        $docId = add_document(
+        DocumentManager::addDocument(
             $courseInfo,
             str_replace($courseDirectory, '/', $docPath),
             'file',
@@ -845,14 +845,6 @@ class PDF
             $userId
         );
 
-        api_item_property_update(
-            $courseInfo,
-            TOOL_DOCUMENT,
-            $docId,
-            'DocumentAdded',
-            $userId
-        );
-
         Display::addFlash(Display::return_message(get_lang('ItemAdded')));
     }
 

+ 2 - 27
main/inc/lib/svg-edit/extensions/savefile_config.php

@@ -117,26 +117,13 @@ $documentPath = $saveDir.'/'.$drawFileName;
 file_put_contents($documentPath, $contents);
 if ($currentTool == 'document/createdraw') {
     //add document to database
-    $doc_id = add_document(
+    $doc_id = DocumentManager::addDocument(
         $_course,
         $relativeUrlPath.'/'.$drawFileName,
         'file',
         filesize($documentPath),
         $title
     );
-    api_item_property_update(
-        $_course,
-        TOOL_DOCUMENT,
-        $doc_id,
-        'DocumentAdded',
-        $_user['user_id'],
-        $groupInfo,
-        null,
-        null,
-        null,
-        $current_session_id
-    );
-
 } elseif ($currentTool == 'document/editdraw') {
     //check path
     if (!isset($_SESSION['draw_file'])) {
@@ -168,25 +155,13 @@ if ($currentTool == 'document/createdraw') {
         );
     } else {
         //add a new document
-        $doc_id = add_document(
+        $doc_id = DocumentManager::addDocument(
             $_course,
             $relativeUrlPath.'/'.$drawFileName,
             'file',
             filesize($documentPath),
             $title
         );
-        api_item_property_update(
-            $_course,
-            TOOL_DOCUMENT,
-            $doc_id,
-            'DocumentAdded',
-            $_user['user_id'],
-            $groupInfo,
-            null,
-            null,
-            null,
-            $current_session_id
-        );
     }
 }
 

+ 12 - 85
main/lp/learnpath.class.php

@@ -663,7 +663,7 @@ class learnpath
                         $filepath.'audio',
                         api_get_permissions_for_new_directories()
                     );
-                    $audio_id = add_document(
+                    $audio_id = DocumentManager::addDocument(
                         $_course,
                         '/audio',
                         'folder',
@@ -676,30 +676,6 @@ class learnpath
                         $sessionId,
                         $userId
                     );
-                    api_item_property_update(
-                        $_course,
-                        TOOL_DOCUMENT,
-                        $audio_id,
-                        'FolderCreated',
-                        $userId,
-                        null,
-                        null,
-                        null,
-                        null,
-                        $sessionId
-                    );
-                    api_item_property_update(
-                        $_course,
-                        TOOL_DOCUMENT,
-                        $audio_id,
-                        'invisible',
-                        $userId,
-                        null,
-                        null,
-                        null,
-                        null,
-                        $sessionId
-                    );
                 }
 
                 $file_path = handle_uploaded_document(
@@ -1327,37 +1303,13 @@ class learnpath
             $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
             if (!is_dir($filepath.'audio')) {
                 mkdir($filepath.'audio', api_get_permissions_for_new_directories());
-                $audio_id = add_document(
+                $audio_id = DocumentManager::addDocument(
                     $_course,
                     '/audio',
                     'folder',
                     0,
                     'audio'
                 );
-                api_item_property_update(
-                    $_course,
-                    TOOL_DOCUMENT,
-                    $audio_id,
-                    'FolderCreated',
-                    api_get_user_id(),
-                    null,
-                    null,
-                    null,
-                    null,
-                    api_get_session_id()
-                );
-                api_item_property_update(
-                    $_course,
-                    TOOL_DOCUMENT,
-                    $audio_id,
-                    'invisible',
-                    api_get_user_id(),
-                    null,
-                    null,
-                    null,
-                    null,
-                    api_get_session_id()
-                );
             }
 
             // Upload file in documents.
@@ -7147,7 +7099,7 @@ class learnpath
                 $file_size = filesize($filepath.$filename);
                 $save_file_path = $dir.$filename;
 
-                $document_id = add_document(
+                $document = DocumentManager::addDocument(
                     $courseInfo,
                     $save_file_path,
                     'file',
@@ -7161,20 +7113,9 @@ class learnpath
                     $creatorId
                 );
 
-                if ($document_id) {
-                    api_item_property_update(
-                        $courseInfo,
-                        TOOL_DOCUMENT,
-                        $document_id,
-                        'DocumentAdded',
-                        $creatorId,
-                        null,
-                        null,
-                        null,
-                        null,
-                        $sessionId
-                    );
+                $document_id = $document->getId();
 
+                if ($document_id) {
                     $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
                     $new_title = $originalTitle;
 
@@ -9566,7 +9507,7 @@ class learnpath
         $fileSize = filesize($filepath.$filename);
         $saveFilePath = $dir.$filename;
 
-        $documentId = add_document(
+        $document = DocumentManager::addDocument(
             $courseInfo,
             $saveFilePath,
             'file',
@@ -9580,41 +9521,27 @@ class learnpath
             $creatorId
         );
 
-        if (!$documentId) {
+        $documentId = $document->getId();
+
+        if (!$document) {
             return 0;
         }
 
-        api_item_property_update(
-            $courseInfo,
-            TOOL_DOCUMENT,
-            $documentId,
-            'DocumentAdded',
-            $creatorId,
-            null,
-            null,
-            null,
-            null,
-            $sessionId
-        );
-
         $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
         $newTitle = $originalTitle;
 
         if ($newComment || $newTitle) {
             $em = Database::getManager();
 
-            /** @var CDocument $doc */
-            $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
-
             if ($newComment) {
-                $doc->setComment($newComment);
+                $document->setComment($newComment);
             }
 
             if ($newTitle) {
-                $doc->setTitle($newTitle);
+                $document->setTitle($newTitle);
             }
 
-            $em->persist($doc);
+            $em->persist($document);
             $em->flush();
         }
 

+ 1 - 25
main/lp/learnpathItem.class.php

@@ -4271,37 +4271,13 @@ class learnpathItem
                 $filepath.'audio',
                 api_get_permissions_for_new_directories()
             );
-            $audio_id = add_document(
+            DocumentManager::addDocument(
                 $course_info,
                 '/audio',
                 'folder',
                 0,
                 'audio'
             );
-            api_item_property_update(
-                $course_info,
-                TOOL_DOCUMENT,
-                $audio_id,
-                'FolderCreated',
-                api_get_user_id(),
-                null,
-                null,
-                null,
-                null,
-                api_get_session_id()
-            );
-            api_item_property_update(
-                $course_info,
-                TOOL_DOCUMENT,
-                $audio_id,
-                'invisible',
-                api_get_user_id(),
-                null,
-                null,
-                null,
-                null,
-                api_get_session_id()
-            );
         }
 
         $key = 'file';

+ 1 - 1
main/lp/openoffice_document.class.php

@@ -298,7 +298,7 @@ abstract class OpenofficeDocument extends learnpath
 
         if (file_exists($this->base_work_dir.'/'.$this->created_dir)) {
             // Register Files to Document tool
-            $ids[] = add_document(
+            $ids[] = DocumentManager::addDocument(
                 $_course,
                 '/'.$this->created_dir,
                 'file',

+ 3 - 10
main/wiki/wiki.inc.php

@@ -2427,7 +2427,7 @@ class Wiki
         $exportPath = $exportDir.'/'.$wikiFileName;
 
         file_put_contents($exportPath, $wikiContents);
-        $doc_id = add_document(
+        $document = DocumentManager::addDocument(
             $_course,
             $groupPath.'/'.$wikiFileName,
             'file',
@@ -2435,16 +2435,9 @@ class Wiki
             $wikiTitle
         );
 
-        api_item_property_update(
-            $_course,
-            TOOL_DOCUMENT,
-            $doc_id,
-            'DocumentAdded',
-            api_get_user_id(),
-            $groupInfo
-        );
+        $id = $document->getId();
 
-        return $doc_id;
+        return $id;
     }
 
     /**

+ 2 - 2
src/CoreBundle/Component/Editor/Driver/CourseDriver.php

@@ -252,7 +252,7 @@ class CourseDriver extends Driver implements DriverInterface
 
                 // Removing course path
                 $realPath = str_replace($realPathRoot, '/', $realPath);
-                add_document(
+                \DocumentManager::addDocument(
                     $this->connector->course,
                     $realPath,
                     'file',
@@ -348,7 +348,7 @@ class CourseDriver extends Driver implements DriverInterface
 
             // Removing course path
             $newPath = str_replace($realPathRoot, '/', $realPath);
-            $documentId = add_document(
+            $documentId = DocumentManager::addDocument(
                 $_course,
                 $newPath,
                 'folder',

+ 4 - 4
src/CourseBundle/Component/CourseCopy/CourseRestorer.php

@@ -352,7 +352,7 @@ class CourseRestorer
                     if (empty($documentData)) {
                         /* This means the folder exists in the
                         filesystem but not in the DB, trying to fix it */
-                        add_document(
+                        DocumentManager::addDocument(
                             $course_info,
                             $folderToCreate,
                             'folder',
@@ -413,7 +413,7 @@ class CourseRestorer
                             }
 
                             // This code fixes the possibility for a file without a directory entry to be
-                            $document_id = add_document(
+                            $document_id = DocumentManager::addDocument(
                                 $course_info,
                                 $new,
                                 'folder',
@@ -436,7 +436,7 @@ class CourseRestorer
                             $insertUserId = $this->checkUserId($insertUserId);
                             $toUserId = $this->checkUserId($toUserId, true);
 
-                            api_item_property_update(
+                            /*api_item_property_update(
                                 $course_info,
                                 TOOL_DOCUMENT,
                                 $document_id,
@@ -447,7 +447,7 @@ class CourseRestorer
                                 null,
                                 null,
                                 $my_session_id
-                            );
+                            );*/
                         }
                     }
                 }