Example #1
0
	public function sendemail()
	{
		
		JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));
		$app  = JFactory::getApplication();
		$data = array();

		
		$data['from_name']  = $app->input->post->get('name', '', 'string');
		$data['from_email'] = $app->input->post->get('email', '', 'string');
		$data['to_email']   = $app->input->post->get('to_email', '', 'string');
		$data['doc_id']     = $app->input->getInt('id', 0);

		JUDownloadHelper::obCleanData();
		if (!JUDownloadFrontHelperMail::sendEmailByEvent('document.sendtofriend', $data['doc_id'], $data))
		{
			echo '<label class="control-label"></label><div class="controls"><span class="alert alert-error">' . JText::_('COM_JUDOWNLOAD_FAIL_TO_SEND_EMAIL') . '</span></div>';
			exit;
		}
		else
		{
			echo '<label class="control-label"></label><div class="controls"><span class="alert alert-success">' . JText::_('COM_JUDOWNLOAD_SEND_EMAIL_SUCCESSFULLY') . '</span></div>';
			exit;
		}
	}
 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 #3
0
 public function publish(&$pks, $value = 1)
 {
     $table = $this->getTable('Comment', 'JUDownloadTable');
     $new_pks = array();
     while (!empty($pks)) {
         $pk = array_shift($pks);
         $new_pks[] = $pk;
         $table->reset();
         if (!$table->load($pk)) {
             if ($error = $table->getError()) {
                 $this->setError($error);
             }
             return false;
         }
         $db = $this->getDbo();
         $query = $db->getQuery(true);
         $query->clear();
         $query->select('id');
         $query->from('#__judownload_comments');
         $query->where('lft > ' . (int) $table->lft);
         $query->where('rgt < ' . (int) $table->rgt);
         $db->setQuery($query);
         $childIds = $db->loadColumn();
         foreach ($childIds as $childId) {
             if (!in_array($childId, $pks)) {
                 array_push($pks, $childId);
             }
         }
         $commentId = $pk;
         if (!parent::publish($pk, $value)) {
             return false;
         }
         JUDownloadFrontHelperMail::sendEmailByEvent('comment.editstate', $commentId);
         $logData = array('user_id' => $table->user_id, 'event' => 'comment.editstate', 'item_id' => $commentId, 'doc_id' => $table->doc_id, 'value' => $value, 'reference' => '');
         JUDownloadFrontHelperLog::addLog($logData);
     }
     $pks = $new_pks;
     return true;
 }
