function approve($comment_ids)
 {
     if (!is_array($comment_ids) || empty($comment_ids)) {
         $this->setError('COM_JUDOWNLOAD_NO_ITEM_SELECTED');
         return false;
     }
     JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_judownload/tables');
     $comment_table = JTable::getInstance("Comment", "JUDownloadTable");
     $count = 0;
     $comment_ids = (array) $comment_ids;
     $rootComment = JUDownloadFrontHelperComment::getRootComment();
     $docIds = array();
     foreach ($comment_ids as $comment_id) {
         $comment_table->reset();
         if ($comment_table->load($comment_id) && $comment_table->parent_id == $rootComment->id && $comment_table->approved == 0) {
             $docIds[$comment_table->doc_id] = $comment_table->doc_id;
         }
         $user = JFactory::getUser();
         $date = JFactory::getDate();
         $comment_table->approved = 1;
         $comment_table->published = 1;
         $comment_table->approved_by = $user->id;
         $comment_table->approved_time = $date->toSql();
         $comment_table->store();
         $count++;
         JUDownloadFrontHelperMail::sendEmailByEvent('comment.approve', $comment_id);
         $logData = array('user_id' => $comment_table->user_id, 'event' => 'comment.approve', 'item_id' => $comment_id, 'doc_id' => $comment_table->doc_id, 'value' => 0, 'reference' => '');
         JUDownloadFrontHelperLog::addLog($logData);
     }
     foreach ($docIds as $docId) {
         JUDownloadHelper::rebuildRating($docId);
     }
     return $count;
 }
Example #2
0
 public function saveDocumentAddLog($table, $isNew)
 {
     $app = JFactory::getApplication();
     if ($app->isSite()) {
         $user = JFactory::getUser();
         if ($isNew) {
             $logData = array('user_id' => $user->id, 'event' => 'document.create', 'item_id' => $table->id, 'doc_id' => $table->id, 'value' => 0, 'reference' => '');
         } else {
             $logData = array('user_id' => $user->id, 'event' => 'document.edit', 'item_id' => $table->id, 'doc_id' => $table->id, 'value' => 0, 'reference' => '');
         }
         JUDownloadFrontHelperLog::addLog($logData);
     }
 }
Example #3
0
 public function save($data)
 {
     $dispatcher = JDispatcher::getInstance();
     $table = $this->getTable();
     $pk = !empty($data['id']) ? $data['id'] : (int) $this->getState($this->getName() . '.id');
     $isNew = true;
     $app = JFactory::getApplication();
     JPluginHelper::importPlugin('content');
     if ($pk > 0) {
         $table->load($pk);
         $isNew = false;
     }
     if ($table->parent_id != $data['parent_id'] || $data['id'] == 0) {
         $table->setLocation($data['parent_id'], 'last-child');
     }
     if (!$table->bind($data)) {
         $this->setError($table->getError());
         return false;
     }
     if (isset($data['rules'])) {
         $rules = new JAccessRules($data['rules']);
         $table->setRules($rules);
     }
     $this->prepareTable($table);
     if (!$table->check()) {
         $this->setError($table->getError());
         return false;
     }
     $result = $dispatcher->trigger($this->event_before_save, array($this->option . '.' . $this->name, &$table, $isNew));
     if (in_array(false, $result, true)) {
         $this->setError($table->getError());
         return false;
     }
     if (!$table->store()) {
         $this->setError($table->getError());
         return false;
     }
     $dispatcher->trigger($this->event_after_save, array($this->option . '.' . $this->name, &$table, $isNew));
     $this->setState($this->getName() . '.id', $table->id);
     $this->cleanCache();
     if (!$isNew && $app->isSite()) {
         $user = JFactory::getUser();
         $logData = array('user_id' => $user->id, 'event' => 'comment.edit', 'item_id' => $table->id, 'doc_id' => $table->doc_id, 'value' => 0, 'reference' => '');
         JUDownloadFrontHelperLog::addLog($logData);
     }
     return $table->id;
 }
