Beispiel #1
0
 public function saveDocumentStoreCategoryField($isNew, $pk, $fieldsData, $newMainCatId)
 {
     if (!$isNew) {
         $categoriesField = new JUDownloadFieldCore_categories(null, $pk);
         if ($this->getDocumentSubmitType($pk) == 'submit' && $categoriesField->canSubmit() || $this->getDocumentSubmitType($pk) == 'edit' && $categoriesField->canEdit()) {
             $categoriesField->is_new = $isNew;
             $categoriesFieldValue = $fieldsData[$categoriesField->id];
             $saveFieldCategory = $categoriesField->storeValue($categoriesFieldValue);
             if ($saveFieldCategory) {
                 $documentObject = JUDownloadHelper::getDocumentById($pk);
                 $mainCatIdDB = $documentObject->cat_id;
                 if ($mainCatIdDB != $newMainCatId) {
                     $fieldGroupIdDB = JUDownloadHelper::getCategoryById($mainCatIdDB)->fieldgroup_id;
                     $fieldGroupId = JUDownloadHelper::getCategoryById($newMainCatId)->fieldgroup_id;
                     if ($fieldGroupId != $fieldGroupIdDB) {
                         JUDownloadHelper::deleteFieldValuesOfDocument($pk);
                     }
                 }
             } else {
                 $this->setError('COM_JUDOWNLOAD_FAIL_TO_SAVE_CATEGORY_FIELD');
                 return false;
             }
         }
     }
     return true;
 }