Example #4
0
 public function delete($pk = null, $children = true)
 {
     $k = $this->_tbl_key;
     $pk = is_null($pk) ? $this->{$k} : $pk;
     if ($this->_trackAssets) {
         $name = $this->_getAssetName();
         $asset = JTable::getInstance('Asset');
         if (!$asset->_lock()) {
             return false;
         }
         if ($asset->loadByName($name)) {
             if (!$asset->delete(null, $children)) {
                 $this->setError($asset->getError());
                 $asset->_unlock();
                 return false;
             }
             $asset->_unlock();
         } else {
             $this->setError($asset->getError());
             $asset->_unlock();
             return false;
         }
     }
     if (!($node = $this->_getNode($pk))) {
         $this->_unlock();
         return false;
     }
     $commentObjList = array();
     if ($children) {
         $tree = $this->getTree($pk);
         foreach ($tree as $comment) {
             $this->_delete($comment);
             $commentObjList[] = JUDownloadFrontHelperComment::getCommentObject($comment->id);
         }
         if (!$this->_lock()) {
             return false;
         }
         $query = $this->_db->getQuery(true);
         $query->delete();
         $query->from($this->_tbl);
         $query->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
         $query = $this->_db->getQuery(true);
         $query->update($this->_tbl);
         $query->set('lft = lft - ' . (int) $node->width);
         $query->where('lft > ' . (int) $node->rgt);
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
         $query = $this->_db->getQuery(true);
         $query->update($this->_tbl);
         $query->set('rgt = rgt - ' . (int) $node->width);
         $query->where('rgt > ' . (int) $node->rgt);
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
     } else {
         $this->_delete($node);
         if (!$this->_lock()) {
             return false;
         }
         $query = $this->_db->getQuery(true);
         $query->delete();
         $query->from($this->_tbl);
         $query->where('lft = ' . (int) $node->lft);
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
         $query = $this->_db->getQuery(true);
         $query->update($this->_tbl);
         $query->set('lft = lft - 1');
         $query->set('rgt = rgt - 1');
         $query->set('level = level - 1');
         $query->where('lft BETWEEN ' . (int) $node->lft . ' AND ' . (int) $node->rgt);
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
         $query = $this->_db->getQuery(true);
         $query->update($this->_tbl);
         $query->set('parent_id = ' . (int) $node->parent_id);
         $query->where('parent_id = ' . (int) $node->{$k});
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
         $query = $this->_db->getQuery(true);
         $query->update($this->_tbl);
         $query->set('lft = lft - 2');
         $query->where('lft > ' . (int) $node->rgt);
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
         $query = $this->_db->getQuery(true);
         $query->update($this->_tbl);
         $query->set('rgt = rgt - 2');
         $query->where('rgt > ' . (int) $node->rgt);
         $this->_runQuery($query, 'JLIB_DATABASE_ERROR_DELETE_FAILED');
     }
     $this->_unlock();
     if ($children && !empty($commentObjList)) {
         foreach ($commentObjList as $commentObj) {
             if ($commentObj->approved == 0) {
                 JUDownloadFrontHelperMail::sendEmailByEvent('comment.reject', $commentObj->id, get_object_vars($commentObj));
             } elseif (JUDownloadFrontHelperModerator::isModerator()) {
                 JUDownloadFrontHelperMail::sendEmailByEvent('comment.moddelete', $commentObj->id, get_object_vars($commentObj));
             } else {
                 JUDownloadFrontHelperMail::sendEmailByEvent('comment.userdelete', $commentObj->id, get_object_vars($commentObj));
             }
         }
     } else {
         $commentObj = JUDownloadFrontHelperComment::getCommentObject($node->id);
         if ($commentObj->approved == 0) {
             JUDownloadFrontHelperMail::sendEmailByEvent('comment.reject', $commentObj->id, get_object_vars($commentObj));
         } elseif (JUDownloadFrontHelperModerator::isModerator()) {
             JUDownloadFrontHelperMail::sendEmailByEvent('comment.moddelete', $commentObj->id, get_object_vars($commentObj));
         } else {
             JUDownloadFrontHelperMail::sendEmailByEvent('comment.userdelete', $commentObj->id, get_object_vars($commentObj));
         }
     }
     return true;
 }
Example #5
0
 public function saveDocumentSendEmail($table, $isNew, $fieldsData, $tableBeforeSave = null)
 {
     $app = JFactory::getApplication();
     if ($app->isSite()) {
         if ($isNew) {
             JUDownloadFrontHelperMail::sendEmailByEvent('document.create', $table->id);
         } else {
             $versionField = new JUDownloadFieldCore_version();
             if (isset($fieldsData[$versionField->id]) && version_compare($tableBeforeSave->version, $fieldsData[$versionField->id]) != 0) {
                 JUDownloadFrontHelperMail::sendEmailByEvent('document.update', $table->id);
             }
             JUDownloadFrontHelperMail::sendEmailByEvent('document.edit', $table->id);
         }
     }
 }