Example #4
0
	public function voteComment($commentId)
	{
		$commentObj = JUDownloadFrontHelperComment::getCommentObject($commentId);
		if (!$commentObj)
		{
			return;
		}

		$vote_up = JFactory::getApplication()->input->getInt('vote_up', 0);

		$helpful_votes = intval($commentObj->helpful_votes);
		$total_votes   = intval($commentObj->total_votes);

		$params                  = JUDownloadHelper::getParams(null, $commentObj->doc_id);
		$allow_vote_down_comment = $params->get('allow_vote_down_comment', 1);

		
		if (!$allow_vote_down_comment)
		{
			$like_system = true;

			
			if ($vote_up != 1)
			{
				$voteType  = 0;
				$reference = 'unlike';
				$total_votes--;
				$helpful_votes--;
			}
			
			else
			{
				$voteType  = 1;
				$reference = 'like';
				$total_votes++;
				$helpful_votes++;
			}
		}
		else
		{
			$like_system = false;

			
			if ($vote_up != 1)
			{
				$voteType  = -1;
				$reference = 'vote_down';
				$total_votes++;
			}
			
			else
			{
				$voteType  = 1;
				$reference = 'vote_up';
				$total_votes++;
				$helpful_votes++;
			}
		}

		$votedValue = $this->getCommentVotedValue($commentObj->id);
		
		if (($allow_vote_down_comment && $votedValue) || ($votedValue == $voteType))
		{
			$return                = array();
			$return['message']     = JText::_('COM_JUDOWNLOAD_VOTING_ERROR');
			$return['like_system'] = $like_system;
			$return['vote_type']   = null;

			JUDownloadHelper::obCleanData();
			echo json_encode($return);
			exit();
		}

		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->update('#__judownload_comments')
			->set('helpful_votes = ' . $helpful_votes)
			->set('total_votes = ' . $total_votes)
			->where('id = ' . $commentObj->id);
		$db->setQuery($query);

		if ($db->execute())
		{
			
			$dispatcher = JDispatcher::getInstance();
			JPluginHelper::importPlugin('judownload');
			$dispatcher->trigger('onVoteComment', $commentObj, $like_system, $voteType);

			$user   = JFactory::getUser();
			$userId = $user->id;

			
			$logData = array(
				'user_id'   => $user->id,
				'event'     => 'comment.vote',
				'item_id'   => $commentObj->id,
				'doc_id'    => $commentObj->doc_id,
				'value'     => $voteType,
				'reference' => $reference
			);

			JUDownloadFrontHelperLog::addLog($logData);

			
			if ($userId > 0)
			{
				$cookieName = 'judl-comment-vote-' . $commentObj->id . '_' . $userId;
			}
			
			else
			{
				$ipAddress  = JUDownloadFrontHelper::getIpAddress();
				$ipAddress  = str_replace('.', '_', $ipAddress);
				$cookieName = 'judl-comment-vote-' . $commentObj->id . '_' . $ipAddress;
			}

			
			$config        = JFactory::getConfig();
			$cookie_domain = $config->get('cookie_domain', '');
			$cookie_path   = $config->get('cookie_path', '/');
			setcookie($cookieName, $voteType, time() + 60 * 60 * 24 * 30, $cookie_path, $cookie_domain);

			$return                = array();
			$return['message']     = JText::sprintf('COM_JUDOWNLOAD_N_HELPFUL_VOTES_N_TOTAL_VOTES', $helpful_votes, $total_votes);
			$return['like_system'] = $like_system;
			$return['vote_type']   = $voteType;
		}
		else
		{
			$return                = array();
			$return['message']     = JText::_('COM_JUDOWNLOAD_VOTING_ERROR');
			$return['like_system'] = $like_system;
			$return['vote_type']   = null;
		}

		JUDownloadHelper::obCleanData();
		echo json_encode($return);
		exit();
	}
Example #5
0
	public function publish()
	{
		
		JSession::checkToken('get') or die(JText::_('JINVALID_TOKEN'));

		
		$cid   = JFactory::getApplication()->input->get('id', array(), 'array');
		$data  = array('publish' => 1, 'unpublish' => 0);
		$task  = $this->getTask();
		$value = JArrayHelper::getValue($data, $task, 0, 'int');

		if (empty($cid))
		{
			JError::raiseWarning(500, JText::_('COM_JUDOWNLOAD_NO_ITEM_SELECTED'));
		}
		else
		{
			
			$model = $this->getModel();

			
			JArrayHelper::toInteger($cid);

			
			if (!$model->publish($cid, $value))
			{
				JError::raiseWarning(500, $model->getError());
			}
			else
			{
				if ($value == 1)
				{
					$ntext = $this->text_prefix . '_N_ITEMS_PUBLISHED';
				}
				elseif ($value == 0)
				{
					$ntext = $this->text_prefix . '_N_ITEMS_UNPUBLISHED';

				}

				foreach ($cid AS $id)
				{
					
					JUDownloadFrontHelperMail::sendEmailByEvent('document.editstate', $id);
				}

				$this->setMessage(JText::plural($ntext, count($cid)));

				
				$user = JFactory::getUser();
				foreach ($cid AS $id)
				{
					$logData = array(
						'user_id'   => $user->id,
						'event'     => 'document.editstate',
						'item_id'   => $id,
						'doc_id'    => $id,
						'value'     => $value,
						'reference' => '',
					);

					JUDownloadFrontHelperLog::addLog($logData);
				}
			}
		}

		$this->setRedirect(JRoute::_($this->getReturnPage()));
	}