Beispiel #2
0
	public static function optimizeListDocumentQuery(&$query, $massSelect = false)
	{
		$user = JFactory::getUser();
		$query->select('cmain.id AS cat_id');
		$query->join('', '#__judownload_documents_xref AS dxmain ON d.id = dxmain.doc_id AND dxmain.main = 1');
		$query->join('', '#__judownload_categories AS cmain ON cmain.id = dxmain.cat_id');

		
		$categoryIdArrayCanAccess = JUDownloadFrontHelperCategory::getAccessibleCategoryIds();
		if (is_array($categoryIdArrayCanAccess) && count($categoryIdArrayCanAccess) > 0)
		{
			$query->where('cmain.id IN(' . implode(",", $categoryIdArrayCanAccess) . ')');
		}
		else
		{
			$query->where('cmain.id IN("")');
		}

		if ($massSelect)
		{
			
			$query->select('(SELECT COUNT(*) FROM #__judownload_files AS f WHERE f.doc_id = d.id AND f.published = 1) AS total_files');

			
			$commentsField = new JUDownloadFieldCore_comments();
			if ($commentsField->canView(array("view" => "list")))
			{
				$isModerator = JUDownloadFrontHelperModerator::isModerator();
				if (!$isModerator && !$user->authorise('core.admin', 'com_judownload'))
				{
					$params                = JUDownloadHelper::getParams();
					$negative_vote_comment = $params->get('negative_vote_comment');
					if (is_numeric($negative_vote_comment) && $negative_vote_comment > 0)
					{
						$query->select('(SELECT COUNT(*) FROM #__judownload_comments AS cm WHERE cm.doc_id = d.id AND cm.approved = 1 AND cm.published = 1 AND cm.level = 1
										AND (cm.total_votes - cm.helpful_votes) < ' . $negative_vote_comment . ' ) AS total_comments');
					}
					else
					{
						$query->select('(SELECT COUNT(*) FROM #__judownload_comments AS cm WHERE cm.doc_id = d.id AND cm.approved = 1 AND cm.published = 1 AND cm.level = 1) AS total_comments');
					}
				}
			}

			
			$subscriptionsField = new JUDownloadFieldCore_subscriptions();
			if ($subscriptionsField->canView(array("view" => "list")))
			{
				$query->select('(SELECT COUNT(*) FROM #__judownload_subscriptions AS sub WHERE sub.item_id = d.id AND sub.type = "document" AND sub.published = 1) AS total_subscriptions');
			}

			
			$reportsField = new JUDownloadFieldCore_reports();
			if ($reportsField->canView(array("view" => "list")))
			{
				$query->select('(SELECT COUNT(*) FROM #__judownload_reports AS r WHERE r.item_id = d.id AND r.type = "document") AS total_reports');
			}

			$categoriesField = new JUDownloadFieldCore_categories();
			if ($categoriesField->canView(array("view" => "list")))
			{
				
				$query->select('(SELECT GROUP_CONCAT(catids.id ORDER BY dx_catids.main DESC, dx_catids.ordering ASC SEPARATOR ",") FROM (#__judownload_categories AS catids JOIN #__judownload_documents_xref AS dx_catids ON catids.id = dx_catids.cat_id) WHERE d.id = dx_catids.doc_id GROUP BY d.id) AS cat_ids');
				
				$query->select('(SELECT GROUP_CONCAT(cattitles.title ORDER BY dx_cattitles.main DESC, dx_cattitles.ordering ASC SEPARATOR "|||") FROM (#__judownload_categories AS cattitles JOIN #__judownload_documents_xref AS dx_cattitles ON cattitles.id = dx_cattitles.cat_id) WHERE d.id = dx_cattitles.doc_id GROUP BY d.id) AS cat_titles');
			}

			$tagsField = new JUDownloadFieldCore_tags();
			if ($tagsField->canView(array("view" => "list")))
			{
				
				
				$query->select('IFNULL ((SELECT GROUP_CONCAT(tagids.id ORDER BY tx_tagids.ordering ASC SEPARATOR ",") FROM (#__judownload_tags AS tagids JOIN #__judownload_tags_xref AS tx_tagids ON tagids.id = tx_tagids.tag_id) WHERE d.id = tx_tagids.doc_id GROUP BY d.id), "") AS tag_ids');
				
				$query->select('IFNULL ((SELECT GROUP_CONCAT(tagtitles.title ORDER BY tx_tagtitles.ordering ASC SEPARATOR "|||") FROM (#__judownload_tags AS tagtitles JOIN #__judownload_tags_xref AS tx_tagtitles ON tagtitles.id = tx_tagtitles.tag_id) WHERE d.id = tx_tagtitles.doc_id GROUP BY d.id), "") AS tag_titles');
			}

			
			$app         = JFactory::getApplication();
			$accessLevel = implode(',', $user->getAuthorisedViewLevels());
			$db          = JFactory::getDbo();
			$date        = JFactory::getDate();
			$nullDate    = $db->quote($db->getNullDate());
			$nowDate     = $db->quote($date->toSql());

			
			$fieldQuery = $db->getQuery(true);
			$fieldQuery->select('field.id');
			$fieldQuery->from('#__judownload_fields AS field');
			$fieldQuery->where('field.field_name = ""');
			$fieldQuery->where('field.list_view = 1');

			$fieldQuery->where('field.published = 1');
			$fieldQuery->where('field.publish_up <= ' . $nowDate);
			$fieldQuery->where('(field.publish_down = ' . $nullDate . ' OR field.publish_down > ' . $nowDate . ')');

			
			$fieldQuery->where('(field.access IN (' . $accessLevel . ') OR field.who_can_download_can_access = 1)');

			$view = $app->input->get('view', '');
			if ($view == 'category' || $view == 'tree')
			{
				$cat_id   = $app->input->getInt('id', 0);
				$category = JUDownloadHelper::getCategoryById($cat_id);
				if (is_object($category))
				{
					$fieldQuery->where('field.group_id = ' . $category->fieldgroup_id);
				}
			}
			else
			{
				$fieldQuery->join('', '#__judownload_categories AS c ON (field.group_id = c.fieldgroup_id OR field.group_id = 1)');

				if (is_array($categoryIdArrayCanAccess) && count($categoryIdArrayCanAccess) > 0)
				{
					$fieldQuery->where('c.id IN(' . implode(",", $categoryIdArrayCanAccess) . ')');
				}
				else
				{
					$fieldQuery->where('c.id IN("")');
				}
			}

			$fieldQuery->join('', '#__judownload_fields_groups AS field_group ON field.group_id = field_group.id');
			$fieldQuery->where('field_group.published = 1');
			$fieldQuery->where('field_group.access IN (' . $accessLevel . ')');

			$fieldQuery->group('field.id');

			$db->setQuery($fieldQuery);

			
			$fields = $db->loadObjectList();
			foreach ($fields AS $field)
			{
				$query->select('IFNULL (fields_values_' . $field->id . '.value, "") AS field_values_' . $field->id);
				$query->join('LEFT', '#__judownload_fields_values AS fields_values_' . $field->id . ' ON fields_values_' . $field->id . '.doc_id = d.id AND fields_values_' . $field->id . '.field_id = ' . $field->id);
			}
		}
	}