Example #6
0
	public function saveComment($postData = array())
	{
		
		$user    = JFactory::getUser();
		$nowDate = JFactory::getDate()->toSql();

		$title = htmlspecialchars($postData['title']);
		
		$comment = htmlspecialchars($postData['comment'], ENT_NOQUOTES);

		if ($user->get('guest'))
		{
			$guestName  = strip_tags($postData['guest_name']);
			$guestEmail = strip_tags($postData['guest_email']);
		}
		else
		{
			$guestName  = '';
			$guestEmail = '';
		}

		$website = isset($postData['website']) ? strip_tags($postData['website']) : '';

		$docId        = (int) $postData['doc_id'];
		$params       = JUDownloadHelper::getParams(null, $docId);
		$totalVotes   = 0;
		$helpfulVotes = 0;
		$ipAddress    = JUDownloadFrontHelper::getIpAddress();
		$parentId     = (int) $postData['parent_id'];
		$rootComment  = JUDownloadFrontHelperComment::getRootComment();

		
		if ($parentId == $rootComment->id)
		{
			
			$approved = JUDownloadFrontHelperPermission::canAutoApprovalComment($docId);
			$level    = 1;
			if ($params->get('filter_comment_language', 0))
			{
				$language = $postData['comment_language'];
			}
			else
			{
				$language = '*';
			}
		}
		else
		{
			
			$approved      = JUDownloadFrontHelperPermission::canAutoApprovalReplyComment($docId);
			$parentComment = $this->getCommentObject($parentId);
			$level         = $parentComment->level + 1;
			$language      = '*';
		}

		if ($approved)
		{
			$approved  = 1;
			$published = 1;
		}
		else
		{
			$approved  = 0;
			$published = 0;
		}

		$dataComment = array('title'         => $title, 'comment' => $comment, 'user_id' => $user->id,
		                     'guest_name'    => $guestName, 'guest_email' => $guestEmail, 'website' => $website,
		                     'doc_id'        => $docId, 'created' => $nowDate, 'total_votes' => $totalVotes,
		                     'helpful_votes' => $helpfulVotes, 'ip_address' => $ipAddress, 'approved' => $approved,
		                     'published'     => $published, 'parent_id' => $parentId, 'level' => $level,
		                     'language'      => $language
		);

		JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_judownload/tables');
		$commentTable = JTable::getInstance('Comment', 'JUDownloadTable');
		$commentTable->setLocation($postData['parent_id'], 'last-child');
		$commentTable->bind($dataComment);

		
		if (!$commentTable->check() || !$commentTable->store())
		{
			$this->setError($commentTable->getError());

			return false;
		}

		
		$canRateDocument = JUDownloadFrontHelperPermission::canRateDocument($docId);
		if ($canRateDocument && $params->get('enable_doc_rate_in_comment_form', 1) && ($commentTable->parent_id == $rootComment->id))
		{
			$postData['approved'] = $approved;
			$criteriaArray        = array();

			
			if (isset($postData['criteria_array']))
			{
				if (JUDownloadHelper::hasMultiRating())
				{
					$criteriaArray = $postData['criteria_array'];
					$saveRating    = $this->saveRating($postData, $docId, $criteriaArray, $commentTable->id);
				}
			}
			
			else
			{
				if (isset($postData['ratingValue']))
				{
					$saveRating = $this->saveRating($postData, $docId, $criteriaArray, $commentTable->id);
				}
			}

			if (!$saveRating)
			{
				$this->setError(JText::_('COM_JUDOWNLOAD_SAVE_RATING_FAILED'));

				return false;
			}
		}

		
		if (JUDLPROVERSION && isset($postData['subscribe']) && $postData['subscribe'])
		{
			$subscriptionData               = array();
			$subscriptionData['user_id']    = $user->id;
			$subscriptionData['type']       = 'comment';
			$subscriptionData['comment_id'] = $commentTable->id;
			$subscriptionData['name']       = ($user->id == 0) ? $guestName : $user->username;
			$subscriptionData['email']      = ($user->id == 0) ? $guestEmail : $user->email;
			$subscriptionData['item_id']    = $commentTable->id;
			$subscriptionData['ip_address'] = $ipAddress;
			$subscriptionData['created']    = $nowDate;
			$subscriptionData['published']  = ($user->id == 0 && $params->get('activate_subscription_by_email', 1)) ? 0 : 1;
			
			require_once JPATH_SITE . '/components/com_judownload/models/subscribe.php';
			JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_judownload/models');
			$subscribeModel = JModelLegacy::getInstance('Subscribe', 'JUDownloadModel');
			if (!$subscribeModel->add($subscriptionData))
			{
				$this->setError(JText::_('COM_JUDOWNLOAD_SUBSCRIBE_FAILED'));

				return false;
			}
		}

		
		if ($commentTable->parent_id == $rootComment->id)
		{
			
			JUDownloadFrontHelperMail::sendEmailByEvent('comment.create', $commentTable->id);
			
			$logData = array(
				'item_id' => $commentTable->id,
				'doc_id'  => $docId,
				'user_id' => $user->id,
				'event'   => 'comment.create'
			);

			$commentSubmitType = 'create';
		}
		
		else
		{
			
			JUDownloadFrontHelperMail::sendEmailByEvent('comment.reply', $commentTable->id);

			
			$logData           = array(
				'user_id'   => $user->id,
				'event'     => 'comment.reply',
				'item_id'   => $commentTable->id,
				'doc_id'    => $docId,
				'value'     => 0,
				'reference' => $commentTable->parent_id,
			);
			$commentSubmitType = 'reply';
		}

		JUDownloadFrontHelperLog::addLog($logData);

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

		$dispatcher->trigger('onCommentSubmit', array($commentTable, $commentSubmitType));

		return $commentTable->id;
	}