Example #6
0
	public function updateComment()
	{
		
		JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));

		
		$user  = JFactory::getUser();
		$model = $this->getModel();

		
		$app            = JFactory::getApplication();
		$data           = $app->input->getArray($_POST);
		$documentId     = $data['doc_id'];
		$commentId      = $data['comment_id'];
		$canEditComment = JUDownloadFrontHelperPermission::canEditComment($commentId);
		$redirectUrl    = JRoute::_(JUDownloadHelperRoute::getDocumentRoute($documentId) . '#comment-item-' . $commentId);

		if (!$canEditComment)
		{
			$this->setMessage(JText::_('COM_JUDOWNLOAD_UPDATE_COMMENT_ERROR'));
			$this->setRedirect($redirectUrl);

			return false;
		}
		$params = JUDownloadHelper::getParams(null, $documentId);

		
		$ratingValue = $this->validateCriteria($data);
		if ($ratingValue)
		{
			$data = array_merge($data, $ratingValue);
		}
		else
		{
			$this->setMessage(JText::_('COM_JUDOWNLOAD_UPDATE_COMMENT_ERROR'));
			$this->setRedirect($redirectUrl);

			return false;
		}

		JUDownloadHelper::obCleanData();
		if ($model->updateComment($data, $params))
		{
			
			$logData = array(
				'user_id'   => $user->id,
				'event'     => 'comment.edit',
				'item_id'   => $commentId,
				'doc_id'    => $documentId,
				'value'     => 0,
				'reference' => '',
			);
			JUDownloadFrontHelperLog::addLog($logData);
			$this->setMessage(JText::_('COM_JUDOWNLOAD_UPDATE_COMMENT_SUCCESSFULLY'));
			$this->setRedirect($redirectUrl);

			return true;
		}
		else
		{
			$this->setMessage(JText::_('COM_JUDOWNLOAD_UPDATE_COMMENT_ERROR'));
			$this->setRedirect($redirectUrl);

			return false;
		}
	}