Beispiel #3
0
 public function insertUpdateDocument($data, $isInsert = true)
 {
     $db = JFactory::getDbo();
     $iconDir = JPATH_ROOT . '/' . JUDownloadFrontHelper::getDirectory('document_icon_directory', 'media/com_judownload/images/document/');
     $originalDir = $iconDir . 'original/';
     $newMainCatId = $data['main_cat'];
     $gallery = $data['gallery'];
     $files = $data['files'];
     $fieldsData = $data['fieldsData'];
     $relatedDocs = $data['related_docs'];
     $data = $data['data'];
     $messages = array();
     if (!$isInsert) {
         $docObj = JUDownloadHelper::getDocumentById($data['id']);
         if ($docObj->cat_id != $newMainCatId) {
             $oldFieldGroup = JUDownloadHelper::getCategoryById($docObj->cat_id);
             $newFieldGroup = JUDownloadHelper::getCategoryById($newMainCatId);
             if ($oldFieldGroup->fieldgroup_id != $newFieldGroup->fieldgroup_id) {
                 $query = $db->getQuery(true);
                 $query->select("field.*");
                 $query->from("#__judownload_fields AS field");
                 $query->select("plg.folder");
                 $query->join("", "#__judownload_plugins AS plg ON field.plugin_id = plg.id");
                 $query->join("", "#__judownload_categories AS c ON (c.fieldgroup_id = field.group_id AND field.group_id != 1)");
                 $query->join("", "#__judownload_documents_xref AS dxref ON (dxref.cat_id = c.id AND dxref.main = 1)");
                 $query->join("", "#__judownload_documents AS d ON dxref.doc_id = d.id");
                 $query->where("d.id = " . $data['id']);
                 $query->group('field.id');
                 $query->order('field.ordering');
                 $db->setQuery($query);
                 $fields = $db->loadObjectList();
                 foreach ($fields as $field) {
                     $fieldObj = JUDownloadFrontHelperField::getField($field, $data['id']);
                     $fieldObj->onDelete();
                 }
             }
         }
     }
     $iconPath = '';
     $iconFieldId = $this->field_name_id_array['icon'];
     if (!empty($data['icon'])) {
         $iconPath = $data['icon'];
         unset($data['icon']);
     }
     if (!empty($fieldsData[$iconFieldId])) {
         $iconPath = $fieldsData[$iconFieldId];
         unset($fieldsData[$iconFieldId]);
     }
     $table = JTable::getInstance("Document", "JUDownloadTable");
     if (!$table->bind($data) || !$table->check() || !$table->store()) {
         return array('doc_id' => 0, 'messages' => $table->getErrors());
     }
     $docId = $table->id;
     $categoriesField = new JUDownloadFieldCore_categories(null, $docId);
     $categoriesField->is_new_doc = $isInsert;
     $result = $categoriesField->storeValue($fieldsData[$this->field_name_id_array['cat_id']]);
     if (!$result) {
         $table->delete($docId);
         return array('doc_id' => 0, 'messages' => $db->getErrorMsg());
     }
     $query = $db->getQuery(true);
     $query->select("field.*");
     $query->from("#__judownload_fields AS field");
     $query->select("plg.folder");
     $query->join("", "#__judownload_plugins AS plg ON field.plugin_id = plg.id");
     $query->join("", "#__judownload_categories AS c ON (c.fieldgroup_id = field.group_id OR field.group_id = 1)");
     $query->join("", "#__judownload_documents_xref AS dxref ON (dxref.cat_id = c.id AND dxref.main = 1)");
     $query->join("", "#__judownload_documents AS d ON dxref.doc_id = d.id");
     $query->where("d.id = {$docId}");
     $query->where("field.field_name != 'id'");
     $query->where("field.field_name != 'cat_id'");
     $query->group('field.id');
     $query->order('ordering ASC');
     $db->setQuery($query);
     $fields = $db->loadObjectList();
     $docObj = JUDownloadHelper::getDocumentById($docId);
     foreach ($fields as $field) {
         if (isset($fieldsData[$field->id])) {
             $fieldObj = JUDownloadFrontHelperField::getField($field, $docObj);
             $fieldObj->fields_data = $fieldsData;
             $fieldValue = $fieldsData[$field->id];
             $fieldObj->is_new_doc = $isInsert;
             $fieldValue = $fieldObj->onImportDocument($fieldValue);
             $fieldObj->storeValue($fieldValue);
         }
     }
     if ($iconPath) {
         $iconPath = JUDownloadHelper::getPhysicalPath($iconPath);
         if (!$iconPath) {
             $messages[] = JText::sprintf('COM_JUDOWNLOAD_CSV_PROCESS_FILE_S_NOT_FOUND', $iconPath);
         } else {
             if ($data['id'] > 0) {
                 if ($table->icon) {
                     if (JFile::exists($iconDir . $table->icon)) {
                         JFile::delete($iconDir . $table->icon);
                         JFile::delete($originalDir . $table->icon);
                     }
                 }
             }
             $iconName = basename($iconPath);
             $iconName = $docId . "_" . JUDownloadHelper::fileNameFilter($iconName);
             if (JFile::copy($iconPath, $originalDir . $iconName) && JUDownloadHelper::renderImages($originalDir . $iconName, $iconDir . $iconName, 'document_icon', true, null, $data['id'])) {
                 $table->icon = $iconName;
                 $table->store();
             }
         }
     }
     $imageTable = JTable::getInstance("Image", "JUDownloadTable");
     if (!empty($gallery)) {
         $dir_document_ori = JPATH_SITE . "/" . JUDownloadFrontHelper::getDirectory("document_original_image_directory", "media/com_judownload/images/gallery/original/") . $docId . "/";
         $dir_document_small = JPATH_SITE . "/" . JUDownloadFrontHelper::getDirectory("document_small_image_directory", "media/com_judownload/images/gallery/small/") . $docId . "/";
         $dir_document_big = JPATH_SITE . "/" . JUDownloadFrontHelper::getDirectory("document_big_image_directory", "media/com_judownload/images/gallery/big/") . $docId . "/";
         if (!JFolder::exists($dir_document_ori)) {
             $file_index = $dir_document_ori . 'index.html';
             $buffer = "<!DOCTYPE html><title></title>";
             JFile::write($file_index, $buffer);
         }
         if (!JFolder::exists($dir_document_small)) {
             $file_index = $dir_document_small . 'index.html';
             $buffer = "<!DOCTYPE html><title></title>";
             JFile::write($file_index, $buffer);
         }
         if (!JFolder::exists($dir_document_big)) {
             $file_index = $dir_document_big . 'index.html';
             $buffer = "<!DOCTYPE html><title></title>";
             JFile::write($file_index, $buffer);
         }
         $image_ordering = 1;
         $date = JFactory::getDate();
         foreach ($gallery as $imagePath) {
             $imagePath = JUDownloadHelper::getPhysicalPath($imagePath);
             if (!$imagePath) {
                 $messages[] = JText::sprintf('COM_JUDOWNLOAD_CSV_PROCESS_FILE_S_NOT_FOUND', $imagePath);
                 continue;
             }
             $imageName = basename($imagePath);
             $imageName = JUDownloadHelper::generateImageNameByDocument($docId, $imageName);
             if (JFile::copy($imagePath, $dir_document_ori . $imageName) && JUDownloadHelper::renderImages($dir_document_ori . $imageName, $dir_document_small . $imageName, 'document_small', true, null, $data['id']) && JUDownloadHelper::renderImages($dir_document_ori . $imageName, $dir_document_big . $imageName, 'document_big', true, null, $data['id'])) {
                 $imageObj = new stdClass();
                 $imageObj->id = 0;
                 $imageObj->file_name = $imageName;
                 $imageObj->doc_id = $docId;
                 $imageObj->ordering = $image_ordering;
                 $imageObj->created = $date->toSql();
                 $imageObj->published = 1;
                 if (!$imageTable->bind($imageObj) || !$imageTable->check() || !$imageTable->store()) {
                     $messages[] = implode(' | ', $imageTable->getErrors());
                     JFile::delete($dir_document_ori . $imageName);
                     JFile::delete($dir_document_small . $imageName);
                     JFile::delete($dir_document_big . $imageName);
                 } else {
                     $image_ordering++;
                 }
             } else {
                 $messages[] = JText::sprintf('COM_JUDOWNLOAD_CSV_PROCESS_CAN_NOT_COPY_FILE_FROM_S_TO_S', $imagePath, $dir_document_ori . $imageName);
             }
         }
     }
     $fileTable = JTable::getInstance("File", "JUDownloadTable");
     if (!empty($files)) {
         $file_directory = JPATH_SITE . "/" . JUDownloadFrontHelper::getDirectory("file_directory", "media/com_judownload/files/");
         if (!JFolder::exists($file_directory . $docId . "/")) {
             $file_index = $file_directory . $docId . "/index.html";
             $buffer = "<!DOCTYPE html><title></title>";
             JFile::write($file_index, $buffer);
         }
         $file_ordering = 1;
         foreach ($files as $filePath) {
             $filePath = JUDownloadHelper::getPhysicalPath($filePath);
             if (!$filePath) {
                 $messages[] = JText::sprintf('COM_JUDOWNLOAD_CSV_PROCESS_FILE_S_NOT_FOUND', $filePath);
                 continue;
             }
             $query = $db->getQuery(true);
             $query->select('COUNT(*)')->from('#__judownload_files')->where('doc_id = ' . $docId)->where('`rename` = ' . $db->quote(basename($filePath)));
             $db->setQuery($query);
             $count = $db->loadResult();
             if ($count) {
                 $messages[] = JText::sprintf('COM_JUDOWNLOAD_CSV_PROCESS_EXISTED_FILE_S', $filePath);
                 continue;
             }
             $fileObject = array();
             $fileObject['id'] = 0;
             $fileObject['doc_id'] = $docId;
             $fileObject['ordering'] = $file_ordering;
             $fileObject['rename'] = basename($filePath);
             $fileObject['file_name'] = md5($fileObject['rename'] . JUDownloadHelper::generateRandomString(10)) . "." . JFile::getExt($fileObject['rename']);
             $fileObject['published'] = 1;
             $this->addFileInfo($fileObject, $filePath, $file_directory);
             $dest = $file_directory . $docId . "/" . $fileObject['file_name'];
             if ($fileTable->bind($fileObject) && $fileTable->check() && $fileTable->store()) {
                 if (!JFile::copy($filePath, $dest)) {
                     $fileTable->delete($fileTable->id);
                     $messages[] = JText::sprintf('COM_JUDOWNLOAD_CSV_PROCESS_CAN_NOT_COPY_FILE_FROM_S_TO_S', $filePath, $dest);
                 }
                 $file_ordering++;
             } else {
                 $messages[] = implode(' | ', $fileTable->getErrors());
             }
         }
     }
     if (!empty($relatedDocs)) {
         $ordering = 1;
         foreach ($relatedDocs as $relatedDocId) {
             $document = JUDownloadHelper::getDocumentById($relatedDocId);
             if ($document) {
                 $relatedDocObj = new stdClass();
                 $relatedDocObj->id = 0;
                 $relatedDocObj->doc_id = $docId;
                 $relatedDocObj->doc_id_related = $relatedDocId;
                 $relatedDocObj->ordering = $ordering;
                 $query = $db->getQuery(true);
                 $query->select('id')->from('#__judownload_documents_relations')->where('doc_id = ' . $docId)->where('doc_id_related = ' . $relatedDocId);
                 $db->setQuery($query);
                 $existedId = $db->loadResult();
                 if ($existedId) {
                     $relatedDocObj->id = $existedId;
                     $db->updateObject('#__judownload_documents_relations', $relatedDocObj, 'id');
                 } else {
                     $db->insertObject('#__judownload_documents_relations', $relatedDocObj);
                 }
                 $relationId = $db->insertid();
                 if ($relationId > 0) {
                     $ordering++;
                 } else {
                     $messages[] = $db->getErrorMsg();
                 }
             } else {
                 $messages[] = JText::sprintf('COM_JUDOWNLOAD_CSV_PROCESS_INVALID_RELATED_DOCUMENT_N', $relatedDocId);
             }
         }
     }
     return array('doc_id' => $docId, 'messages' => $messages);
 }