Example #7
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 #8
0
 public function delete($pk = null)
 {
     JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_judownload/tables');
     $k = $this->_tbl_key;
     $pk = is_null($pk) ? $this->{$k} : $pk;
     $db = JFactory::getDbo();
     $query = "DELETE FROM #__judownload_subscriptions WHERE item_id = {$pk} AND type = 'document'";
     $db->setQuery($query);
     $db->execute();
     $query = "SELECT * FROM #__judownload_comments WHERE doc_id = " . $pk;
     $db->setQuery($query);
     $commentIds = $db->loadColumn();
     if ($commentIds) {
         $commentTable = JTable::getInstance("Comment", "JUDownloadTable");
         foreach ($commentIds as $commentId) {
             $commentTable->delete($commentId);
         }
     }
     $query = "SELECT id FROM #__judownload_rating WHERE doc_id = {$pk}";
     $db->setQuery($query);
     $ratingItemIds = $db->loadColumn();
     if ($ratingItemIds) {
         $ratingTable = JTable::getInstance("Rating", "JUDownloadTable");
         foreach ($ratingItemIds as $ratingItemId) {
             $ratingTable->delete($ratingItemId);
         }
     }
     $query = "DELETE FROM #__judownload_reports WHERE item_id = {$pk} AND type = 'document'";
     $db->setQuery($query);
     $db->execute();
     $query = "SELECT id FROM #__judownload_collections_items WHERE doc_id = {$pk}";
     $db->setQuery($query);
     $collectionItemIds = $db->loadColumn();
     if ($collectionItemIds) {
         $collectionItemTable = JTable::getInstance("CollectionItem", "JUDownloadTable");
         foreach ($collectionItemIds as $collectionItemId) {
             $collectionItemTable->delete($collectionItemId);
         }
     }
     JUDownloadHelper::deleteLogs('document', $pk);
     $query = "DELETE FROM #__judownload_mailqs\r\n\t\t\t      WHERE item_id =" . $pk . "\r\n\t\t\t\t\t\tAND email_id IN (SELECT id FROM #__judownload_emails WHERE (`event` LIKE 'document.%' AND `event` != 'document.delete'))";
     $db->setQuery($query);
     $db->execute();
     $query = $db->getQuery(true);
     $query->select('id');
     $query->from('#__judownload_documents');
     $query->where('approved=' . -$pk);
     $db->setQuery($query);
     $tempDocIds = $db->loadColumn();
     if (count($tempDocIds)) {
         foreach ($tempDocIds as $tempDocId) {
             $this->deleteMainData($tempDocId, true);
         }
     }
     $cat_id = JUDownloadFrontHelperCategory::getMainCategoryId($this->id);
     $this->deleteMainData($pk);
     if (parent::delete($pk)) {
         $app = JFactory::getApplication();
         if ($app->isSite()) {
             $registry = new JRegistry();
             $registry->loadObject($this);
             $mailData = $registry->toArray();
             $mailData['cat_id'] = $cat_id;
             if ($this->approved < 1) {
                 JUDownloadFrontHelperMail::sendEmailByEvent('document.reject', $this->id, $mailData);
             } else {
                 JUDownloadFrontHelperMail::sendEmailByEvent('document.delete', $this->id, $mailData);
             }
         }
         return true;
     } else {
         return false;
     }
 }
Example #9
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 #10
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;
			}
		}
	}