Example #7
0
	public function createDownloadPackage($type, $itemIdArray, $parentId, $version)
	{
		$app = JFactory::getApplication();
		// If set no_counting_download_time, storeId will be used to check if download file in "no counting download" period
		sort($itemIdArray);
		$storeId = md5($type . serialize($itemIdArray) . $version);

		if ($type == 'document')
		{
			$params = JUDownloadHelper::getParams($parentId);
		}
		else
		{
			$params = JUDownloadHelper::getParams(null, $parentId);
		}

		$noCountingDownloadSecond = (int) $params->get('no_counting_download_time', 300);
		if ($noCountingDownloadSecond > 0)
		{
			$storeIdArray = (array) $app->getUserState('com_judownload.download.storeid');
		}
		else
		{
			$storeIdArray = array();
		}

		$user = JFactory::getUser();

		$downloadZippedFileMode      = $params->get('download_zipped_file_mode', 'temp');
		$downloadOneFileNoZippedMode = $params->get('download_one_file_no_zipped_mode', 'temp');

		// Min download speed.
		$minDownloadSpeed = (int) $params->get('min_download_speed', 10);
		$minDownloadSpeed = $minDownloadSpeed > 0 ? $minDownloadSpeed : 10;
		$minDownloadSpeed = $minDownloadSpeed * 1024; //KBps

		// Min live time of download package.
		$adjustFileLiveTime = (int) $params->get('adjust_file_live_time', 60);
		$adjustFileLiveTime = $adjustFileLiveTime >= 0 ? $adjustFileLiveTime : 60;

		// Time download package created.
		$createdTimeDate  = JFactory::getDate()->toSql();
		$createdTimeStamp = strtotime($createdTimeDate);

		// Trigger JU Download after download
		$dispatcher = JDispatcher::getInstance();
		JPluginHelper::importPlugin('judownload');

		// Physical file path to download, to be used in temp folder mode
		$downloadFilePath = '';

		// True if file is zipped by zip class
		$zipFile = false;

		// Get comment for zip package.
		$zipCommentConfig = $params->get('zip_comment', '');

		// Zip comment parsed from $zipCommentConfig case by case
		$zipComment = '';

		if ($type == 'document')
		{
			// Get category id.
			$categoryId      = $parentId;
			$documentIdArray = $itemIdArray;
			// Download multi documents in the same cat
			if (count($documentIdArray) > 1)
			{
				// In this case : user downloading category.
				// Sort array document id.
				sort($documentIdArray);

				// Create zip package.
				$zip     = new Zip();
				$zipFile = true;

				// Parse zip comment
				$zipComment = $this->parseCommentTxt($zipCommentConfig, $categoryId);

				// File id array in all download documents to reference in tmp file table
				$fileIdArrayInTmpZip = array();
				foreach ($documentIdArray AS $documentId)
				{
					$documentObject = JUDownloadHelper::getDocumentById($documentId);
					$documentTitle  = $this->filterFileFolderName($documentObject->title);
					$documentTitle  = trim($documentTitle);
					$fileObjectList = $this->getAllFilesOfDocument($documentId);
					// If document has file, add document title as a folder contains files
					if (count($fileObjectList))
					{
						$zip->addDirectory($documentTitle);
					}

					// File id array in document to log document.download
					$fileIdArray  = array();
					$documentSize = 0;
					foreach ($fileObjectList AS $fileObject)
					{
						$physicalFilePath = $this->getPhysicalFilePath($fileObject->id);

						if (JFile::exists($physicalFilePath))
						{
							$filePathInZip = $documentTitle . '/' . $this->filterFileFolderName($fileObject->rename);

							// Add file extension to file path, if the extension is not the same original file
							$fileExtOri   = JFile::getExt($physicalFilePath);
							$fileExtInZip = JFile::getExt($filePathInZip);
							if ($fileExtInZip != $fileExtOri)
							{
								$filePathInZip = $filePathInZip . '.' . $fileExtOri;
							}
							$filePathInZip = trim($filePathInZip);

							$zip->addLargeFile($physicalFilePath, $filePathInZip);
							$documentSize += $fileObject->size;
							if (!in_array($storeId, $storeIdArray))
							{
								$this->updateFileDownloadCounter($fileObject->id);
							}
						}
						$fileIdArray[]         = $fileObject->id;
						$fileIdArrayInTmpZip[] = $fileObject->id;
					}

					if (!in_array($storeId, $storeIdArray))
					{
						$this->updateDocumentDownloadCounter($documentId);

						$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $documentSize));

						// Add log when download
						$logData = array(
							'user_id'   => $user->id,
							'event'     => 'document.download',
							'item_id'   => $documentId,
							'doc_id'    => $documentId,
							'value'     => $documentSize,
							'reference' => implode(',', $fileIdArray)
						);

						JUDownloadFrontHelperLog::addLog($logData);
					}
				}
				// End - Zip file

				$categoryObject = JUDownloadHelper::getCategoryById($categoryId);
				$zipFileName    = $this->makeSafeFileName($categoryObject->title) . ".zip";
			}
			//Download one document
			else
			{
				/*
				 * Download document when not isset cat_id
				 * Download document we only get first element of documentIds array
				 */
				$documentId     = $documentIdArray[0];
				$documentObject = JUDownloadHelper::getDocumentById($documentId);

				$documentTitle  = $this->filterFileFolderName($documentObject->title);
				$fileObjectList = $this->getAllFilesOfDocument($documentId);

				// Zip file even document has only one file, we can change this later here...
				// Create zip download package.
				$zip     = new Zip();
				$zipFile = true;

				// Parse zip comment
				$zipComment = $this->parseCommentTxt($zipCommentConfig, $categoryId, $documentId);

				$documentTitle = trim($documentTitle);
				//Add document title as a folder contains files
				$zip->addDirectory($documentTitle);

				$fileIdArray  = array();
				$documentSize = 0;
				foreach ($fileObjectList AS $fileObject)
				{
					// One document allow to download by version
					$physicalFilePath = $this->getPhysicalFilePath($fileObject->id, $version);

					if (JFile::exists($physicalFilePath))
					{
						$filePathInZip = $documentTitle . '/' . $this->filterFileFolderName($fileObject->rename);

						// Add file extension to file path, if the extension is not the same original file
						$fileExtOri   = JFile::getExt($physicalFilePath);
						$fileExtInZip = JFile::getExt($filePathInZip);
						if ($fileExtInZip != $fileExtOri)
						{
							$filePathInZip = $filePathInZip . '.' . $fileExtOri;
						}
						$filePathInZip = trim($filePathInZip);

						$zip->addLargeFile($physicalFilePath, $filePathInZip);
						$documentSize += $fileObject->size;
						if (!in_array($storeId, $storeIdArray))
						{
							$this->updateFileDownloadCounter($fileObject->id, $version);
						}
					}
					$fileIdArray[] = $fileObject->id;
				}
				// End - Zip file

				if (!in_array($storeId, $storeIdArray))
				{
					$this->updateDocumentDownloadCounter($documentId);

					$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $documentSize));

					// Add log
					$logData = array(
						'user_id'   => $user->id,
						'event'     => 'document.download',
						'item_id'   => $documentId,
						'doc_id'    => $documentId,
						'value'     => $documentSize,
						'reference' => implode(',', $fileIdArray) . ($version ? ':' . $version : '')
					);

					JUDownloadFrontHelperLog::addLog($logData);
				}

				$zipFileName = $this->makeSafeFileName($documentObject->title . " " . $version) . ".zip";
			}
		}
		elseif ($type == 'file')
		{
			$fileIdArray = $itemIdArray;
			$documentId  = $parentId;
			//Download multi files in one document
			if (count($fileIdArray) > 1)
			{
				$documentObject = JUDownloadHelper::getDocumentById($documentId);

				$documentTitle  = $this->filterFileFolderName($documentObject->title);
				$mainCategoryId = JUDownloadFrontHelperCategory::getMainCategoryId($documentId);

				$zip     = new Zip();
				$zipFile = true;

				// Parse zip comment
				$zipComment = $this->parseCommentTxt($zipCommentConfig, $mainCategoryId, $documentId);

				$documentTitle = trim($documentTitle);
				$zip->addDirectory($documentTitle);

				$documentSize = 0;
				foreach ($fileIdArray AS $fileId)
				{
					// One document allow to download by version
					$physicalFilePath = $this->getPhysicalFilePath($fileId, $version);

					if (JFile::exists($physicalFilePath))
					{
						$fileObject    = $this->getFileObject($fileId);
						$filePathInZip = $documentTitle . '/' . $this->filterFileFolderName($fileObject->rename);

						// Add file extension to file path, if the extension is not the same original file
						$fileExtOri   = JFile::getExt($physicalFilePath);
						$fileExtInZip = JFile::getExt($filePathInZip);
						if ($fileExtInZip != $fileExtOri)
						{
							$filePathInZip = $filePathInZip . '.' . $fileExtOri;
						}
						$filePathInZip = trim($filePathInZip);

						$zip->addLargeFile($physicalFilePath, $filePathInZip);
						$documentSize += $fileObject->size;
						if (!in_array($storeId, $storeIdArray))
						{
							$this->updateFileDownloadCounter($fileId, $version);
						}
					}
				}
				// End - Zip file

				// Sort $fileIdArrayInTmpZip before add log and store it to tmp files table
				sort($fileIdArray);

				if (!in_array($storeId, $storeIdArray))
				{
					$this->updateDocumentDownloadCounter($documentId);

					$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $documentSize));

					// Add log
					$logData = array(
						'user_id'   => $user->id,
						'event'     => 'document.download',
						'item_id'   => $documentId,
						'doc_id'    => $documentId,
						'value'     => $documentSize,
						'reference' => implode(',', $fileIdArray) . ($version ? ':' . $version : '')
					);

					JUDownloadFrontHelperLog::addLog($logData);
				}

				$zipFileName = $this->makeSafeFileName($documentObject->title . " " . $version) . ".zip";
			}
			//Download one file
			elseif (count($fileIdArray) == 1)
			{
				$zipOneFile = $params->get('zip_one_file', 0);

				$fileId     = $itemIdArray[0];
				$fileObject = $this->getFileObject($fileId);

				// One file allow to download by version
				$physicalFilePath = $this->getPhysicalFilePath($fileId, $version);
				$physicalFilePath = JPath::clean($physicalFilePath);

				$fileExtOri = JFile::getExt($physicalFilePath);

				$configAllowZipFile = $params->get('allow_zip_file', 1);

				// Download one file no zipped (File can be zip file or not, but we still using var $zipFileName for general download file name)
				if ($fileExtOri == "zip" || !$zipOneFile || !$configAllowZipFile)
				{
					$zipFile = false;

					// In this case, $zipFileName is file name(zipped or not)
					$zipFileName = $this->filterFileFolderName($fileObject->rename);
					$zipFileName = $this->makeSafeFileName(JFile::stripExt($zipFileName) . " " . $version) . "." . JFile::getExt($zipFileName);
					// Add file extension to file path, if the extension is not the same original file
					$fileExtInZip = JFile::getExt($zipFileName);
					if ($fileExtInZip != $fileExtOri)
					{
						$zipFileName = $zipFileName . '.' . $fileExtOri;
					}
					$zipFileName = trim($zipFileName);
				}
				// Download one file zipped
				else
				{
					// Initialize zip object.
					$zip     = new Zip();
					$zipFile = true;

					$mainCategoryId = JUDownloadFrontHelperCategory::getMainCategoryId($documentId);
					// Parse zip comment
					$zipComment = $this->parseCommentTxt($zipCommentConfig, $mainCategoryId, $documentId);

					if (JFile::exists($physicalFilePath))
					{
						$filePathInZip = $this->filterFileFolderName($fileObject->rename);

						// Add file extension to file path, if the extension is not the same original file
						$fileExtInZip = JFile::getExt($filePathInZip);
						if ($fileExtInZip != $fileExtOri)
						{
							$filePathInZip = $filePathInZip . '.' . $fileExtOri;
						}
						$filePathInZip = trim($filePathInZip);

						$zip->addLargeFile($physicalFilePath, $filePathInZip);
					}
					// End - Zip file

					$zipFileName = $this->filterFileFolderName($fileObject->rename);
					$zipFileName = $this->makeSafeFileName(JFile::stripExt($zipFileName) . " " . $version) . ".zip";
					$zipFileName = trim($zipFileName);
				}

				if (!in_array($storeId, $storeIdArray))
				{
					$this->updateDocumentDownloadCounter($documentId, $version);
					$this->updateFileDownloadCounter($fileId, $version);

					$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $fileObject->size));

					// Add log
					$logData = array(
						'user_id'   => $user->id,
						'event'     => 'document.download',
						'item_id'   => $documentId,
						'doc_id'    => $documentId,
						'value'     => $fileObject->size,
						'reference' => $fileId . ($version ? ':' . $version : '')
					);

					JUDownloadFrontHelperLog::addLog($logData);
				}
			}
		}
		// Only support download file/document, invalid type -> return false
		else
		{
			return false;
		}

		$serverTime      = JFactory::getDate()->toSql();
		$serverTimeStamp = strtotime($serverTime);

		// Store ID of download file(s) into session
		if ($noCountingDownloadSecond > 0)
		{
			$storeIdArray                   = (array) $app->getUserState('com_judownload.download.storeid');
			$storeIdArray[$serverTimeStamp] = $storeId;
			$storeIdArray                   = array_unique($storeIdArray);
			$app->setUserState('com_judownload.download.storeid', $storeIdArray);
		}

		// Last download time to calculate download interval
		$session = JFactory::getSession();
		$session->set('judl-last-download-time', $serverTime);

		// If use zip class to zip files, set comment then close the archive
		if ($zipFile)
		{
			// Set comment for zip file
			$zip->setComment($zipComment);

			// Close the archive
			$zip->finalize();
		}

		// Send email by event for each document when download
		$docIdArray = array();
		if ($type == 'file')
		{
			$docIdArray[] = $parentId;
		}
		else
		{
			$docIdArray = $itemIdArray;
		}

		$docIdArray = array_unique($docIdArray);
		//Send mail by event
		foreach ($docIdArray AS $docId)
		{
			JUDownloadFrontHelperMail::sendEmailByEvent('document.download', $docId);
		}

		// Download ZIPPED file
		if ($zipFile)
		{
			// Directly download(from zip resource by PHP)
			$resourceFilePath   = $zip->getZipFile();
			$transport          = 'php';
			$speed              = (int) $params->get('max_download_speed', 200);
			$resume             = $params->get('resume_download', 1);
			$downloadMultiParts = $params->get('download_multi_parts', 1);

			$downloadResult = JUDownloadHelper::downloadFile($resourceFilePath, $zipFileName, $transport, $speed, $resume, $downloadMultiParts);

			if ($downloadResult !== true)
			{
				$this->setError($downloadResult);

				return false;
			}
		}
		// Download ONE NO ZIPPED file, in this case $zipFileName is the download file name, file can be zip file or not
		else
		{
			// Directly download
			$transport          = $downloadOneFileNoZippedMode;
			$speed              = (int) $params->get('max_download_speed', 200);
			$resume             = $params->get('resume_download', 1);
			$downloadMultiParts = $params->get('download_multi_parts', 1);

			$downloadResult = JUDownloadHelper::downloadFile($physicalFilePath, $zipFileName, $transport, $speed, $resume, $downloadMultiParts);

			if ($downloadResult !== true)
			{
				$this->setError($downloadResult);

				return false;
			}
		}

		return true;
	}