Beispiel #4
0
 public function save($key = null, $urlVar = null)
 {
     JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));
     $app = JFactory::getApplication();
     $lang = JFactory::getLanguage();
     $model = $this->getModel();
     $table = $model->getTable();
     $checkin = property_exists($table, 'checked_out');
     $context = "{$this->option}.edit.{$this->context}";
     $task = $this->getTask();
     $data = $app->input->post->get('jform', array(), 'array');
     $fieldsData = $app->input->post->get('fields', array(), 'array');
     $files = array_values($app->input->post->get("judlfiles", array(), 'array'));
     $changelogs = array_values($app->input->post->get("changelogs", array(), 'array'));
     $versions = $app->input->post->get("versions", array(), 'array');
     $related_documents = array_values($app->input->post->get("related_documents", array(), 'array'));
     if (empty($key)) {
         $key = $table->getKeyName();
     }
     if (empty($urlVar)) {
         $urlVar = $key;
     }
     $recordId = $app->input->getInt($urlVar, 0);
     if (!$this->checkEditId($context, $recordId)) {
         $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $recordId));
         $this->setMessage($this->getError(), 'error');
         $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $this->getRedirectToListAppend(), false));
         return false;
     }
     $data[$key] = $recordId;
     if ($task == 'save2copy') {
         if ($checkin && $model->checkin($data[$key]) === false) {
             $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()));
             $this->setMessage($this->getError(), 'error');
             $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($recordId, $urlVar), false));
             return false;
         }
         $docArr = array($data[$key]);
         $currentDocumentObject = JUDownloadHelper::getDocumentById($data[$key]);
         $catArr = array($currentDocumentObject->cat_id);
         $copyOptionsArr = array('copy_downloads', 'copy_rates', 'copy_hits', 'copy_permission', 'copy_extra_fields', 'copy_files', 'copy_changelogs', 'copy_related_documents', 'copy_comments', 'copy_reports', 'copy_subscriptions', 'copy_logs');
         $documentCopyMappedId = $model->copyAndMap($docArr, $catArr, $copyOptionsArr, $files, $versions, 'save2copy', $fieldsData);
         $data[$key] = $documentCopyMappedId;
         $save2copy = true;
         $task = 'apply';
     }
     if (!$this->allowSave($data, $key)) {
         $this->setError(JText::_('JLIB_APPLICATION_ERROR_SAVE_NOT_PERMITTED'));
         $this->setMessage($this->getError(), 'error');
         $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $this->getRedirectToListAppend(), false));
         return false;
     }
     $form = $model->getForm($data, false);
     if (!$form) {
         $app->enqueueMessage($model->getError(), 'error');
         return false;
     }
     $validData = $model->validate($form, $data);
     $validFieldsData = $model->validateFields($fieldsData, $data[$key]);
     $validFiles = $model->validateFiles($files, $data[$key]);
     if ($validData === false || $validFieldsData === false || $validFiles === false) {
         $errors = $model->getErrors();
         for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
             if ($errors[$i] instanceof Exception) {
                 $app->enqueueMessage($errors[$i]->getMessage(), 'warning');
             } else {
                 $app->enqueueMessage($errors[$i], 'warning');
             }
         }
         $app->setUserState($context . '.data', $data);
         $app->setUserState($context . '.fieldsdata', $fieldsData);
         $app->setUserState($context . '.files', $files);
         $app->setUserState($context . '.changelogs', $changelogs);
         $app->setUserState($context . '.versions', $versions);
         $app->setUserState($context . '.related_documents', $related_documents);
         if (isset($save2copy) && $save2copy) {
             $model->delete($data[$key]);
         }
         $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($recordId, $urlVar), false));
         return false;
     }
     $data['data'] = $validData;
     $data['data'][$key] = $data[$key];
     $data['fieldsData'] = $validFieldsData;
     $data['files'] = $validFiles;
     $data['changelogs'] = $changelogs;
     $data['versions'] = $versions;
     $data['related_documents'] = $related_documents;
     $categoriesField = new JUDownloadFieldCore_categories();
     if ($model->getDocumentSubmitType($data['data'][$key]) == 'submit' && !$categoriesField->canSubmit() || $model->getDocumentSubmitType($data['data'][$key]) == 'edit' && !$categoriesField->canEdit()) {
         $documentObjectDb = JUDownloadHelper::getDocumentById($data['data'][$key]);
         if ($documentObjectDb) {
             $data['fieldsData'][$categoriesField->id]['main'] = $documentObjectDb->cat_id;
         } else {
             $this->setError(JText::_('COM_JUDOWNLOAD_INVALID_DOCUMENT'));
             $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($recordId, $urlVar), false));
             return false;
         }
     }
     if (!$model->save($data)) {
         $app->setUserState($context . '.data', $validData);
         $app->setUserState($context . '.fieldsdata', $validFieldsData);
         $app->setUserState($context . '.changelogs', $changelogs);
         $app->setUserState($context . '.versions', $versions);
         $app->setUserState($context . '.files', $files);
         $app->setUserState($context . '.related_documents', $related_documents);
         $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
         $this->setMessage($this->getError(), 'error');
         $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($recordId, $urlVar), false));
         return false;
     }
     if ($table->load($recordId)) {
         if ($table->id > 0) {
             if ($checkin && $model->checkin($recordId) === false) {
                 $app->setUserState($context . '.data', $validData);
                 $app->setUserState($context . '.fieldsdata', $validFieldsData);
                 $app->setUserState($context . '.files', $files);
                 $app->setUserState($context . '.changelogs', $changelogs);
                 $app->setUserState($context . '.versions', $versions);
                 $app->setUserState($context . '.related_documents', $related_documents);
                 $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()));
                 $this->setMessage($this->getError(), 'error');
                 $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($recordId, $urlVar), false));
                 return false;
             }
         }
     }
     $this->setMessage(JText::_(($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS') ? $this->text_prefix : 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'));
     switch ($task) {
         case 'apply':
             $recordId = $model->getState($this->context . '.id');
             $this->holdEditId($context, $recordId);
             $app->setUserState($context . '.data', null);
             $app->setUserState($context . '.fieldsdata', null);
             $app->setUserState($context . '.files', null);
             $app->setUserState($context . '.changelogs', null);
             $app->setUserState($context . '.versions', null);
             $app->setUserState($context . '.related_documents', null);
             $model->checkout($recordId);
             $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend($recordId, $urlVar), false));
             break;
         case 'save2new':
             $this->releaseEditId($context, $recordId);
             $app->setUserState($context . '.data', null);
             $app->setUserState($context . '.fieldsdata', null);
             $app->setUserState($context . '.files', null);
             $app->setUserState($context . '.changelogs', null);
             $app->setUserState($context . '.versions', null);
             $app->setUserState($context . '.related_documents', null);
             $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_item . $this->getRedirectToItemAppend(null, $urlVar), false));
             break;
         default:
             $this->releaseEditId($context, $recordId);
             $app->setUserState($context . '.data', null);
             $app->setUserState($context . '.fieldsdata', null);
             $app->setUserState($context . '.files', null);
             $app->setUserState($context . '.changelogs', null);
             $app->setUserState($context . '.versions', null);
             $app->setUserState($context . '.related_documents', null);
             $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $this->getRedirectToListAppend(), false));
             break;
     }
     $this->postSaveHook($model, $validData);
     return true;
 }