Example #8
0
	public function download()
	{
		
		JSession::checkToken('request') or die(JText::_('JINVALID_TOKEN'));

		
		$model = $this->getModel();

		
		$model->deleteExpiredTmpFiles();

		
		$app = JFactory::getApplication();
		
		$submittedCategoryId = $app->input->getInt('cat_id', 0);
		$documentIds         = $app->input->get('doc_id', null, null);
		$fileIds             = $app->input->get('file_id', null, null);
		$version             = $app->input->get('version', '', 'string');

		$serverTime      = JFactory::getDate()->toSql();
		$serverTimeStamp = strtotime($serverTime);

		$valuesStoreId = (array) $app->getUserState('com_judownload.download.storeid');

		$params                 = JUDownloadHelper::getParams();
		$noCountingDownloadTime = (int) $params->get('no_counting_download_time', 300);
		
		if ($noCountingDownloadTime > 0)
		{
			if (!empty($valuesStoreId))
			{
				foreach ($valuesStoreId AS $keyStoreId => $valueStoreId)
				{
					if ($serverTimeStamp - $keyStoreId > $noCountingDownloadTime)
					{
						unset($valuesStoreId[$keyStoreId]);
					}
				}
			}

			$app->setUserState('com_judownload.download.storeid', $valuesStoreId);
		}

		
		$dispatcher = JDispatcher::getInstance();
		JPluginHelper::importPlugin('judownload');

		
		if (isset($fileIds))
		{
			
			if (is_array($fileIds))
			{
				
				$fileIdArray = $fileIds;
			}
			else
			{
				
				$fileIdArray = explode(',', $fileIds);
			}

			
			if (count($fileIdArray) > 0)
			{
				
				if (count($fileIdArray) > 1)
				{
					
					$documentId = (int) $documentIds;
					if (!$documentIds)
					{
						$message = JText::_('COM_JUDOWNLOAD_NO_DOCUMENT_DETECTED');
						$this->setRedirect($this->getReturnPage(), $message, 'error');

						return false;
					}

					
					$fileObjectList   = $model->getAllFilesOfDocument($documentId);
					$validFileIdArray = array();
					foreach ($fileObjectList AS $fileObject)
					{
						if (in_array($fileObject->id, $fileIdArray))
						{
							$validFileIdArray[] = $fileObject->id;
						}
					}
				}
				
				else
				{
					$fileObject = $model->getFileObject($fileIdArray[0]);
					$documentId = $fileObject->doc_id;
					if (isset($documentIds))
					{
						$documentIdPost = (int) $documentIds;
						if ($documentIdPost != $documentId)
						{
							$message = JText::_('COM_JUDOWNLOAD_INVALID_DATA');
							$this->setRedirect($this->getReturnPage(), $message, 'error');

							return false;
						}
					}
					$validFileIdArray = $fileIdArray;
					
					$physicalFilePath = $model->getPhysicalFilePath($validFileIdArray[0]);
					$physicalFilePath = JPath::clean($physicalFilePath);
					if (!JFile::exists($physicalFilePath))
					{
						$message = JText::_('COM_JUDOWNLOAD_FILE_DOES_NOT_EXIST');
						$this->setRedirect($this->getReturnPage(), $message, 'error');

						return false;
					}
				}

				
				$canDownloadDocument = $model->canDownloadDocument($documentId);
				if ($canDownloadDocument)
				{
					if (count($validFileIdArray) > 0)
					{
						
						$externalField = new JUDownloadFieldCore_external_link();
						$document      = JUDownloadHelper::getDocumentById($documentId);
						if ($externalField->isPublished() && $document->external_link != '')
						{
							$dispatcher->trigger('onAfterDownloadDocument', array($documentId, array(), 0));

							
							$logData = array(
								'user_id'   => JFactory::getUser()->id,
								'event'     => 'document.download',
								'item_id'   => $documentId,
								'doc_id'    => $documentId,
								'value'     => 0,
								'reference' => 'external'
							);
							JUDownloadFrontHelperLog::addLog($logData);

							
							JUDownloadFrontHelperMail::sendEmailByEvent('document.download', $documentId);

							
							$model->updateDocumentDownloadCounter($documentId);

							
							$this->setRedirect(JRoute::_($document->external_link, false));

							return true;
						}

						if (count($validFileIdArray) > 1)
						{
							$params = JUDownloadHelper::getParams(null, (int) $documentId);
							
							if (!$params->get('allow_zip_file', 1))
							{
								$message = JText::_('COM_JUDOWNLOAD_INVALID_DOWNLOAD_DATA');
								$this->setRedirect($this->getReturnPage(), $message, 'error');

								return false;
							}
						}

						
						foreach ($validFileIdArray AS $validFileId)
						{
							$canDownloadFile = $model->canDownloadFile($validFileId, false);
							if (!$canDownloadFile)
							{
								$fileObject = $model->getFileObject($validFileId);
								$message    = JText::sprintf('COM_JUDOWNLOAD_YOU_CAN_NOT_DOWNLOAD_FILE_X', $fileObject->rename);
								$this->setRedirect($this->getReturnPage(), $message, 'error');

								return false;
							}
						}

						if ($noCountingDownloadTime > 0)
						{
							sort($validFileIdArray);
							$storeID = md5('file' . serialize($validFileIdArray) . $version);
							if (in_array($storeID, $valuesStoreId))
							{
								$generalCheck = true;
							}
							else
							{
								
								$generalCheck = $model->generalCheckDownload();
							}
						}
						else
						{
							$generalCheck = $model->generalCheckDownload();
						}

						if (!$generalCheck)
						{
							$message = $model->getError();
							$this->setRedirect($this->getReturnPage(), $message, 'error');

							return false;
						}

						if ($model->download('file', $validFileIdArray, $documentId, $version) === false)
						{
							$message = $model->getError();
							$this->setRedirect($this->getReturnPage(), $message, 'error');

							return false;
						}

					}
					
					else
					{
						$message = JText::_('COM_JUDOWNLOAD_INVALID_DOWNLOAD_DATA');
						$this->setRedirect($this->getReturnPage(), $message, 'error');

						return false;
					}
				}
				
				else
				{
					$message          = implode("<br/>", $model->getErrors());
					$params           = JUDownloadHelper::getParams(null, $documentId);
					$display_messages = $params->get('show_rule_messages', 'modal');
					if ($display_messages == "redirect")
					{
						$return = $app->input->get('return', null, 'base64');
						$this->setRedirect(JRoute::_('index.php?option=com_judownload&view=downloaderror&return=' . $return, false), $message, 'error');
					}
					else
					{
						$this->setRedirect($this->getReturnPage(), $message, 'error');
					}

					return false;
				}
			}
			
			else
			{
				$message = JText::_('COM_JUDOWNLOAD_NO_FILE_TO_DOWNLOAD');
				$this->setRedirect($this->getReturnPage(), $message, 'error');

				return false;
			}
		}
		
		else
		{
			
			if (is_array($documentIds))
			{
				$documentIdArray = $documentIds;
			}
			else
			{
				$documentIdArray = explode(',', $documentIds);
			}

			if (count($documentIdArray) > 0)
			{
				
				if (count($documentIdArray) > 1)
				{
					$categoryId = $submittedCategoryId;
					
					if (!$categoryId)
					{
						$message = JText::_('COM_JUDOWNLOAD_NO_CATEGORY_DETECTED');
						$this->setRedirect($this->getReturnPage(), $message, 'error');

						return false;
					}

					$params = JUDownloadHelper::getParams(null, $categoryId);
					
					if (!$params->get('allow_download_multi_docs', 0))
					{
						$message = JText::_('COM_JUDOWNLOAD_INVALID_DOWNLOAD_DATA');
						$this->setRedirect($this->getReturnPage(), $message, 'error');

						return false;
					}

					
					$validDocumentIdArray = array();

					
					$documentIdsInCat = $model->getChildDocumentIds($categoryId);

					foreach ($documentIdsInCat AS $documentIdInCat)
					{
						if (in_array($documentIdInCat, $documentIdArray))
						{
							$validDocumentIdArray[] = $documentIdInCat;
						}
					}
				}
				
				else
				{
					$documentId = $documentIdArray[0];
					$categoryId = JUDownloadFrontHelperCategory::getMainCategoryId($documentId);

					$validDocumentIdArray = $documentIdArray;
					$documentIdInCat      = JUDownloadHelper::getDocumentById($documentId);
					$externalField        = new JUDownloadFieldCore_external_link();
					if ($externalField->isPublished() && $documentIdInCat->external_link != '')
					{
						$dispatcher->trigger('onAfterDownloadDocument', array($documentId, array(), 0));

						
						$logData = array(
							'user_id'   => JFactory::getUser()->id,
							'event'     => 'document.download',
							'item_id'   => $documentId,
							'doc_id'    => $documentId,
							'value'     => 0,
							'reference' => 'external'
						);
						JUDownloadFrontHelperLog::addLog($logData);

						
						JUDownloadFrontHelperMail::sendEmailByEvent('document.download', $documentId);

						
						$model->updateDocumentDownloadCounter($documentId);

						
						$this->setRedirect(JRoute::_($documentIdInCat->external_link, false));

						return true;
					}
				}

				if (count($validDocumentIdArray) > 1)
				{
					$params = JUDownloadHelper::getParams($categoryId);
					
					if (!$params->get('allow_zip_file', 1))
					{
						$message = JText::_('COM_JUDOWNLOAD_INVALID_DOWNLOAD_DATA');
						$this->setRedirect($this->getReturnPage(), $message, 'error');

						return false;
					}
				}
				elseif (count($validDocumentIdArray) == 1)
				{
					$filesInDocument = JUDownloadFrontHelperDocument::getFilesByDocumentId((int) $validDocumentIdArray[0]);
					if (count($filesInDocument) > 1)
					{
						if (!$params->get('allow_zip_file', 1))
						{
							$linkFiles = JUDownloadHelperRoute::getDocumentRoute((int) $validDocumentIdArray[0]);
							$linkFiles .= '#judl-files';
							$app->redirect(JRoute::_($linkFiles, false));
						}
					}
				}

				
				foreach ($validDocumentIdArray AS $documentId)
				{
					$canDownloadDocument = $model->canDownloadDocument($documentId);
					if (!$canDownloadDocument)
					{
						$message          = implode("<br/>", $model->getErrors());
						$params           = JUDownloadHelper::getParams(null, $documentId);
						$display_messages = $params->get('show_rule_messages', 'modal');
						if ($display_messages == "redirect")
						{
							$return = $app->input->get('return', null, 'base64');
							$this->setRedirect(JRoute::_('index.php?option=com_judownload&view=downloaderror&return=' . $return, false), $message, 'error');
						}
						else
						{
							$this->setRedirect($this->getReturnPage(), $message, 'error');
						}

						return false;
					}
				}

				
				if ($noCountingDownloadTime > 0)
				{
					sort($validDocumentIdArray);
					$storeID = md5('document' . serialize($validDocumentIdArray) . $version);
					if (in_array($storeID, $valuesStoreId))
					{
						$generalCheck = true;
					}
					else
					{
						
						$generalCheck = $model->generalCheckDownload();
					}
				}
				else
				{
					$generalCheck = $model->generalCheckDownload();
				}

				if (!$generalCheck)
				{
					$message = $model->getError();
					$this->setRedirect($this->getReturnPage(), $message, 'error');

					return false;
				}

				
				if (count($validDocumentIdArray) == 1)
				{
					if (count($filesInDocument) == 1)
					{
						
						if (!$params->get('allow_zip_file', 1))
						{
							$fileObject = $filesInDocument[0];
							$fileId     = $fileObject->id;
							if ($model->download('file', array($fileId), $validDocumentIdArray[0], $version) === false)
							{
								$message = $model->getError();
								$this->setRedirect($this->getReturnPage(), $message, 'error');

								return false;
							}
						}
					}
				}

				if ($model->download('document', $validDocumentIdArray, $categoryId, $version) === false)
				{
					$message = $model->getError();
					$this->setRedirect($this->getReturnPage(), $message, 'error');

					return false;
				}
			}
			
			else
			{
				$message = JText::_('COM_JUDOWNLOAD_NO_DOCUMENT_TO_DOWNLOAD');
				$this->setRedirect($this->getReturnPage(), $message, 'error');

				return false;
			}
		}
	}