diff --git a/application/modules/backend/library/backend/commands/ConvertVideo.php b/application/modules/backend/library/backend/commands/ConvertVideo.php index 28d6cc47e..73821cd8f 100644 --- a/application/modules/backend/library/backend/commands/ConvertVideo.php +++ b/application/modules/backend/library/backend/commands/ConvertVideo.php @@ -1,99 +1,100 @@ . **/ class Backend_Commands_ConvertVideo implements Local_Queue_CommandInterface { protected $collectionId; protected $fileId; protected $fileType; public static $VIDEO_FILE_TYPES = array('video/3gpp','video/3gpp2','video/mpeg','video/quicktime','video/x-flv','video/webm','application/ogg','video/x-ms-asf','video/x-matroska', 'video/mp4'); /** * PHP 5 allows developers to declare constructor methods for classes. * Classes which have a constructor method call this method on each newly-created object, * so it is suitable for any initialization that the object may need before it is used. * * Note: Parent constructors are not called implicitly if the child class defines a constructor. * In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. * * param [ mixed $args [, $... ]] * * @param int $collectionId * @param int $fileId * * @link http://php.net/manual/en/language.oop5.decon.php */ public function __construct($collectionId, $fileId, $fileType) { $this->collectionId = $collectionId; $this->fileId = $fileId; $this->fileType = $fileType; } public function doCommand() { return $this->callConvertVideo($this->collectionId, $this->fileId, $this->fileType); } protected function callConvertVideo($collectionId, $fileId, $fileType) { $log = Zend_Registry::get('logger'); $log->debug('**********' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $videoServer = new Default_Model_DbTable_Video(); $data = array('id' => $videoServer->getNewId(),'collection_id' => $collectionId,'file_id' => $fileId, 'create_timestamp' => new Zend_Db_Expr('NOW()')); $videoServer->insert($data); //call video convert server $salt = PPLOAD_DOWNLOAD_SECRET; $timestamp = time() + 3600; // one hour valid $hash = hash('sha512',$salt . $collectionId . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $fileId . '/s/' . $hash . '/t/' . $timestamp; $url .= '/lt/filepreview/' . $fileId; - + $url = Default_Model_PpLoad::createDownloadUrl($collectionId,$fileId,array('id'=>$fileId, 't'=>$timestamp, 'lt'=>'filepreview')); + $result = $videoServer->storeExternalVideo($collectionId, $fileType, $url); if(!empty($result) && $result != 'Error') { //Save Preview URL in DB $config = Zend_Registry::get('config'); $cdnurl = $config->videos->media->cdnserver; $url_preview = $cdnurl.$collectionId."/".$result.".mp4"; $url_thumb = $cdnurl.$collectionId."/".$result."_thumb.png"; $data = array('url_preview' => $url_preview, 'url_thumb' => $url_thumb); $videoServer->update($data, "collection_id = $collectionId AND file_id = $fileId"); } else { $log->debug("Error on Converting Video! Result: ".$result); return false; } return true; } } \ No newline at end of file diff --git a/application/modules/default/controllers/AdsController.php b/application/modules/default/controllers/AdsController.php index 63c7d6038..eeb7873bc 100755 --- a/application/modules/default/controllers/AdsController.php +++ b/application/modules/default/controllers/AdsController.php @@ -1,80 +1,87 @@ . **/ class AdsController extends Local_Controller_Action_DomainSwitch { - + public function indexAction() { $this->_helper->layout->disableLayout(); - + $file_id = $this->getParam('file_id'); $file_type = $this->getParam('file_type'); $file_name = $this->getParam('file_name'); $file_size = $this->getParam('file_size'); $projectId = $this->getParam('project_id'); - if($this->hasParam('link_type')) { - $linkType = $this->getParam('link_type'); + if ($this->hasParam('link_type')) { + $linkType = $this->getParam('link_type'); } else { $linkType = "download"; } - + $this->view->link_type = $linkType; - + $memberId = $this->_authMember->member_id; - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - if(isset($file_id) && isset($projectId) && isset($memberId)) { + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + if (isset($file_id) && isset($projectId) && isset($memberId)) { $memberDlHistory = new Default_Model_DbTable_MemberDownloadHistory(); - $data = array('project_id' => $projectId, 'member_id' => $memberId, 'file_id' => $file_id, 'file_type' => $file_type, 'file_name' => $file_name, 'file_size' => $file_size); + $data = array( + 'project_id' => $projectId, + 'member_id' => $memberId, + 'file_id' => $file_id, + 'file_type' => $file_type, + 'file_name' => $file_name, + 'file_size' => $file_size + ); $memberDlHistory->createRow($data)->save(); } - + $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($projectId); - + //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $collectionID = $productInfo->ppload_collection_id; $timestamp = time() + 3600; // one hour valid //20181009 ronald: change hash from MD5 to SHA512 //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying - $hash = hash('sha512',$salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying + $hash = hash('sha512', $salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file_id . '/s/' . $hash . '/t/' . $timestamp . '/u/' . $memberId . '/' . $file_name; - - if($linkType == 'install') { + $url = Default_Model_PpLoad::createDownloadUrl($productInfo->ppload_collection_id,$file_name,array('id'=>$file_id, 'u'=>$memberId)); + + if ($linkType == 'install') { $helperCatXdgType = new Default_View_Helper_CatXdgType(); $xdgType = $helperCatXdgType->catXdgType($productInfo->project_category_id); $url = 'ocs://install' - . '?url=' . urlencode($url) - . '&type=' . urlencode($xdgType) - . '&filename=' . urldecode($file_name); + . '?url=' . urlencode($url) + . '&type=' . urlencode($xdgType) + . '&filename=' . urldecode($file_name); } + $this->view->url = $url; } - } - } \ No newline at end of file diff --git a/application/modules/default/controllers/DlController.php b/application/modules/default/controllers/DlController.php index 570ee3717..18a0c0a6c 100755 --- a/application/modules/default/controllers/DlController.php +++ b/application/modules/default/controllers/DlController.php @@ -1,255 +1,201 @@ . **/ class DlController extends Local_Controller_Action_DomainSwitch { - + public function indexAction() { $this->_helper->layout->disableLayout(); - + $file_id = $this->getParam('file_id'); $file_type = $this->getParam('file_type'); $file_name = $this->getParam('file_name'); $file_size = $this->getParam('file_size'); $projectId = $this->getParam('project_id'); - if($this->hasParam('link_type')) { - $linkType = $this->getParam('link_type'); - } else { - $linkType = "download"; + $linkType = "download"; + if ($this->hasParam('link_type')) { + $linkType = $this->getParam('link_type'); } $isExternal = $this->getParam('is_external'); $externalLink = $this->getParam('external_link'); - + $hasTorrent = $this->getParam('has_torrent'); - + $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($projectId); - + $collectionID = $productInfo->ppload_collection_id; $sModel = new Default_Model_Section(); $section = $sModel->fetchSectionForCategory($productInfo->project_category_id); $info = new Default_Model_Info(); $supporter = $info->getRandomSupporterForSection($section['section_id']); - + $this->view->section_id = $section['section_id']; $this->view->link_type = $linkType; $this->view->file_name = $file_name; $this->view->file_size = $file_size; $this->view->file_size_human = $this->humanFileSize($file_size); $this->view->project_title = $productInfo->title; $this->view->project_owner = $productInfo->username; $this->view->project_id = $projectId; $this->view->is_external = $isExternal; $this->view->external_link = $externalLink; $this->view->supporter = $supporter; - $this->view->has_torrent = ($hasTorrent=="1"); + $this->view->has_torrent = ($hasTorrent == "1"); $this->view->file_id = $file_id; - + $memberId = $this->_authMember->member_id; - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - - - /* - //Log download - try { - $filesDl = new Default_Model_DbTable_PploadFilesDownloaded(); - $id = $filesDl->getNewId(); - $data = array('id' => $id, 'client_id' => PPLOAD_CLIENT_ID, 'owner_id' => $productInfo->member_id, 'collection_id' => $collectionID, 'file_id' => $file_id, 'downloaded_timestamp' => new Zend_Db_Expr ('Now()'), 'downloaded_ip' => $this->getRealIpAddr(), 'referer' => $this->getReferer()); - if(!empty($memberId)) { - $data['user_id'] = $memberId; - } - $data['source'] = 'OCS-Webserver'; - $data['link_type'] = $linkType; + if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $filesDl->createRow($data)->save(); + $payload = array('id' => $file_id, 'u' => $memberId, 'lt' => $linkType); + $url = Default_Model_PpLoad::createDownloadUrlJwt($collectionID, $file_name, $payload); - } catch (Exception $exc) { - //echo $exc->getTraceAsString(); - $errorLog = Zend_Registry::get('logger'); - $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); - } - */ - - - //create ppload download hash: secret + collection_id + expire-timestamp - $salt = PPLOAD_DOWNLOAD_SECRET; - - $timestamp = time() + 3600; // one hour valid - //20181009 ronald: change hash from MD5 to SHA512 - //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying - $hash = hash('sha512',$salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying - - // handle cookie - $config = Zend_Registry::get('config'); - $cookieName = $config->settings->session->auth->anonymous; - $storedInCookie = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : NULL; - if(!$storedInCookie) - { - $remember_me_seconds = $config->settings->session->remember_me->cookie_lifetime; - $cookieExpire = time() + $remember_me_seconds; - $storedInCookie = $hash; - setcookie($cookieName, $hash, $cookieExpire, '/'); - } - - $url = PPLOAD_API_URI . 'files/download/id/' . $file_id . '/s/' . $hash . '/t/' . $timestamp; - if(isset($memberId)) { - $url .= '/u/' . $memberId; - } - $url .= '/c/' . $storedInCookie; - $url .= '/lt/' . $linkType . '/' . $file_name; - - - if($linkType == 'install') { + if ($linkType == 'install') { $helperCatXdgType = new Default_View_Helper_CatXdgType(); $xdgType = $helperCatXdgType->catXdgType($productInfo->project_category_id); $url = 'ocs://install' - . '?url=' . urlencode($url) - . '&type=' . urlencode($xdgType) - . '&filename=' . urldecode($file_name); + . '?url=' . urlencode($url) + . '&type=' . urlencode($xdgType) + . '&filename=' . urldecode($file_name); } - $this->view->url = $url; + $this->view->url = $url; // save to member_download_history - if(isset($file_id) && isset($projectId)) { - - // $data = array('project_id' => $projectId, 'member_id' => $memberId,'anonymous_cookie'=>$storedInCookie, 'file_id' => $file_id, 'file_type' => $file_type, 'file_name' => $file_name, 'file_size' => $file_size,'downloaded_ip' => $this->getRealIpAddr()); + if (isset($file_id) && isset($projectId)) { + $server_info = ''; - $server_info = ''; - - foreach ( $_SERVER as $key=>$value ) { - if ($value) { - $server_info = $server_info.$key.': '.$value.' '; - } + foreach ($_SERVER as $key => $value) { + if ($value) { + $server_info = $server_info . $key . ': ' . $value . ' '; + } } + // handle cookie + $config = Zend_Registry::get('config'); + $cookieName = $config->settings->session->auth->anonymous; + $storedInCookie = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : null; + if (!$storedInCookie) { + $remember_me_seconds = $config->settings->session->remember_me->cookie_lifetime; + $cookieExpire = time() + $remember_me_seconds; + $hash = hash('sha512', PPLOAD_DOWNLOAD_SECRET . $collectionID . (time() + 3600)); + $storedInCookie = $hash; + setcookie($cookieName, $hash, $cookieExpire, '/'); + } $data = array( 'project_id' => $projectId, 'member_id' => $memberId, 'anonymous_cookie' => $storedInCookie, 'file_id' => $file_id, 'file_type' => $file_type, 'file_name' => $file_name, 'file_size' => $file_size, 'downloaded_ip' => $this->getRealIpAddr(), 'HTTP_X_FORWARDED_FOR' => isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null, 'HTTP_X_FORWARDED' => isset($_SERVER['HTTP_X_FORWARDED']) ? $_SERVER['HTTP_X_FORWARDED'] : null, 'HTTP_CLIENT_IP' => isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : null, 'HTTP_FORWARDED_FOR' => isset($_SERVER['HTTP_FORWARDED_FOR']) ? $_SERVER['HTTP_FORWARDED_FOR'] : null, 'HTTP_FORWARDED' => isset($_SERVER['HTTP_FORWARDED']) ? $_SERVER['HTTP_FORWARDED'] : null, 'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'], 'server_info' => $server_info ); $memberDlHistory = new Default_Model_DbTable_MemberDownloadHistory(); $memberDlHistory->createRow($data)->save(); } - - - // anonymous dl save to member_download_fingerprint 17.07 temperately deactived - /*if(isset($file_id) && isset($projectId) && !isset($memberId)) { - $config = Zend_Registry::get('config'); - $cookieName = $config->settings->session->auth->anonymous; - $storedInCookie = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : NULL; - if(!$storedInCookie) - { - $remember_me_seconds = $config->settings->session->remember_me->cookie_lifetime; - $cookieExpire = time() + $remember_me_seconds; - setcookie($cookieName, $hash, $cookieExpire, '/'); - } - - $memberDlAnonymous = new Default_Model_DbTable_MemberDownloadAnonymous(); - $data = array('project_id' => $projectId, 'user' => $_COOKIE[$cookieName], 'file_id' => $file_id); - $memberDlAnonymous->createRow($data)->save(); - }*/ } - + } + /** + * @param int $bytes + * @return string|null + */ + public function humanFileSize($bytes) + { + if (!empty($bytes)) { + $size = round($bytes / 1048576, 2); + if ($size == 0.0) { + return '0.01 MB'; + } else { + return $size . ' MB'; + } + } else { + return null; + } } - function getRealIpAddr() + public function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { - $ip=$_SERVER['HTTP_CLIENT_IP']; - } - elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy + $ip = $_SERVER['HTTP_CLIENT_IP']; + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { - $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; - } - else - { - $ip=$_SERVER['REMOTE_ADDR']; + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } else { + $ip = $_SERVER['REMOTE_ADDR']; } + return $ip; } - function getReferer() + /** + * @return mixed|null + */ + protected function getReferer() { $referer = null; if (!empty($_SERVER['HTTP_REFERER'])) { $referer = $_SERVER['HTTP_REFERER']; } + return $referer; } - - function formatBytes($bytes, $precision = 2) { - $units = array('B', 'KB', 'MB', 'GB', 'TB'); - $bytes = max($bytes, 0); - $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); - $pow = min($pow, count($units) - 1); + /** + * @param int $bytes + * @param int $precision + * @return string + */ + protected function formatBytes($bytes, $precision = 2) + { + $units = array('B', 'KB', 'MB', 'GB', 'TB'); + + $bytes = max($bytes, 0); + $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); + $pow = min($pow, count($units) - 1); // Uncomment one of the following alternatives // $bytes /= pow(1024, $pow); - // $bytes /= (1 << (10 * $pow)); + // $bytes /= (1 << (10 * $pow)); - return round($bytes, $precision) . ' ' . $units[$pow]; - } - - function humanFileSize($bytes) { - if(!empty($bytes)) - { - $size = round($bytes / 1048576, 2); - if($size == 0.0) - { - return '0.01 MB'; - }else - { - return $size.' MB'; - } - } - else - { - return null; - } + return round($bytes, $precision) . ' ' . $units[$pow]; } - } \ No newline at end of file diff --git a/application/modules/default/controllers/Embedv1Controller.php b/application/modules/default/controllers/Embedv1Controller.php index ac5c5d4ce..a0d249862 100644 --- a/application/modules/default/controllers/Embedv1Controller.php +++ b/application/modules/default/controllers/Embedv1Controller.php @@ -1,983 +1,986 @@ . **/ class Embedv1Controller extends Zend_Controller_Action { protected $_format = 'json'; protected $_params = array(); public function init() { parent::init(); $this->initView(); $this->_initResponseHeader(); } public function initView() { // Disable render view $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); } /** * @throws Zend_Exception protected function _initRequestParamsAndFormat() { // Set request parameters switch (strtoupper($_SERVER['REQUEST_METHOD'])) { case 'GET': $this->_params = $_GET; break; case 'PUT': parse_str(file_get_contents('php://input'), $_PUT); $this->_params = $_PUT; break; case 'POST': $this->_params = $_POST; break; default: Zend_Registry::get('logger')->err( __METHOD__ . ' - request method not supported - ' . $_SERVER['REQUEST_METHOD'] ); exit('request method not supported'); } // Set format option if (isset($this->_params['format']) && strtolower($this->_params['format']) == 'json' ) { $this->_format = 'json'; } } */ protected function _initResponseHeader() { $duration = 1800; // in seconds $expires = gmdate("D, d M Y H:i:s", time() + $duration) . " GMT"; $this->getResponse() ->setHeader('X-FRAME-OPTIONS', 'ALLOWALL', true) // ->setHeader('Last-Modified', $modifiedTime, true) ->setHeader('Expires', $expires, true) ->setHeader('Pragma', 'cache', true) ->setHeader('Cache-Control', 'max-age=1800, public', true); } public function indexAction() { $this->_sendErrorResponse(999, 'unknown request'); } protected function _sendErrorResponse($statuscode, $message = '') { if ($this->_format == 'json') { $response = array( 'status' => 'failed', 'statuscode' => $statuscode, 'message' => $message ); } $this->_sendResponse($response, $this->_format); } protected function _sendResponse($response, $format = 'json', $xmlRootTag = 'ocs') { header('Pragma: public'); header('Cache-Control: cache, must-revalidate'); $duration = 1800; // in seconds $expires = gmdate("D, d M Y H:i:s", time() + $duration) . " GMT"; header('Expires: ' . $expires); $callback = $this->getParam('callback'); if ($callback != "") { header('Content-Type: text/javascript; charset=UTF-8'); // strip all non alphanumeric elements from callback $callback = preg_replace('/[^a-zA-Z0-9_]/', '', $callback); echo $callback. '('. json_encode($response). ')'; }else{ header('Content-Type: application/json; charset=UTF-8'); echo json_encode($response); } exit; } public function projectdetailAction(){ $product = $this->_getProject($this->getParam('projectid')); $html = ''; $html = $this->_getHTMLProjectDetail($product); $response = array( 'status' => 'ok', 'statuscode' => 100, 'message' => '', 'data' => array(), 'html' =>'' ); if (!empty($product)) { $response['data'] = $product; } $response['html'] = $html; $this->_sendResponse($response, $this->_format); } protected function _getHTMLProjectDetail($project) { $helperImage = new Default_View_Helper_Image(); $helperPrintDate = new Default_View_Helper_PrintDate(); $printRating= new Default_View_Helper_PrintRatingWidgetSimple(); $html = ''; $html = $html.'
'; $html = $html.'
'; $html = $html.'
'.$project['title']; $html = $html.''.$project['cat_title']; $html = $html.''; $html = $html.'
'; $html = $html.'
'; $html = $html.$printRating->printRatingWidgetSimple($project['laplace_score'],$project['count_likes'],$project['count_dislikes']); $html = $html.'
'; $html = $html.'
'; $html = $html.'
'; // carousels if(count($project['pics'])>0){ $html = $html.'
'; $html = $html.''; /* if(count($project['pics'])>1){ $html = $html.''; $html = $html.''; } */ $html = $html.'
'; } // begin opendesktopwidget-content $html = $html.'
'; $html = $html.'
'; $html = $html.''; $html = $html.'
'; // begin opendesktopwidget-tab-pane-content $html = $html.'
'; $html = $html.'
'; $html = $html.' Description'; $html = $html.$project['description']; if($project['lastchangelog']){ $html = $html.' Last change log'; $html = $html.' '.$project['lastchangelog']['title'].''; $html = $html.''. $helperPrintDate->printDate($project['lastchangelog']['created_at']).''; $html = $html.' '.$project['lastchangelog']['text'].''; } // comments begin $html = $html.'
'; $html_comment = $this->_getHTMLPagerComments($project['comments']) .'
' .$this->_getHTMLComments($project['comments']) .'
'; $html = $html.$html_comment; $html = $html.'
'; // comments end $html = $html.'
'; // end opendesktopwidget-content-description // begin opendesktopwidget-content-files $html = $html.'
'; $html = $html.$this->_getHTMLFiles($project['files']); $html = $html.'
'; // end opendesktopwidget-content-files // begin opendesktopwidget-content-changelogs $html = $html.'
'; $html = $html.$this->_getHTMLChangelogs($project['changelogs']); $html = $html.'
'; // end opendesktopwidget-content-changelogs // begin opendesktopwidget-content-reviews $html = $html.'
'; $html = $html.$this->_getHTMLReviews($project['reviews']); $html = $html.'
'; // end opendesktopwidget-content-reviews // end opendesktopwidget-tab-pane-content $html = $html.'
'; $html = $html.'
'; //opendesktopwidget-main-detail-container-body-content $html = $html.'
'; // end opendesktopwidget-content // end opendesktopwidget-content return $html; } protected function _getHTMLChangelogs($logs) { $helperPrintDate = new Default_View_Helper_PrintDate(); $html = '
'; foreach ($logs as $log) { $html = $html.'
'.$log['title'].''; $html = $html.''.$helperPrintDate->printDate($log['created_at']).''; $html = $html.'
'; $html = $html.''.$log['text'].''; } $html = $html.'
'; return $html; } protected function _getHTMLReviews($reviews) { $helperImage = new Default_View_Helper_Image(); $helperPrintDate = new Default_View_Helper_PrintDate(); $cntActive = 0; $cntLikes = 0; $cntDislike = 0; $cntAll = count($reviews); foreach ($reviews as $review) { if($review['rating_active']==1) { $cntActive =$cntActive+1; $cntLikes = $cntLikes + $review['user_like']; $cntDislike = $cntDislike + $review['user_dislike']; } } $html = '
'; $html = $html.'
'; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.'
'; foreach ($reviews as $review) { $clsActive = ''; $clsLike = ''; if($review['rating_active']==0){ $clsActive ='opendesktopwidget-reviews-rows-inactive '; }else{ $clsActive ='opendesktopwidget-reviews-rows-active '; } if($review['user_like']==1){ $clsLike ='opendesktopwidget-reviews-rows-clsUpvotes '; }else{ $clsLike ='opendesktopwidget-reviews-rows-clsDownvotes '; } $html = $html.'
'; $html = $html.'
'; $html = $html.''; $html = $html.''.$review['username'].''; $html = $html.''.$helperPrintDate->printDate($review['created_at']).''; if($review['user_like']==1){ $html = $html.''; }else{ $html = $html.''; } $html = $html.'
'; $html = $html.''.$review['comment_text'].''; $html = $html.'
'; } $html = $html.'
'; return $html; } protected function _getProject($project_id){ $modelProduct = new Default_Model_Project(); $project = $modelProduct->fetchProductInfo($project_id); if ($project==null) { $this->_sendErrorResponse(101, 'content not found'); } $result = array(); $result = array( 'project_id' => $project['project_id'], 'member_id' => $project['member_id'], 'title' => $project['title'], 'description' => $project['description'], 'version' => $project['version'], 'project_category_id' =>$project['project_category_id'], 'project_created_at' =>$project['project_created_at'], 'project_changed_at' => $project['project_changed_at'], 'laplace_score' => $project['laplace_score'], 'ppload_collection_id' => $project['ppload_collection_id'], 'image_small' => $project['image_small'], 'count_likes' => $project['count_likes'], 'count_dislikes' => $project['count_dislikes'], 'count_comments' => $project['count_comments'], 'cat_title' => $project['cat_title'], 'username' => $project['username'], 'profile_image_url' => $project['profile_image_url'], 'comments' => array(), 'files' =>array(), 'lastchangelog' => array(), 'pics' => array(), 'changelogs' => array(), 'reviews' => array() ); // gallerypics $galleryPictureTable = new Default_Model_DbTable_ProjectGalleryPicture(); $stmt = $galleryPictureTable->select()->where('project_id = ?', $project_id)->order(array('sequence')); $pics = array(); foreach ($galleryPictureTable->fetchAll($stmt) as $pictureRow) { $pics[] = $pictureRow['picture_src']; } $result['pics'] = $pics; // changelogs $tableProjectUpdates = new Default_Model_ProjectUpdates(); $updates = $tableProjectUpdates->fetchProjectUpdates($project_id); if (count($updates) > 0) { $logs = array(); foreach ($updates as $update) { $logs[] = array( 'title' => $update['title'], 'text' => $update['text'], 'created_at' => $update['created_at'], ); } $result['lastchangelog'] = $logs[0]; $result['changelogs'] = $logs; } //reviews $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); $reviews = $tableProjectRatings->fetchRating($project_id); $r = array(); foreach ($reviews as $review) { $r[] = array( 'member_id' => $review['member_id'], 'user_like' => $review['user_like'], 'user_dislike' => $review['user_dislike'], 'rating_active' => $review['rating_active'], 'created_at' => $review['created_at'], 'profile_image_url' => $review['profile_image_url'], 'username' => $review['username'], 'comment_text' => $review['comment_text'] ); } $result['reviews'] = $r; // comments $comments = $this->_getCommentsForProject($project_id); $result['comments'] = $comments; // pploadfiles $files = $this->_getPploadFiles($project['ppload_collection_id']); $result['files'] = $files; return $result; } public function commentsAction() { $project_id = $this->getParam('id'); $page = $this->getParam('page'); $nopage = $this->getParam('nopage'); // with param nopage will only show prudusts list otherwise show $pageLimit = $this->getParam('pagelimit'); if(empty($project_id)){ $response = array( 'status' => 'ok', 'statuscode' => 100, 'message' => '', 'totalitems' =>0, 'html' =>'', 'data' => array() ); }else{ if(empty($page)) $page=0; if(empty($pageLimit)) $pageLimit=10; $comments = $this->_getCommentsForProject($project_id,$page,$pageLimit); $commentsResult = $comments['result']; $response = array( 'status' => 'ok', 'statuscode' => 100, 'message' => '', 'totalitems' => count($commentsResult), 'data' => array() ); if (!empty($commentsResult)) { $response['data'] = $commentsResult; // create html if(empty($nopage)) { // init with comments & pager $html = $this->_getHTMLPagerComments($comments) .'
' .$this->_getHTMLComments($comments) .'
'; }else{ // for only ajax paging content $html =$this->_getHTMLComments($comments); } $response['html'] =$html; } } $this->_sendResponse($response, $this->_format); } protected function _getHTMLComments($comments) { $commentslist = $comments['result']; $helperImage = new Default_View_Helper_Image(); $helperBuildMemberUrl = new Default_View_Helper_BuildMemberUrl(); $helperPrintDate = new Default_View_Helper_PrintDate(); $html = ''; foreach ($commentslist as $p) { $html = $html.'
'; $html = $html.''; $html = $html.'
'; $html = $html.''.$p['username'].''; $html = $html.''. $helperPrintDate->printDate($p['comment_created_at']).''; $html = $html.'
'; $html = $html.'
'; $html = $html.'
'.$p['comment_text'].'
'; $html = $html.'
'; $html = $html.'
'; } return $html; } protected function _getCommentsForProject($project_id,$curPage=1,$pageItemsCount=10) { $modelComments = new Default_Model_ProjectComments(); $comments = $modelComments->getCommentTreeForProject($project_id); $comments->setItemCountPerPage($pageItemsCount); $comments->setCurrentPageNumber($curPage); $result = array(); foreach ($comments as $comment) { $c = $comment['comment']; $result[] = array( 'comment_id' => $c['comment_id'], 'member_id' => $c['member_id'], 'comment_text' => nl2br(Default_Model_HtmlPurify::purify($c['comment_text']),true), 'level' => $comment['level'], 'comment_type' => $c['comment_type'], 'profile_image_url' => $c['profile_image_url'], 'username' => $c['username'], 'comment_target_id'=>$c['comment_target_id'], 'comment_created_at' => $c['comment_created_at'] ); } $rlt = array( 'totalItemCount' => $comments->getTotalItemCount(), 'count' => $comments->count(), 'itemCountPerPage'=>$comments->getItemCountPerPage(), 'result' => $result ); return $rlt; } public function memberprojectsAction() { $user_id = $this->getParam('memberid'); $page = $this->getParam('page'); $nopage = $this->getParam('nopage'); // with param nopage will only show prudusts list otherwise show member+pager+productlist $pageLimit = $this->getParam('pagelimit'); $catids = $this->getParam('catids'); if(empty($pageLimit)){ $pageLimit = 10; } if(empty($catids)){ $catids = null; } if(empty($page)){ $page = 1; } if(empty($user_id)){ $response = array( 'status' => 'ok', 'statuscode' => 100, 'message' => '', 'totalitems' =>0, 'html' =>'', 'data' => array() ); }else{ $userProducts = $this->_getMemberProducts($user_id, $pageLimit, $page,$catids); $response = array( 'status' => 'ok', 'statuscode' => 100, 'message' => '', 'totalitems' => count($userProducts), 'data' => array() ); if (!empty($userProducts)) { $response['data'] = $userProducts; // create html if(empty($nopage)) { // init with member & pager & products $html = $this->_getHTMLMember($user_id) .'
' .$this->_getHTMLPager($user_id,$pageLimit,$page,$catids) .'
' .$this->_getHTMLProducts($userProducts) .'
' .'
'; }else{ // for only ajax paging content $html =$this->_getHTMLProducts($userProducts); } $response['html'] =$html; } } $this->_sendResponse($response, $this->_format); } protected function _getHTMLMember($user_id) { $html = ''; $modelMember = new Default_Model_Member(); $m = $modelMember->fetchMemberData($user_id); $helperImage = new Default_View_Helper_Image(); $html = $html.'
'; $html = $html.''; $html = $html.''; $html = $html.'
'; return $html; } protected function _getHTMLProducts($userProducts) { $helperImage = new Default_View_Helper_Image(); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $printRating= new Default_View_Helper_PrintRatingWidgetSimple(); $helperPrintDate = new Default_View_Helper_PrintDate(); $html = ''; foreach ($userProducts as $p) { $html = $html.'
'; //$html = $html.''; $html = $html.''; $html = $html.'
'; $html = $html.'
'; $html = $html.''.$p['title'].''; $html = $html.''.$p['version'].''; $html = $html.''.$p['cat_name'].''; if($p['count_comments']>0){ $html = $html.''.$p['count_comments'].' comment' .($p['count_comments']>1?'s':'').''; } $html = $html.'
'; $html = $html.'
'; $html = $html.$printRating->printRatingWidgetSimple($p['laplace_score'],$p['count_likes'],$p['count_dislikes']); $html = $html.''. $helperPrintDate->printDate($p['changed']).''; $html = $html.'
'; $html = $html.'
'; //$html = $html.'
'; $html = $html.'
'; } return $html; } protected function _getHTMLPager($user_id,$pageLimit=10,$page=1,$catids=null) { $modelProject = new Default_Model_Project(); $total_records = $modelProject->countAllProjectsForMemberCatFilter($user_id,true,$catids); $total_pages = ceil($total_records / $pageLimit); if($total_pages <=1) return ''; $html = '
'; return $html; } protected function _getHTMLPagerComments($comments) { $total_pages = $comments['count']; if($total_pages<=1) return ''; $html = '
'; return $html; } protected function _getMemberProducts($user_id,$pageLimit=5,$page=1,$catids = null) { $modelProject = new Default_Model_Project(); $userProjects = $modelProject->fetchAllProjectsForMemberCatFilter($user_id, $pageLimit,($page - 1) * $pageLimit, true,$catids); $result = array(); foreach ($userProjects as $project) { $result[] = array( 'id' => $project['project_id'], 'title' => Default_Model_HtmlPurify::purify($project['title']), 'desc' => Default_Model_HtmlPurify::purify($project['description']), 'version' =>Default_Model_HtmlPurify::purify($project['version']), 'cat_id' =>$project['project_category_id'], 'cat_name' => $project['catTitle'], 'created' =>$project['project_created_at'], 'changed' => $project['project_changed_at'], 'laplace_score' => $project['laplace_score'], 'image_small' => $project['image_small'] , 'count_dislikes' => $project['count_dislikes'], 'count_likes' => $project['count_likes'], 'count_comments' => $project['count_comments'] , 'ppload_collection_id' => $project['ppload_collection_id'] ); } return $result; } protected function _getPploadFiles($ppload_collection_id) { $result = array(); - $pploadApi = new Ppload_Api(array( - 'apiUri' => PPLOAD_API_URI, - 'clientId' => PPLOAD_CLIENT_ID, - 'secret' => PPLOAD_SECRET - )); - if ($ppload_collection_id) - { - $filesRequest = array( - 'collection_id' => $ppload_collection_id, - 'perpage' => 100 - ); - - $filesResponse = $pploadApi->getFiles($filesRequest); - - if (isset($filesResponse->status) && $filesResponse->status == 'success') { - $i=0; - foreach ($filesResponse->files as $file) { - $downloadLink = PPLOAD_API_URI . 'files/download/'. 'id/' . $file->id . '/' . $file->name; - $tags = $this->_parseFileTags($file->tags); - $p_type = $this->_getPackagetypeText($tags['packagetypeid']); - $p_lice = $this->_getLicenceText($tags['licensetype']); - $result[] = array( - 'id' =>$file->id, - 'downloadlink'=>$downloadLink, - 'name'=> $file->name, - 'version'=> $file->version, - 'description'=> $file->description, - 'type'=> $file->type, - 'downloaded_count' => $file->downloaded_count, - 'size' => round($file->size / (1024*1024),2), - 'license' => $p_lice, - 'package_type' => $p_type, - 'package_arch' => $tags['packagearch'], - 'created' =>$file->created_timestamp , - 'updated' =>$file->updated_timestamp - ); - } - } - } + $pploadApi = new Ppload_Api(array( + 'apiUri' => PPLOAD_API_URI, + 'clientId' => PPLOAD_CLIENT_ID, + 'secret' => PPLOAD_SECRET + )); + if ($ppload_collection_id) { + $filesRequest = array( + 'collection_id' => $ppload_collection_id, + 'perpage' => 100 + ); + + $filesResponse = $pploadApi->getFiles($filesRequest); + + if (isset($filesResponse->status) && $filesResponse->status == 'success') { + $i = 0; + foreach ($filesResponse->files as $file) { + $downloadLink = PPLOAD_API_URI . 'files/download/' . 'id/' . $file->id . '/' . $file->name; + $payload = array('id' => $file->id); + $downloadLink = Default_Model_PpLoad::createDownloadUrlJwt($ppload_collection_id, $file->name, $payload); + + $tags = $this->_parseFileTags($file->tags); + $p_type = $this->_getPackagetypeText($tags['packagetypeid']); + $p_lice = $this->_getLicenceText($tags['licensetype']); + $result[] = array( + 'id' => $file->id, + 'downloadlink' => $downloadLink, + 'name' => $file->name, + 'version' => $file->version, + 'description' => $file->description, + 'type' => $file->type, + 'downloaded_count' => $file->downloaded_count, + 'size' => round($file->size / (1024 * 1024), 2), + 'license' => $p_lice, + 'package_type' => $p_type, + 'package_arch' => $tags['packagearch'], + 'created' => $file->created_timestamp, + 'updated' => $file->updated_timestamp + ); + } + } + } + return $result; } protected function _getHTMLFiles($files) { if(count($files)==0) return ''; $helperPrintDate = new Default_View_Helper_PrintDate(); $html = '
'; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; foreach ($files as $file) { $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; $html = $html.''; } $html = $html.'
FileVersionDescriptionFiletypePackagetypeLicenseDownloadsDateFilesize
'.$file['name'].''.$file['version'].''.$file['description'].''.$file['type'].''.$file['package_type'].''.$file['license'].''.$file['downloaded_count'].''.$file['created'].''.$file['size'].'MB
'; return $html; } public function pploadAction() { $downloadItems = array(); $ppload_collection_id = $this->getParam('ppload_collection_id'); $count_downloads_hive = $this->getParam('count_downloads_hive'); if(empty($count_downloads_hive)){ $downloads = 0; }else{ $downloads = $count_downloads_hive; } $files = $this->_getPploadFiles($ppload_collection_id); $html=''; $html = $this->_getHTMLFiles($files); if ($this->_format == 'json') { $response = array( 'status' => 'ok', 'statuscode' => 100, 'message' => '', 'totalitems' => count($files), 'html' => $html ); $this->_sendResponse($response, $this->_format); } } protected function _getLicenceText($id) { $typetext = ''; switch ($id) { case 0: $typetext = 'Other'; break; case 1: $typetext = 'GPLv2 or later'; break; case 2: $typetext = 'LGPL'; break; case 3: $typetext = 'Artistic 2.0'; break; case 4: $typetext = 'X11'; break; case 5: $typetext = 'QPL'; break; case 6: $typetext = 'BSD'; break; case 7: $typetext = 'Proprietary License'; break; case 8: $typetext = 'GFDL'; break; case 9: $typetext = 'CPL 1.0'; break; case 10: $typetext = 'Creative Commons by'; break; case 11: $typetext = 'Creative Commons by-sa'; case 12: $typetext = 'Creative Commons by-nd'; break; case 13: $typetext = 'Creative Commons by-nc'; break; case 14: $typetext = 'Creative Commons by-nc-sa'; break; case 15: $typetext = 'Creative Commons by-nc-nd'; break; case 16: $typetext = 'AGPL'; break; case 18: $typetext = 'GPLv2 only'; break; case 19: $typetext = 'GPLv3'; break; } return $typetext; } protected function _getPackagetypeText($typid) { $typetext = ''; switch ($typid) { case 1: $typetext = 'AppImage'; break; case 2: $typetext = 'Android (APK)'; break; case 3: $typetext = 'OS X compatible'; break; case 4: $typetext = 'Windows executable'; break; case 5: $typetext = 'Debian'; break; case 6: $typetext = 'Snappy'; break; case 7: $typetext = 'Flatpak'; break; case 8: $typetext = 'Electron-Webapp'; break; case 9: $typetext = 'Arch'; break; case 10: $typetext = 'open/Suse'; break; case 11: $typetext = 'Redhat'; break; case 12: $typetext = 'Source Code'; break; } return $typetext; } /** * @param string $fileTags * * @return array */ protected function _parseFileTags($fileTags) { $tags = explode(',', $fileTags); $parsedTags = array( 'link' => '', 'licensetype' => '', 'packagetypeid' => '', 'packagearch' => '' ); foreach ($tags as $tag) { $tag = trim($tag); if (strpos($tag, 'link##') === 0) { $parsedTags['link'] = urldecode(str_replace('link##', '', $tag)); } else { if (strpos($tag, 'licensetype-') === 0) { $parsedTags['licensetype'] = str_replace('licensetype-', '', $tag); } else { if (strpos($tag, 'packagetypeid-') === 0) { $parsedTags['packagetypeid'] = str_replace('packagetypeid-', '', $tag); } else { if (strpos($tag, 'packagearch-') === 0) { $parsedTags['packagearch'] = str_replace('packagearch-', '', $tag); } } } } } return $parsedTags; } } diff --git a/application/modules/default/controllers/ProductController.php b/application/modules/default/controllers/ProductController.php index 448f5c07e..a2d0b8ea1 100644 --- a/application/modules/default/controllers/ProductController.php +++ b/application/modules/default/controllers/ProductController.php @@ -1,3453 +1,3341 @@ . **/ class ProductController extends Local_Controller_Action_DomainSwitch { const IMAGE_SMALL_UPLOAD = 'image_small_upload'; const IMAGE_BIG_UPLOAD = 'image_big_upload'; /** * Zend_Controller_Request_Abstract object wrapping the request environment * * @var Zend_Controller_Request_Http */ protected $_request = null; /** @var int */ protected $_projectId; /** @var int */ protected $_collectionId; /** @var Zend_Auth */ protected $_auth; /** @var string */ protected $_browserTitlePrepend; public function init() { parent::init(); $this->_projectId = (int)$this->getParam('project_id'); $this->_collectionId = (int)$this->getParam('collection_id'); $this->_auth = Zend_Auth::getInstance(); $this->_browserTitlePrepend = $this->templateConfigData['head']['browser_title_prepend']; $action = $this->getRequest()->getActionName(); $title = $action; if ($action == 'add') { $title = 'add product'; } else { $title = $action; } $this->view->headTitle($title . ' - ' . $this->getHeadTitle(), 'SET'); } public function ratingAction() { $this->_helper->layout()->disableLayout(); if (array_key_exists($this->_projectId, $this->_authMember->projects)) { return; } $userRating = (int)$this->getParam('rate', 0); $modelRating = new Default_Model_DbTable_ProjectRating(); $modelRating->rateForProject($this->_projectId, $this->_authMember->member_id, $userRating); } public function pploadAction() { $this->_helper->layout->disableLayout(); $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $collectionID = $productInfo->ppload_collection_id; $timestamp = time() + 3600; // one hour valid //20181009 ronald: change hash from MD5 to SHA512 //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $hash = hash('sha512',$salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $this->view->download_hash = $hash; $this->view->download_timestamp = $timestamp; $this->view->product = $productInfo; $this->_helper->viewRenderer('/partials/pploadajax'); } public function gettaggroupsforcatajaxAction() { $this->_helper->layout()->disableLayout(); $catId = null; $fileId = null; if ($this->hasParam('file_id')) { $fileId = $this->getParam('file_id'); } if ($this->hasParam('project_cat_id')) { $catId = $this->getParam('project_cat_id'); $catTagModel = new Default_Model_Tags(); $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId); $tableTags = new Default_Model_DbTable_Tags(); $result = array(); $resultGroup = array(); foreach ($tagGroups as $group) { $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); $selectedTags = null; if (!empty($fileId)) { $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE, $group['tag_group_id']); } $group['tag_list'] = $tags; $group['selected_tags'] = $selectedTags; $result[] = $group; } $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($tagGroups), 'tag_groups' => $result)); return; } $this->_helper->json(array('status' => 'error')); } public function listsamesourceurlAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $result = $modelProduct->getSourceUrlProjects($productInfo->source_url); $r = '
'; foreach ($result as $value) { $r = $r . '
' . '
' . $value['title'] . '
' . '' . '
' . $value['created_at'] . '
' . '
' . $value['changed_at'] . '
' . '
'; } $r = $r . '
'; /*$response='';*/ echo $r; } public function getfilesajaxAction() { $this->_helper->layout()->disableLayout(); $collection_id = null; $file_status = null; $ignore_status_code = null; $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); if ($this->hasParam('status')) { $file_status = $this->getParam('status'); } if ($this->hasParam('ignore_status_code')) { $ignore_status_code = $this->getParam('ignore_status_code'); } $filesTable = new Default_Model_DbTable_PploadFiles(); if ($this->hasParam('collection_id')) { $collection_id = $this->getParam('collection_id'); $result = array(); $isForAdmin = false; if ($userRoleName == Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN) { $isForAdmin = true; } //Load files from DB if ($ignore_status_code == 0 && $file_status == 'active') { $files = $filesTable->fetchAllActiveFilesForProject($collection_id, $isForAdmin); } else { $files = $filesTable->fetchAllFilesForProject($collection_id, $isForAdmin); } //Check, if the project category has tag-grous $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($productInfo->project_category_id); foreach ($files as $file) { //add tag grous, if needed if (!empty($tagGroups)) { $groups = $this->getTagGroupsForCat($file['id']); $file['tag_groups'] = $groups; } //Download Counter //new counter IP based $counterUkAll = $file['count_dl_all_uk']; $counterNoUkAll = $file['count_dl_all_nouk']; $counterUkToday = $file['count_dl_uk_today']; $counterNew = 0; if (!empty($counterUkAll)) { $counterNew = $counterNew + $counterUkAll; } if (!empty($counterUkToday)) { $counterNew = $counterNew + $counterUkToday; } if (!empty($counterNoUkAll)) { $counterNew = $counterNew + $counterNoUkAll; } $file['downloaded_count_uk'] = $counterNew; if ($userRoleName == Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN) { //$file['downloaded_count_live'] = $this->getFileDownloadCount($collection_id, $file['id']); $counterToday = $file['count_dl_today']; $counterAll = $file['count_dl_all']; $counter = 0; if (!empty($counterToday)) { $counter = $counterToday; } if (!empty($counterAll)) { $counter = $counter + $counterAll; } $file['downloaded_count_live'] = $counter; } else { unset($file['count_dl_all']); unset($file['count_dl_all_nouk']); unset($file['count_dl_all_uk']); unset($file['count_dl_uk_today']); unset($file['count_dl_today']); unset($file['downloaded_count']); } $result[] = $file; } $this->_helper->json(array('status' => 'success', 'ResultSize' => count($result), 'files' => $result)); return; } $this->_helper->json(array('status' => 'error')); } private function getTagGroupsForCat($fileId) { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $catId = $productInfo->project_category_id; if (!empty($catId)) { $catTagModel = new Default_Model_Tags(); $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId); $tableTags = new Default_Model_DbTable_Tags(); $result = array(); foreach ($tagGroups as $group) { $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); $selectedTags = null; if (!empty($fileId)) { $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE, $group['tag_group_id']); } $group['tag_list'] = $tags; $group['selected_tags'] = $selectedTags; $result[] = $group; } return $result; } return null; } public function getfiletagsajaxAction() { $this->_helper->layout()->disableLayout(); $fileId = null; if ($this->hasParam('file_id')) { $fileId = $this->getParam('file_id'); $tagModel = new Default_Model_Tags(); $fileTags = $tagModel->getFileTags($fileId); $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($fileTags), 'file_tags' => $fileTags)); return; } $this->_helper->json(array('status' => 'error')); } public function showAction() { $this->view->authMember = $this->_authMember; $this->_helper->viewRenderer('index'); $this->indexAction(); } public function indexAction() { if (!empty($this->_collectionId)) { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductForCollectionId($this->_collectionId); $this->_projectId = $productInfo->project_id; } if (empty($this->_projectId)) { $this->redirect('/explore'); } $this->view->paramPageId = (int)$this->getParam('page'); $this->view->member_id = null; if (null != $this->_authMember && null != $this->_authMember->member_id) { $this->view->member_id = $this->_authMember->member_id; } - // $this->fetchDataForIndexView(); $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); if (empty($productInfo)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } //Check if this is a collection if ($productInfo->type_id == $modelProduct::PROJECT_TYPE_COLLECTION) { $this->redirect('/c/' . $this->_projectId); } $this->view->product = $productInfo; $this->view->headTitle($productInfo->title . ' - ' . $this->getHeadTitle(), 'SET'); $this->view->cat_id = $this->view->product->project_category_id; $tagGroupFilter = Zend_Registry::isRegistered('config_store_taggroups') ? Zend_Registry::get('config_store_taggroups') : null; if (!empty($tagGroupFilter)) { $filterArray = array(); foreach ($tagGroupFilter as $tagGroupId) { $inputFilter = $this->getFilterTagFromCookie($tagGroupId); $filterArray[$tagGroupId] = $inputFilter; } $this->view->tag_group_filter = $filterArray; } //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $collectionID = $this->view->product->ppload_collection_id; $timestamp = time() + 3600; // one hour valid //20181009 ronald: change hash from MD5 to SHA512 //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $hash = hash('sha512', $salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $this->view->download_hash = $hash; $this->view->download_timestamp = $timestamp; $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); $isAdmin = false; if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $isAdmin = true; } $helperUserIsOwner = new Default_View_Helper_UserIsOwner(); $helperIsProjectActive = new Default_View_Helper_IsProjectActive(); if (!$isAdmin AND (false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) ) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } if ((APPLICATION_ENV != 'searchbotenv') AND (false == SEARCHBOT_DETECTED)) { Default_Model_Views::saveViewProduct($this->_projectId); $tablePageViews = new Default_Model_DbTable_StatPageViews(); - $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), - $this->_authMember->member_id); + $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), $this->_authMember->member_id); } $fmodel = new Default_Model_DbTable_PploadFiles(); $filesList = array(); if (isset($this->view->product->ppload_collection_id)) { $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); if (!empty($files)) { foreach ($files as $file) { $timestamp = time() + 3600; // one hour valid $hash = hash('sha512', $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; if (null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; + + $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview'); + $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload); + $file['url'] = urlencode($url); //If this file is a video, we have to convert it for preview - if (!empty($file['type']) && in_array($file['type'], - Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES) && empty($file['ppload_file_preview_id'])) { + if (!empty($file['type']) && in_array($file['type'], Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES) && empty($file['ppload_file_preview_id'])) { $queue = Local_Queue_Factory::getQueue(); - $command = new Backend_Commands_ConvertVideo($file['collection_id'], $file['id'], - $file['type']); + $command = new Backend_Commands_ConvertVideo($file['collection_id'], $file['id'], $file['type']); $queue->send(serialize($command)); } - if (!empty($file['url_preview'])) { $file['url_preview'] = urlencode($file['url_preview']); } if (!empty($file['url_thumb'])) { $file['url_thumb'] = urlencode($file['url_thumb']); } $filesList[] = $file; } } } $this->view->filesJson = Zend_Json::encode($filesList); //gitlab if ($this->view->product->is_gitlab_project) { $gitProject = $this->fetchGitlabProject($this->view->product->gitlab_project_id); if (null == $gitProject) { $this->view->product->is_gitlab_project = 0; $this->view->product->show_gitlab_project_issues = 0; $this->view->product->use_gitlab_project_readme = 0; $this->view->product->gitlab_project_id = null; } else { $this->view->gitlab_project = $gitProject; //show issues? if ($this->view->product->show_gitlab_project_issues) { $issues = $this->fetchGitlabProjectIssues($this->view->product->gitlab_project_id); $this->view->gitlab_project_issues = $issues; $this->view->gitlab_project_issues_url = $this->view->gitlab_project['web_url'] . '/issues/'; } //show readme.md? if ($this->view->product->use_gitlab_project_readme && null != $this->view->gitlab_project['readme_url']) { $config = Zend_Registry::get('config')->settings->server->opencode; $readme = $this->view->gitlab_project['web_url'] . '/raw/master/README.md?inline=false'; $httpClient = new Zend_Http_Client($readme, array('keepalive' => true, 'strictredirects' => true)); $httpClient->resetParameters(); $httpClient->setUri($readme); $httpClient->setHeaders('Private-Token', $config->private_token); $httpClient->setHeaders('Sudo', $config->user_sudo); $httpClient->setHeaders('User-Agent', $config->user_agent); $httpClient->setMethod(Zend_Http_Client::GET); $response = $httpClient->request(); $body = $response->getRawBody(); if (count($body) == 0) { return array(); } include_once('Parsedown.php'); $Parsedown = new Parsedown(); $this->view->readme = $Parsedown->text($body); } else { $this->view->readme = null; } } } // products related $pc = new Default_Model_ProjectClone(); $cntRelatedProducts = 0; $ancesters = $pc->fetchAncestersIds($this->_projectId); //$siblings = $pc->fetchSiblings($this->_projectId); //$parents = $pc->fetchParentIds($this->_projectId); if ($ancesters && strlen($ancesters) > 0) { $parents = $pc->fetchParentLevelRelatives($this->_projectId); } else { $parents = $pc->fetchParentIds($this->_projectId); } if ($parents && strlen($parents) > 0) { $siblings = $pc->fetchSiblingsLevelRelatives($parents, $this->_projectId); } else { $siblings = null; } $childrens = $pc->fetchChildrensIds($this->_projectId); $childrens2 = null; $childrens3 = null; if (strlen($childrens) > 0) { $childrens2 = $pc->fetchChildrensChildrenIds($childrens); if (strlen($childrens2) > 0) { $childrens3 = $pc->fetchChildrensChildrenIds($childrens2); } } $this->view->related_ancesters = null; $this->view->related_siblings = null; $this->view->related_parents = null; $this->view->related_children = null; $this->view->related_children2 = null; $this->view->related_children3 = null; if ($ancesters && strlen($ancesters) > 0) { $pts = $modelProduct->fetchProjects($ancesters); $this->view->related_ancesters = sizeof($pts) == 0 ? null : $pts; $cntRelatedProducts += sizeof($pts); } if ($siblings && strlen($siblings) > 0) { $pts = $modelProduct->fetchProjects($siblings); $this->view->related_siblings = sizeof($pts) == 0 ? null : $pts; $cntRelatedProducts += sizeof($pts); } if ($parents && strlen($parents) > 0) { $pts = $modelProduct->fetchProjects($parents); $this->view->related_parents = sizeof($pts) == 0 ? null : $pts; $cntRelatedProducts += sizeof($pts); } if ($childrens && strlen($childrens) > 0) { $pts = $modelProduct->fetchProjects($childrens); $this->view->related_children = sizeof($pts) == 0 ? null : $pts; $cntRelatedProducts += sizeof($pts); } if ($childrens2 && strlen($childrens2) > 0) { $pts = $modelProduct->fetchProjects($childrens2); $this->view->related_children2 = sizeof($pts) == 0 ? null : $pts; $cntRelatedProducts += sizeof($pts); } if ($childrens3 && strlen($childrens3) > 0) { $pts = $modelProduct->fetchProjects($childrens3); $this->view->related_children3 = sizeof($pts) == 0 ? null : $pts; $cntRelatedProducts += sizeof($pts); } $this->view->cntRelatedProducts = $cntRelatedProducts; $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; if ($storeConfig->layout_pagedetail && $storeConfig->isRenderReact()) { $this->initJsonForReact(); $this->_helper->viewRenderer('index-react'); } } private function getFilterTagFromCookie($group) { $config = Zend_Registry::get('config'); $cookieName = $config->settings->session->filter_browse_original . $group; $storedInCookie = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : null; return $storedInCookie; } private function fetchGitlabProject($gitProjectId) { $gitlab = new Default_Model_Ocs_Gitlab(); try { $gitProject = $gitlab->getProject($gitProjectId); } catch (Exception $exc) { //Project is gone $modelProject = new Default_Model_Project(); $modelProject->updateProject($this->_projectId, array( 'is_gitlab_project' => 0, 'gitlab_project_id' => null, 'show_gitlab_project_issues' => 0, 'use_gitlab_project_readme' => 0 )); $gitProject = null; } return $gitProject; } private function fetchGitlabProjectIssues($gitProjectId) { $gitlab = new Default_Model_Ocs_Gitlab(); try { $gitProjectIssues = $gitlab->getProjectIssues($gitProjectId); } catch (Exception $exc) { //Project is gone $modelProject = new Default_Model_Project(); $modelProject->updateProject($this->_projectId, array( 'is_gitlab_project' => 0, 'gitlab_project_id' => null, 'show_gitlab_project_issues' => 0, 'use_gitlab_project_readme' => 0 )); $gitProjectIssues = null; } return $gitProjectIssues; } public function initJsonForReact() { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $this->view->product = $productInfo; if (empty($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } if (null != $this->_authMember) { $this->view->authMemberJson = Zend_Json::encode(Default_Model_Member::cleanAuthMemberForJson($this->_authMember)); } $helpAddDefaultScheme = new Default_View_Helper_AddDefaultScheme(); $this->view->product->title = Default_Model_HtmlPurify::purify($this->view->product->title); $this->view->product->description = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify($this->view->product->description)); $this->view->product->version = Default_Model_HtmlPurify::purify($this->view->product->version); $this->view->product->link_1 = Default_Model_HtmlPurify::purify($helpAddDefaultScheme->addDefaultScheme($this->view->product->link_1), Default_Model_HtmlPurify::ALLOW_URL); $this->view->product->source_url = Default_Model_HtmlPurify::purify($this->view->product->source_url, Default_Model_HtmlPurify::ALLOW_URL); $this->view->product->facebook_code = Default_Model_HtmlPurify::purify($this->view->product->facebook_code, Default_Model_HtmlPurify::ALLOW_URL); $this->view->product->twitter_code = Default_Model_HtmlPurify::purify($this->view->product->twitter_code, Default_Model_HtmlPurify::ALLOW_URL); $this->view->product->google_code = Default_Model_HtmlPurify::purify($this->view->product->google_code, Default_Model_HtmlPurify::ALLOW_URL); $this->view->productJson = Zend_Json::encode(Default_Model_Collection::cleanProductInfoForJson($this->view->product)); $fmodel = new Default_Model_DbTable_PploadFiles(); $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); $salt = PPLOAD_DOWNLOAD_SECRET; $filesList = array(); foreach ($files as $file) { $timestamp = time() + 3600; // one hour valid $hash = hash('sha512', $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; if (null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; + + $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview'); + $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload); + $file['url'] = urlencode($url); $filesList[] = $file; } $this->view->filesJson = Zend_Json::encode($filesList); $this->view->filesCntJson = Zend_Json::encode($fmodel->fetchFilesCntForProject($this->view->product->ppload_collection_id)); $tableProjectUpdates = new Default_Model_ProjectUpdates(); $this->view->updatesJson = Zend_Json::encode($tableProjectUpdates->fetchProjectUpdates($this->_projectId)); $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); $ratings = $tableProjectRatings->fetchRating($this->_projectId); $cntRatingsActive = 0; foreach ($ratings as $p) { if ($p['rating_active'] == 1) { $cntRatingsActive = $cntRatingsActive + 1; } } $this->view->ratingsJson = Zend_Json::encode($ratings); $this->view->cntRatingsActiveJson = Zend_Json::encode($cntRatingsActive); $identity = Zend_Auth::getInstance()->getStorage()->read(); if (Zend_Auth::getInstance()->hasIdentity()) { $ratingOfUserJson = $tableProjectRatings->getProjectRateForUser($this->_projectId, $identity->member_id); $this->view->ratingOfUserJson = Zend_Json::encode($ratingOfUserJson); } else { $this->view->ratingOfUserJson = Zend_Json::encode(null); } $tableProjectFollower = new Default_Model_DbTable_ProjectFollower(); $likes = $tableProjectFollower->fetchLikesForProject($this->_projectId); $this->view->likeJson = Zend_Json::encode($likes); $projectplings = new Default_Model_ProjectPlings(); $plings = $projectplings->fetchPlingsForProject($this->_projectId); $this->view->projectplingsJson = Zend_Json::encode($plings); $tableProject = new Default_Model_Project(); $galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId); $this->view->galleryPicturesJson = Zend_Json::encode($galleryPictures); $tagmodel = new Default_Model_Tags(); $tagsuser = $tagmodel->getTagsUser($this->_projectId, Default_Model_Tags::TAG_TYPE_PROJECT); $tagssystem = $tagmodel->getTagsSystemList($this->_projectId); $this->view->tagsuserJson = Zend_Json::encode($tagsuser); $this->view->tagssystemJson = Zend_Json::encode($tagssystem); $modelComments = new Default_Model_ProjectComments(); $offset = 0; $testComments = $modelComments->getCommentTreeForProjectList($this->_projectId); $this->view->commentsJson = Zend_Json::encode($testComments); $modelClone = new Default_Model_ProjectClone(); $origins = $modelClone->fetchOrigins($this->_projectId); $this->view->originsJson = Zend_Json::encode($origins); $related = $modelClone->fetchRelatedProducts($this->_projectId); $this->view->relatedJson = Zend_Json::encode($related); $moreProducts = $tableProject->fetchMoreProjects($this->view->product, 8); $this->view->moreProductsJson = Zend_Json::encode($moreProducts); $moreProducts = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8); $this->view->moreProductsOfOtherUsrJson = Zend_Json::encode($moreProducts); } public function addAction() { $this->view->member = $this->_authMember; $this->view->mode = 'add'; if ($this->getParam('catId')) { $this->view->catId = $this->getParam('catId'); } $form = new Default_Form_Product(array('member_id' => $this->view->member->member_id)); $this->view->form = $form; if ($this->_request->isGet()) { return; } - $helperUserRole = new Backend_View_Helper_UserRole(); - $userRoleName = $helperUserRole->userRole(); - $isAdmin = false; - if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { - $isAdmin = true; - } - - if (isset($_POST['cancel'])) { // user cancel function $this->redirect('/member/' . $this->_authMember->member_id . '/news/'); } if (false === $form->isValid($_POST)) { // form not valid $this->view->form = $form; $this->view->error = 1; return; } $values = $form->getValues(); $imageModel = new Default_Model_DbTable_Image(); try { $values['image_small'] = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD)); } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true)); } // form was valid, so we can set status to active $values['status'] = Default_Model_DbTable_Project::PROJECT_ACTIVE; // save new project $modelProject = new Default_Model_Project(); Zend_Registry::get('logger')->info(__METHOD__ . ' - $post: ' . print_r($_POST, true)); Zend_Registry::get('logger')->info(__METHOD__ . ' - $files: ' . print_r($_FILES, true)); Zend_Registry::get('logger')->info(__METHOD__ . ' - input values: ' . print_r($values, true)); $newProject = null; try { if (isset($values['project_id'])) { $newProject = $modelProject->updateProject($values['project_id'], $values); } else { $newProject = $modelProject->createProject($this->_authMember->member_id, $values, $this->_authMember->username); //$this->createSystemPlingForNewProject($newProject->project_id); } } catch (Exception $exc) { Zend_Registry::get('logger')->warn(__METHOD__ . ' - traceString: ' . $exc->getTraceAsString()); } if (!$newProject) { $this->_helper->flashMessenger->addMessage('

You did not choose a Category in the last level.

'); $this->forward('add'); return; } //update the gallery pics $mediaServerUrls = $this->saveGalleryPics($form->gallery->upload->upload_picture); $modelProject->updateGalleryPictures($newProject->project_id, $mediaServerUrls); //If there is no Logo, we take the 1. gallery pic if (!isset($values['image_small']) || $values['image_small'] == '') { $values['image_small'] = $mediaServerUrls[0]; $newProject = $modelProject->updateProject($newProject->project_id, $values); } //New Project in Session, for AuthValidation (owner) $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id); $modelTags = new Default_Model_Tags(); if ($values['tagsuser']) { $modelTags->processTagsUser($newProject->project_id, implode(',', $values['tagsuser']), Default_Model_Tags::TAG_TYPE_PROJECT); } else { $modelTags->processTagsUser($newProject->project_id, null, Default_Model_Tags::TAG_TYPE_PROJECT); } $modelTags->processTagProductOriginalOrModification($newProject->project_id, $values['is_original_or_modification'][0]); //set license, if needed $licenseTag = $form->getElement('license_tag_id')->getValue(); //only set/update license tags if something was changed if ($licenseTag && count($licenseTag) > 0) { $modelTags->saveLicenseTagForProject($newProject->project_id, $licenseTag); $activityLog = new Default_Model_ActivityLog(); $activityLog->logActivity($newProject->project_id, $newProject->project_id, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED, array('title' => 'Set new License Tag', 'description' => 'New TagId: ' . $licenseTag)); } $isGitlabProject = $form->getElement('is_gitlab_project')->getValue(); $gitlabProjectId = $form->getElement('gitlab_project_id')->getValue(); if ($isGitlabProject && $gitlabProjectId == 0) { $values['gitlab_project_id'] = null; } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($newProject->project_id, $newProject->member_id, Default_Model_ActivityLog::PROJECT_CREATED, $newProject->toArray()); // ppload $this->processPploadId($newProject); try { if (100 < $this->_authMember->roleId) { if (Default_Model_Spam::hasSpamMarkers($newProject->toArray())) { $tableReportComments = new Default_Model_DbTable_ReportProducts(); $tableReportComments->save(array( 'project_id' => $newProject->project_id, 'reported_by' => 24, 'text' => "System: automatic spam detection" )); } Default_Model_DbTable_SuspicionLog::logProject($newProject, $this->_authMember, $this->getRequest()); } } catch (Zend_Exception $e) { Zend_Registry::get('logger')->err($e->getMessage()); } $this->redirect('/member/' . $newProject->member_id . '/products/'); } private function saveGalleryPics($form_element) { $imageModel = new Default_Model_DbTable_Image(); return $imageModel->saveImages($form_element); } /** * @param $projectData */ protected function processPploadId($projectData) { if ($projectData->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionCategory = $projectData->project_category_id; if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) { $collectionCategory .= '-published'; } $collectionRequest = array( 'title' => $projectData->title, 'description' => $projectData->description, 'category' => $collectionCategory, 'content_id' => $projectData->project_id ); $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest); // Store product image as collection thumbnail $this->_updatePploadMediaCollectionthumbnail($projectData); } } /** * ppload */ protected function _updatePploadMediaCollectionthumbnail($projectData) { if (empty($projectData->ppload_collection_id) || empty($projectData->image_small) ) { return false; } $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $filename = sys_get_temp_dir() . '/' . $projectData->image_small; if (false === file_exists(dirname($filename))) { mkdir(dirname($filename), 0777, true); } $viewHelperImage = new Default_View_Helper_Image(); $uri = $viewHelperImage->Image($projectData->image_small, array( 'width' => 600, 'height' => 600 )); file_put_contents($filename, file_get_contents($uri)); $mediaCollectionthumbnailResponse = $pploadApi->postMediaCollectionthumbnail($projectData->ppload_collection_id, array('file' => $filename)); unlink($filename); if (isset($mediaCollectionthumbnailResponse->status) && $mediaCollectionthumbnailResponse->status == 'success' ) { return true; } return false; } public function editAction() { if (empty($this->_projectId)) { $this->redirect($this->_helper->url('add')); return; } $this->_helper->viewRenderer('add'); // we use the same view as you can see at add a product $this->view->mode = 'edit'; $projectTable = new Default_Model_DbTable_Project(); $projectModel = new Default_Model_Project(); $modelTags = new Default_Model_Tags(); $tagTable = new Default_Model_DbTable_Tags(); //check if product with given id exists $projectData = $projectTable->find($this->_projectId)->current(); if (empty($projectData)) { $this->redirect($this->_helper->url('add')); return; } $member = null; if (isset($this->_authMember) AND (false === empty($this->_authMember->member_id))) { $member = $this->_authMember; } else { throw new Zend_Controller_Action_Exception('no authorization found'); } if (("admin" == $this->_authMember->roleName)) { $modelMember = new Default_Model_Member(); $member = $modelMember->fetchMember($projectData->member_id, false); } $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); $isAdmin = false; if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $isAdmin = true; } //set ppload-collection-id in view $this->view->ppload_collection_id = $projectData->ppload_collection_id; $this->view->project_id = $projectData->project_id; $this->view->product = $projectData; //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $collectionID = $projectData->ppload_collection_id; $timestamp = time() + 3600; // one hour valid //20181009 ronald: change hash from MD5 to SHA512 //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $hash = hash('sha512', $salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying $this->view->download_hash = $hash; $this->view->download_timestamp = $timestamp; $this->view->member_id = $member->member_id; $this->view->member = $member; //read the already existing gallery pics and add them to the form $sources = $projectModel->getGalleryPictureSources($this->_projectId); //get the gitlab projects for this user //setup form $form = new Default_Form_Product(array('pictures' => $sources, 'member_id' => $this->view->member_id)); if (false === empty($projectData->image_small)) { $form->getElement('image_small_upload')->setRequired(false); } $form->getElement('preview')->setLabel('Save'); $form->removeElement('project_id'); // we don't need this field in edit mode if ($this->_request->isGet()) { $form->populate($projectData->toArray()); // $form->populate(array('tags' => $modelTags->getTags($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT))); $form->populate(array( 'tagsuser' => $modelTags->getTagsUser($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT) )); $form->getElement('image_small')->setValue($projectData->image_small); //Bilder voreinstellen $form->getElement(self::IMAGE_SMALL_UPLOAD)->setValue($projectData->image_small); $licenseTags = $tagTable->fetchLicenseTagsForProject($this->_projectId); $licenseTag = null; if ($licenseTags) { $licenseTag = $licenseTags[0]['tag_id']; } $form->getElement('license_tag_id')->setValue($licenseTag); $is_original = $modelTags->isProductOriginal($projectData->project_id); $is_modification = $modelTags->isProductModification($projectData->project_id); if ($is_original) { $form->getElement('is_original_or_modification')->setValue(1); } else { if ($is_modification) { $form->getElement('is_original_or_modification')->setValue(2); } } $this->view->form = $form; return; } if (isset($_POST['cancel'])) { // user cancel function $this->redirect('/member/' . $member->member_id . '/news/'); } if (false === $form->isValid($_POST, $this->_projectId)) { // form not valid $this->view->form = $form; $this->view->error = 1; return; } $values = $form->getValues(); //set license, if needed $tagList = $modelTags->getTagsArray($this->_projectId, $modelTags::TAG_TYPE_PROJECT, $modelTags::TAG_LICENSE_GROUPID); $oldLicenseTagId = null; if ($tagList && count($tagList) == 1) { $oldLicenseTagId = $tagList[0]['tag_id']; } $licenseTag = $form->getElement('license_tag_id')->getValue(); //only set/update license tags if something was changed if ($licenseTag <> $oldLicenseTagId) { $modelTags->saveLicenseTagForProject($this->_projectId, $licenseTag); $activityLog = new Default_Model_ActivityLog(); $activityLog->logActivity($this->_projectId, $this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED, array( 'title' => 'License Tag', 'description' => 'Old TagId: ' . $oldLicenseTagId . ' - New TagId: ' . $licenseTag )); } //gitlab project $isGitlabProject = $form->getElement('is_gitlab_project')->getValue(); $gitlabProjectId = $form->getElement('gitlab_project_id')->getValue(); if ($isGitlabProject && $gitlabProjectId == 0) { $values['gitlab_project_id'] = null; } $imageModel = new Default_Model_DbTable_Image(); try { $uploadedSmallImage = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD)); $values['image_small'] = $uploadedSmallImage ? $uploadedSmallImage : $values['image_small']; } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true)); } // save changes $projectModel->updateProject($this->_projectId, $values); //update the gallery pics $pictureSources = array_merge($values['gallery']['online_picture'], $this->saveGalleryPics($form->gallery->upload->upload_picture)); $projectModel->updateGalleryPictures($this->_projectId, $pictureSources); //If there is no Logo, we take the 1. gallery pic if (!isset($projectData->image_small) || $projectData->image_small == '') { $projectData->image_small = $pictureSources[0]; } //20180219 ronald: we set the changed_at only by new files or new updates //$projectData->changed_at = new Zend_Db_Expr('NOW()'); $projectData->save(); $modelTags->processTagProductOriginalOrModification($this->_projectId, $values['is_original_or_modification'][0]); if ($values['tagsuser']) { $modelTags->processTagsUser($this->_projectId, implode(',', $values['tagsuser']), Default_Model_Tags::TAG_TYPE_PROJECT); } else { $modelTags->processTagsUser($this->_projectId, null, Default_Model_Tags::TAG_TYPE_PROJECT); } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray()); // ppload $this->processPploadId($projectData); try { if (100 < $this->_authMember->roleId) { if (Default_Model_Spam::hasSpamMarkers($projectData->toArray())) { $tableReportComments = new Default_Model_DbTable_ReportProducts(); $tableReportComments->save(array( 'project_id' => $projectData->project_id, 'reported_by' => 24, 'text' => "System: automatic spam detection on product edit" )); } Default_Model_DbTable_SuspicionLog::logProject($projectData, $this->_authMember, $this->getRequest()); } } catch (Zend_Exception $e) { Zend_Registry::get('logger')->err($e->getMessage()); } $helperBuildMemberUrl = new Default_View_Helper_BuildMemberUrl(); $this->redirect($helperBuildMemberUrl->buildMemberUrl($member->username, 'products')); } public function getupdatesajaxAction() { $this->view->authMember = $this->_authMember; $tableProject = new Default_Model_ProjectUpdates(); $updates = $tableProject->fetchProjectUpdates($this->_projectId); foreach ($updates as $key => $update) { $updates[$key]['title'] = Default_Model_HtmlPurify::purify($update['title']); $updates[$key]['text'] = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify(htmlentities($update['text'], ENT_QUOTES | ENT_IGNORE))); $updates[$key]['raw_title'] = $update['title']; $updates[$key]['raw_text'] = $update['text']; } $result['status'] = 'success'; $result['ResultSize'] = count($updates); $result['updates'] = $updates; $this->_helper->json($result); } public function saveupdateajaxAction() { $filter = new Zend_Filter_Input( array( '*' => 'StringTrim' ), array( '*' => array(), 'title' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 200)), 'presence' => 'required', 'allowEmpty' => false ), 'text' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 16383)), 'presence' => 'required', 'allowEmpty' => false ), 'update_id' => array('digits', 'allowEmpty' => true) ), $this->getAllParams(), array('allowEmpty' => true)); if ($filter->hasInvalid() OR $filter->hasMissing() OR $filter->hasUnknown()) { $result['status'] = 'error'; $result['messages'] = $filter->getMessages(); $result['update_id'] = null; $this->_helper->json($result); } $update_id = $filter->getEscaped('update_id'); $tableProjectUpdates = new Default_Model_ProjectUpdates(); //Save update if (!empty($update_id)) { //Update old update $updateArray = array(); $updateArray['title'] = $filter->getUnescaped('title'); $updateArray['text'] = $filter->getUnescaped('text'); $updateArray['changed_at'] = new Zend_Db_Expr('Now()'); $countUpdated = $tableProjectUpdates->update($updateArray, 'project_update_id = ' . $update_id); } else { //Add new update $updateArray = array(); $updateArray['title'] = $filter->getUnescaped('title'); $updateArray['text'] = $filter->getUnescaped('text'); $updateArray['public'] = 1; $updateArray['project_id'] = $this->_projectId; $updateArray['member_id'] = $this->_authMember->member_id; $updateArray['created_at'] = new Zend_Db_Expr('Now()'); $updateArray['changed_at'] = new Zend_Db_Expr('Now()'); $rowset = $tableProjectUpdates->save($updateArray); $update_id = $rowset->project_update_id; //20180219 ronald: we set the changed_at only by new files or new updates $projectTable = new Default_Model_Project(); $projectUpdateRow = $projectTable->find($this->_projectId)->current(); if (count($projectUpdateRow) == 1) { $projectUpdateRow->changed_at = new Zend_Db_Expr('NOW()'); $projectUpdateRow->save(); } } $result['status'] = 'success'; $result['update_id'] = $update_id; $this->_helper->json($result); } public function deleteupdateajaxAction() { $this->view->authMember = $this->_authMember; $tableProject = new Default_Model_ProjectUpdates(); $params = $this->getAllParams(); $project_update_id = $params['update_id']; $updateArray = array(); $updateArray['public'] = 0; $updateArray['changed_at'] = new Zend_Db_Expr('Now()'); $tableProject->update($updateArray, 'project_update_id = ' . $project_update_id); $result['status'] = 'success'; $result['update_id'] = $project_update_id; $this->_helper->json($result); } public function updatesAction() { $this->view->authMember = $this->_authMember; $tableProject = new Default_Model_Project(); $this->view->product = $tableProject->fetchProductInfo($this->_projectId); if (false === isset($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $this->view->relatedProducts = $tableProject->fetchSimilarProjects($this->view->product, 6); $this->view->supporter = $tableProject->fetchProjectSupporter($this->_projectId); $this->view->product_views = $tableProject->fetchProjectViews($this->_projectId); $modelPlings = new Default_Model_DbTable_Plings(); $this->view->comments = $modelPlings->getCommentsForProject($this->_projectId, 10); $tableMember = new Default_Model_Member(); $this->view->member = $tableMember->fetchMemberData($this->view->product->member_id); $this->view->updates = $tableProject->fetchProjectUpdates($this->_projectId); $tablePageViews = new Default_Model_DbTable_StatPageViews(); $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), $this->_authMember->member_id); } public function updateAction() { $this->_helper->layout()->setLayout('flat_ui'); $this->view->headScript()->setFile(''); $this->view->headLink()->setStylesheet(''); $this->_helper->viewRenderer('add'); $form = new Default_Form_ProjectUpdate(); $projectTable = new Default_Model_Project(); $projectData = null; $projectUpdateId = (int)$this->getParam('upid'); $this->view->member = $this->_authMember; $this->view->title = 'Add an update for your product'; $activityLogType = Default_Model_ActivityLog::PROJECT_ITEM_CREATED; if (false === empty($projectUpdateId)) { $this->view->title = 'Edit an product update'; $projectData = $projectTable->find($projectUpdateId)->current(); $form->populate($projectData->toArray()); $form->getElement('upid')->setValue($projectUpdateId); $activityLogType = Default_Model_ActivityLog::PROJECT_ITEM_EDITED; } $this->view->form = $form; if ($this->_request->isGet()) { return; } if (isset($_POST['cancel'])) { // user cancel function $this->_redirect('/member/' . $this->_authMember->member_id . '/news/'); } if (false === $form->isValid($_POST)) { // form not valid $this->view->form = $form; $this->view->error = 1; return; } $values = $form->getValues(); $projectUpdateRow = $projectTable->find($values['upid'])->current(); if (count($projectUpdateRow) == 0) { $projectUpdateRow = $projectTable->createRow($values); $projectUpdateRow->project_id = $values['upid']; $projectUpdateRow->created_at = new Zend_Db_Expr('NOW()'); $projectUpdateRow->start_date = new Zend_Db_Expr('NOW()'); $projectUpdateRow->member_id = $this->_authMember->member_id; $projectUpdateRow->creator_id = $this->_authMember->member_id; $projectUpdateRow->status = Default_Model_Project::PROJECT_ACTIVE; $projectUpdateRow->type_id = 2; $projectUpdateRow->pid = $this->_projectId; } else { $projectUpdateRow->setFromArray($values); //20180219 ronald: we set the changed_at only by new files or new updates //$projectUpdateRow->changed_at = new Zend_Db_Expr('NOW()'); } $lastId = $projectUpdateRow->save(); //New Project in Session, for AuthValidation (owner) $this->_auth->getIdentity()->projects[$lastId] = array('project_id' => $lastId); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLogValues = $projectUpdateRow->toArray(); $activityLogValues['image_small'] = $product->image_small; $activityLog = new Default_Model_ActivityLog(); //$activityLog->writeActivityLog($lastId, $projectUpdateRow->member_id, $activityLogType, $activityLogValues); $activityLog->writeActivityLog($lastId, $this->_authMember->member_id, $activityLogType, $activityLogValues); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $urlProjectShow = $helperBuildProductUrl->buildProductUrl($this->_projectId); $this->redirect($urlProjectShow); } public function previewAction() { $this->view->authMember = $this->_authMember; $form = new Default_Form_ProjectConfirm(); if ($this->_request->isGet()) { $form->populate(get_object_vars($this->_authMember)); $this->view->form = $form; $this->fetchDataForIndexView(); $this->view->preview = $this->view->render('product/index.phtml'); return; } if (isset($_POST['save'])) { $projectTable = new Default_Model_Project(); $projectTable->setStatus(Default_Model_Project::PROJECT_INACTIVE, $this->_projectId); //todo: maybe we have to delete the project data from database otherwise we produce many zombies $this->redirect('/member/' . $this->_authMember->member_id . '/products/'); } if (isset($_POST['back'])) { $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $this->redirect($helperBuildProductUrl->buildProductUrl($this->_projectId, 'edit')); } if (false === $form->isValid($_POST)) { // form not valid $this->view->form = $form; $this->fetchDataForIndexView(); $this->view->preview = $this->view->render('product/index.phtml'); $this->view->error = 1; return; } $projectTable = new Default_Model_Project(); $projectTable->setStatus(Default_Model_Project::PROJECT_ACTIVE, $this->_projectId); // add to search index $modelProject = new Default_Model_Project(); $productInfo = $modelProject->fetchProductInfo($this->_projectId); $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->addDocument($productInfo->toArray()); $this->redirect('/member/' . $this->_authMember->member_id . '/products/'); } protected function fetchDataForIndexView() { $tableProject = new Default_Model_Project(); $this->view->product = $tableProject->fetchProductInfo($this->_projectId); if (false === isset($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $desc = $this->view->product->description; $newDesc = $this->bbcode2html($desc); $this->view->product->description = $newDesc; // switch off temporally 02.05.2017 //$this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId); //$orgUpdates = $tableProjectUpdates->fetchLastProjectUpdate($this->_projectId); $tableProjectUpdates = new Default_Model_ProjectUpdates(); $orgUpdates = $tableProjectUpdates->fetchProjectUpdates($this->_projectId); $newUpdates = array(); foreach ($orgUpdates as $update) { $desc = $update['text']; $newDesc = $this->bbcode2html($desc); $update['text'] = $newDesc; $newUpdates[] = $update; } $this->view->updates = $newUpdates; // switch off temporally 02.05.2017 //$this->view->supporter = $tableProject->fetchProjectSupporter($this->_projectId); $this->view->galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId); $this->view->product_views = $tableProject->fetchProjectViews($this->_projectId); $helperFetchCategory = new Default_View_Helper_CatTitle(); $helperFetchCatParent = new Default_View_Helper_CatParent(); $this->view->catId = $this->view->product->project_category_id; $this->view->catTitle = $helperFetchCategory->catTitle($this->view->product->project_category_id); $this->view->catParentId = $helperFetchCatParent->getCatParentId(array('project_category_id' => $this->view->product->project_category_id)); if ($this->view->catParentId) { $this->view->catParentTitle = $helperFetchCategory->catTitle($this->view->catParentId); } $AuthCodeExist = new Local_Verification_WebsiteProject(); $this->view->websiteAuthCode = $AuthCodeExist->generateAuthCode(stripslashes($this->view->product->link_1)); // switch off temporally 02.05.2017 //$modelPlings = new Default_Model_DbTable_Plings(); //$this->view->plings = $modelPlings->getDonationsForProject($this->_projectId, 10); $tableMember = new Default_Model_Member(); $this->view->member = $tableMember->fetchMemberData($this->view->product->member_id); $this->view->more_products = $tableProject->fetchMoreProjects($this->view->product, 8); $this->view->more_products_otheruser = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8); $widgetDefaultModel = new Default_Model_DbTable_ProjectWidgetDefault(); $widgetDefault = $widgetDefaultModel->fetchConfig($this->_projectId); $widgetDefault->text->headline = $this->view->product->title; //$widgetDefault->amounts->current = $this->view->product->amount_received; $widgetDefault->amounts->goal = $this->view->product->amount; $widgetDefault->project = $this->_projectId; $this->view->widgetConfig = $widgetDefault; $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $this->view->permaLink = $helperBuildProductUrl->buildProductUrl($this->_projectId, null, null, true); $this->view->urlPay = $helperBuildProductUrl->buildProductUrl($this->_projectId, 'pay'); $referrerUrl = $this->readExploreUrlFromReferrer(); if (false === empty($referrerUrl)) { $this->view->referrerUrl = $referrerUrl; } } /** * transforms a string with bbcode markup into html * * @param string $txt * @param bool $nl2br * * @return string */ private function bbcode2html($txt, $nl2br = true, $forcecolor = '') { if (!empty($forcecolor)) { $fc = ' style="color:' . $forcecolor . ';"'; } else { $fc = ''; } $newtxt = htmlspecialchars($txt); if ($nl2br) { $newtxt = nl2br($newtxt); } $patterns = array( '`\[b\](.+?)\[/b\]`is', '`\[i\](.+?)\[/i\]`is', '`\[u\](.+?)\[/u\]`is', '`\[li\](.+?)\[/li\]`is', '`\[strike\](.+?)\[/strike\]`is', '`\[url\]([a-z0-9]+?://){1}([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)\[/url\]`si', '`\[quote\](.+?)\[/quote\]`is', '`\[indent](.+?)\[/indent\]`is' ); $replaces = array( '\\1', '\\1', '\\1', '\\1', '\\1', '\1\2', 'Quote:
\1
', '\\1' ); $newtxt = preg_replace($patterns, $replaces, $newtxt); return ($newtxt); } protected function readExploreUrlFromReferrer() { $helperBuildExploreUrl = new Default_View_Helper_BuildExploreUrl(); $referrerExplore = $helperBuildExploreUrl->buildExploreUrl(null, null, null, null, true); /** @var Zend_Controller_Request_Http $request */ $request = $this->getRequest(); if (strpos($request->getHeader('referer'), $referrerExplore) !== false) { return $request->getHeader('referer'); } } public function plingAction() { if (empty($this->_projectId)) { $this->redirect('/explore'); } $this->view->authMember = $this->_authMember; $this->fetchDataForIndexView(); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $this->view->urlPay = $helperBuildProductUrl->buildProductUrl($this->_projectId, 'pay'); $this->view->amount = (float)$this->getParam('amount', 1); $this->view->comment = html_entity_decode(strip_tags($this->getParam('comment'), null), ENT_QUOTES, 'utf-8'); $this->view->provider = mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'), 'utf-8'); $this->view->headTitle($this->_browserTitlePrepend . $this->view->product->title, 'SET'); $helperUserIsOwner = new Default_View_Helper_UserIsOwner(); $helperIsProjectActive = new Default_View_Helper_IsProjectActive(); if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) ) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $tableProject = new Default_Model_Project(); $this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId); } public function payAction() { $this->_helper->layout()->disableLayout(); $tableProject = new Default_Model_Project(); $project = $tableProject->fetchProductInfo($this->_projectId); //get parameter $amount = (float)$this->getParam('amount', 1); $comment = Default_Model_HtmlPurify::purify($this->getParam('comment')); $paymentProvider = mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'), 'utf-8'); $hideIdentity = (int)$this->getParam('hideId', 0); $paymentGateway = $this->createPaymentGateway($paymentProvider); $paymentGateway->getUserDataStore()->generateFromArray($project->toArray()); $requestMessage = 'Thank you for supporting: ' . $paymentGateway->getUserDataStore()->getProductTitle(); $response = null; try { $response = $paymentGateway->requestPayment($amount, $requestMessage); $this->view->checkoutEndpoint = $paymentGateway->getCheckoutEndpoint(); $this->view->paymentKey = $response->getPaymentId(); $this->_helper->viewRenderer->setRender('pay_' . $paymentProvider); } catch (Exception $e) { throw new Zend_Controller_Action_Exception('payment error', 500, $e); } if (false === $response->isSuccessful()) { throw new Zend_Controller_Action_Exception('payment failure', 500); } if (empty($this->_authMember->member_id) or ($hideIdentity == 1)) { $memberId = 1; } else { $memberId = $this->_authMember->member_id; } //Add pling $modelPlings = new Default_Model_DbTable_Plings(); $plingId = $modelPlings->createNewPlingFromResponse($response, $memberId, $project->project_id, $amount); if (false == empty($comment)) { $modelComments = new Default_Model_ProjectComments(); $dataComment = array( 'comment_type' => Default_Model_DbTable_Comments::COMMENT_TYPE_PLING, 'comment_target_id' => $project->project_id, 'comment_member_id' => $memberId, 'comment_pling_id' => $plingId, 'comment_text' => $comment ); $modelComments->save($dataComment); } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $memberId, Default_Model_ActivityLog::PROJECT_PLINGED, $project->toArray()); } /** * @param string $paymentProvider * * @return Local_Payment_GatewayInterface * @throws Exception * @throws Local_Payment_Exception * @throws Zend_Controller_Exception * @throws Zend_Exception */ protected function createPaymentGateway($paymentProvider) { $httpHost = $this->getRequest()->getHttpHost(); /** @var Zend_Config $config */ $config = Zend_Registry::get('config'); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); switch ($paymentProvider) { case 'paypal': $paymentGateway = new Default_Model_PayPal_Gateway($config->third_party->paypal); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal'); // $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal?XDEBUG_SESSION_START=1'); $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentcancel', null, true)); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok', null, true)); break; case 'dwolla': $paymentGateway = new Default_Model_Dwolla_Gateway($config->third_party->dwolla); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/dwolla'); // $paymentGateway->setIpnNotificationUrl('http://' . $_SERVER ['HTTP_HOST'] . '/gateway/dwolla?XDEBUG_SESSION_START=1'); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'dwolla', null, true)); break; case 'amazon': $paymentGateway = new Default_Model_Amazon_Gateway($config->third_party->amazon); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon'); // $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon?XDEBUG_SESSION_START=1'); $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentcancel', null, true)); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok', null, true)); break; default: throw new Zend_Controller_Exception('No known payment provider found in parameters.'); break; } return $paymentGateway; } public function dwollaAction() { $modelPling = new Default_Model_DbTable_Plings(); $plingData = $modelPling->fetchRow(array('payment_reference_key = ?' => $this->getParam('checkoutId'))); $plingData->payment_transaction_id = (int)$this->getParam('transaction'); $plingData->save(); if ($this->_getParam('status') == 'Completed') { $this->_helper->viewRenderer('paymentok'); $this->paymentokAction(); } else { $this->_helper->viewRenderer('paymentcancel'); $this->paymentcancelAction(); } } public function paymentokAction() { $this->_helper->layout()->disableLayout(); $this->view->paymentStatus = 'success'; $this->view->paymentMessage = 'Payment successful.'; $this->fetchDataForIndexView(); } public function paymentcancelAction() { $this->_helper->layout()->disableLayout(); $this->view->paymentStatus = 'danger'; $this->view->paymentMessage = 'Payment cancelled.'; $this->fetchDataForIndexView(); } public function deleteAction() { $this->_helper->layout()->setLayout('flat_ui'); $memberId = (int)$this->getParam('m'); if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id != $memberId) ) { $this->forward('products', 'user', 'default'); return; } $tableProduct = new Default_Model_Project(); $tableProduct->setDeleted($this->_authMember->member_id, $this->_projectId); $product = $tableProduct->find($this->_projectId)->current(); - // delete product from search index - $modelSearch = new Default_Model_Search_Lucene(); - $modelSearch->deleteDocument($product->toArray()); - // $command = new Backend_Commands_DeleteProductExtended($product); - // $command->doCommand(); - // $queue = Local_Queue_Factory::getQueue('search'); - // $command = new Backend_Commands_DeleteProductFromIndex($product->project_id, $product->project_category_id); - // $msg = $queue->send(serialize($command)); - // ppload // Delete collection if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $collectionResponse = $pploadApi->deleteCollection($product->ppload_collection_id); } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_DELETED, $product->toArray()); $this->forward('products', 'user', 'default'); } public function unpublishAction() { $this->_helper->layout()->setLayout('flat_ui'); $memberId = (int)$this->getParam('m'); if ( (empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id != $memberId) ) { return; } $tableProduct = new Default_Model_Project(); $tableProduct->setInActive($this->_projectId, $memberId); $product = $tableProduct->find($this->_projectId)->current(); if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) { $parentProduct = $tableProduct->find($product->pid)->current(); $product->image_small = $parentProduct->image_small; } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_UNPUBLISHED, $product->toArray()); // remove unpublished project from search index $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->deleteDocument($product); // ppload if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionRequest = array( 'category' => $product->project_category_id ); $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest); } $this->forward('products', 'user', 'default', array('member_id' => $memberId)); //$this->redirect('/member/'.$memberId.'/products'); } public function publishAction() { $memberId = (int)$this->getParam('m'); if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id != $memberId) ) { return; } $tableProduct = new Default_Model_Project(); $tableProduct->setActive($this->_authMember->member_id, $this->_projectId); $product = $tableProduct->find($this->_projectId)->current(); if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) { $parentProduct = $tableProduct->find($product->pid)->current(); $product->image_small = $parentProduct->image_small; } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_PUBLISHED, $product->toArray()); - // add published project to search index -// $productInfo = $tableProduct->fetchProductInfo($this->_projectId); -// $modelSearch = new Default_Model_Search_Lucene(); -// $modelSearch->addDocument($productInfo); - // ppload if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionRequest = array( 'category' => $product->project_category_id . '-published' ); $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest); } $this->forward('products', 'user', 'default', array('member_id' => $memberId)); //$this->redirect('/member/'.$memberId.'/products'); } public function loadratingsAction() { $this->_helper->layout->disableLayout(); $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); $ratings = $tableProjectRatings->fetchRating($this->_projectId); $this->_helper->json($ratings); } public function loadcommentAction() { $this->_helper->layout->disableLayout(); $this->view->comments = $this->loadComments(1, $this->_projectId,0); $tableProject = new Default_Model_Project(); $project = $tableProject->fetchProductInfo($this->_projectId); $this->view->product = $project; $this->view->member_id = (int)$this->_authMember->member_id; $requestResult = $this->view->render('product/partials/productCommentsUX1.phtml'); $this->_helper->json(array('status' =>'ok', 'data' => $requestResult)); } private function loadComments($page_offset, $project_id,$comment_type) { $modelComments = new Default_Model_ProjectComments(); $paginationComments = $modelComments->getCommentTreeForProject($project_id,$comment_type); $paginationComments->setItemCountPerPage(25); $paginationComments->setCurrentPageNumber($page_offset); return $paginationComments; } public function loadtagratingAction() { $this->_helper->layout->disableLayout(); //$tableProjectRatings = new Default_Model_DbTable_ProjectRating(); //$ratings = $tableProjectRatings->fetchTagRating($this->_projectId); $category_id = $this->getParam('gid'); $model = new Default_Model_ProjectTagRatings(); $ratingsLabel = $model->getCategoryTagRatings($category_id); $ratingsValue = null; if ($ratingsLabel != null && sizeof($ratingsLabel) > 0) { $ratingsValue = $model->getProjectTagRatings($this->_projectId); } $this->_helper->json(array( 'status' => 'ok', 'labels' => $ratingsLabel, 'values' => $ratingsValue )); } public function votetagratingAction() { $this->_helper->layout->disableLayout(); $vote = $this->getParam('vote'); $tag_id = $this->getParam('tid'); $msg = $this->getParam('msg'); if (strlen($msg) < 1) { $this->_helper->json(array( 'status' => 'error', 'msg' => 'Please add a comment.' )); return; }; $model = new Default_Model_ProjectTagRatings(); if ($this->_authMember->member_id) { $checkVote = $model->checkIfVote($this->_authMember->member_id, $this->_projectId, $tag_id); if (!$checkVote) { $model->doVote($this->_authMember->member_id, $this->_projectId, $tag_id, $vote, $msg); } else { if ($checkVote['vote'] == $vote) { $model->removeVote($checkVote['tag_rating_id']); } else { $model->removeVote($checkVote['tag_rating_id']); $model->doVote($this->_authMember->member_id, $this->_projectId, $tag_id, $vote, $msg); } } $this->_helper->json(array( 'status' => 'ok' )); } else { $this->_helper->json(array( 'status' => 'error', 'msg' => 'Login please' )); } } public function loadfilesjsonAction() { $this->_helper->layout->disableLayout(); // $project_id = $this->getParam('pid'); $modelProject = new Default_Model_Project(); $files = $modelProject->fetchFilesForProject($this->_projectId); $salt = PPLOAD_DOWNLOAD_SECRET; foreach ($files as &$file) { $timestamp = time() + 3600; // one hour valid $hash = hash('sha512', $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; if (null != $this->_authMember && null != $this->_authMember->member_id) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; + + $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview'); + $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload); + $file['url'] = urlencode($url); } $this->_helper->json($files); } public function loadfirstfilejsonAction() { $this->_helper->layout->disableLayout(); // $project_id = $this->getParam('pid'); $modelProject = new Default_Model_Project(); $files = $modelProject->fetchFilesForProject($this->_projectId); $salt = PPLOAD_DOWNLOAD_SECRET; $file = $files[0]; $timestamp = time() + 3600; // one hour valid $hash = hash('sha512', $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; if (null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; + + $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview'); + $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload); + $file['url'] = urlencode($url); $this->_helper->json($file); } public function loadinstallinstructionAction() { $this->_helper->layout->disableLayout(); $infomodel = new Default_Model_Info(); $text = $infomodel->getOCSInstallInstruction(); $this->_helper->json(array( 'status' => 'ok', 'data' => $text )); } public function followAction() { $this->_helper->layout()->disableLayout(); // $this->_helper->viewRenderer->setNoRender(true); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; if (array_key_exists($this->_projectId, $this->_authMember->projects)) { return; } $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id) ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectFollowTable->fetchRow($where); if (null === $result) { $projectFollowTable->createRow($newVals)->save(); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_FOLLOWED, $product->toArray()); } - - - // ppload - //Add collection to favorite - // $projectTable = new Default_Model_DbTable_Project(); - // $projectData = $projectTable->find($this->_projectId)->current(); - // if ($projectData->ppload_collection_id) { - // $pploadApi = new Ppload_Api(array( - // 'apiUri' => PPLOAD_API_URI, - // 'clientId' => PPLOAD_CLIENT_ID, - // 'secret' => PPLOAD_SECRET - // )); - // - // $favoriteRequest = array( - // 'user_id' => $this->_authMember->member_id, - // 'collection_id' => $projectData->ppload_collection_id - // ); - // - // $favoriteResponse = $pploadApi->postFavorite($favoriteRequest); - // } - } public function unfollowAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer('follow'); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id=' . $this->_projectId); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_UNFOLLOWED, $product->toArray()); - - // ppload - // Delete collection from favorite - // $projectTable = new Default_Model_DbTable_Project(); - // $projectData = $projectTable->find($this->_projectId)->current(); - // if ($projectData->ppload_collection_id) { - // $pploadApi = new Ppload_Api(array( - // 'apiUri' => PPLOAD_API_URI, - // 'clientId' => PPLOAD_CLIENT_ID, - // 'secret' => PPLOAD_SECRET - // )); - // - // $favoriteRequest = array( - // 'user_id' => $this->_authMember->member_id, - // 'collection_id' => $projectData->ppload_collection_id - // ); - // - // $favoriteResponse = - // $pploadApi->postFavorite($favoriteRequest); // This post call will retrieve existing favorite info - // if (!empty($favoriteResponse->favorite->id)) { - // $favoriteResponse = $pploadApi->deleteFavorite($favoriteResponse->favorite->id); - // } - // } } public function followpAction() { $this->_helper->layout()->disableLayout(); // $this->_helper->viewRenderer->setNoRender(true); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; if (array_key_exists($this->_projectId, $this->_authMember->projects)) { return; } $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id) ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectFollowTable->fetchRow($where); if (null === $result) { $projectFollowTable->createRow($newVals)->save(); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_FOLLOWED, $product->toArray()); } } public function unfollowpAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer('followp'); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id=' . $this->_projectId); $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_UNFOLLOWED, $product->toArray()); } public function followprojectAction() { $this->_helper->layout()->disableLayout(); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; // not allow to pling himself if (array_key_exists($this->_projectId, $this->_authMember->projects)) { $this->_helper->json(array( 'status' => 'error', 'msg' => 'not allowed' )); return; } $projectFollowTable = new Default_Model_DbTable_ProjectFollower(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id) ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectFollowTable->fetchRow($where); if (null === $result) { $projectFollowTable->createRow($newVals)->save(); $this->logActivity(Default_Model_ActivityLog::PROJECT_FOLLOWED); $cnt = $projectFollowTable->countForProject($this->_projectId); $this->_helper->json(array( 'status' => 'ok', 'msg' => 'Success.', 'cnt' => $cnt, 'action' => 'insert' )); } else { $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id=' . $this->_projectId); $this->logActivity(Default_Model_ActivityLog::PROJECT_UNFOLLOWED); $cnt = $projectFollowTable->countForProject($this->_projectId); $this->_helper->json(array( 'status' => 'ok', 'msg' => 'Success.', 'cnt' => $cnt, 'action' => 'delete' )); } } protected function logActivity($logId) { $tableProduct = new Default_Model_Project(); $product = $tableProduct->find($this->_projectId)->current(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, $logId, $product->toArray()); } public function plingprojectAction() { $this->_helper->layout()->disableLayout(); $this->view->project_id = $this->_projectId; $this->view->authMember = $this->_authMember; // not allow to pling himself if (array_key_exists($this->_projectId, $this->_authMember->projects)) { $this->_helper->json(array( 'status' => 'error', 'msg' => 'not allowed' )); return; } // not allow to pling if not supporter $helperIsSupporter = new Default_View_Helper_IsSupporter(); if (!$helperIsSupporter->isSupporter($this->_authMember->member_id)) { $this->_helper->json(array( 'status' => 'error', 'msg' => 'become a supporter first please. ' )); return; } $projectplings = new Default_Model_ProjectPlings(); $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id); $sql = $projectplings->select() ->where('member_id = ?', $this->_authMember->member_id) ->where('is_deleted = ?', 0) ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectplings->fetchRow($sql); if (null === $result) { $projectplings->createRow($newVals)->save(); //$this->logActivity(Default_Model_ActivityLog::PROJECT_PLINGED_2); $cnt = $projectplings->getPlingsAmount($this->_projectId); $this->_helper->json(array( 'status' => 'ok', 'msg' => 'Success.', 'cnt' => $cnt, 'action' => 'insert' )); } else { // delete pling $projectplings->setDelete($result->project_plings_id); //$this->logActivity(Default_Model_ActivityLog::PROJECT_DISPLINGED_2); $cnt = $projectplings->getPlingsAmount($this->_projectId); $this->_helper->json(array( 'status' => 'ok', 'msg' => 'Success.', 'cnt' => $cnt, 'action' => 'delete' )); } } /** * * public function unplingprojectAction() * { * $this->_helper->layout()->disableLayout(); * * $projectplings = new Default_Model_ProjectPlings(); * $pling = $projectplings->getPling($this->_projectId,$this->_authMember->member_id); * * if($pling) * { * $projectplings->setDelete($pling->project_plings_id); * $cnt = count($projectplings->getPlings($this->_projectId)); * $this->_helper->json(array( * 'status' => 'ok', * 'deleted' => $pling->project_plings_id, * 'msg' => 'Success. ', * 'cnt' => $cnt * )); * * $tableProduct = new Default_Model_Project(); * $product = $tableProduct->find($this->_projectId)->current(); * * $activityLog = new Default_Model_ActivityLog(); * $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, * Default_Model_ActivityLog::PROJECT_DISPLINGED_2, $product->toArray()); * }else{ * $this->_helper->json(array( * 'status' => 'error', * 'msg' => 'not existing.' * )); * } * * * } **/ public function followsAction() { $projectFollowTable = new Default_Model_Member(); $memberId = $this->_authMember->member_id; $this->view->productList = $projectFollowTable->fetchFollowedProjects($memberId); $projectArray = $this->generateFollowedProjectsViewData($this->view->productList); $this->view->productArray['followedProjects'] = $projectArray; } /** * @param $list * * @return array */ protected function generateFollowedProjectsViewData($list) { $viewArray = array(); if (count($list) == 0) { return $viewArray; } $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); foreach ($list as $element) { $arr = array(); $arr['id'] = $element->project_id; $arr['name'] = $element->title; $arr['image'] = $element->image_small; $arr['url'] = $helperBuildProductUrl->buildProductUrl($element->project_id); $arr['urlUnFollow'] = $helperBuildProductUrl->buildProductUrl($element->project_id, 'unfollow'); #$arr['showUrlUnFollow'] = $this->view->isMember; $viewArray[] = $arr; } return $viewArray; } public function verifycodeAction() { $this->_helper->layout()->disableLayout(); if ($this->_request->isXmlHttpRequest()) { $tabProject = new Default_Model_DbTable_Project(); $dataProject = $tabProject->find($this->_projectId)->current(); $this->createTaskWebsiteOwnerVerification($dataProject); $this->view->message = 'Your product page is stored for validation.'; return; } $this->view->message = 'This service is not available at the moment. Please try again later.'; } /** * @param $projectData * * @throws Zend_Exception * @throws Zend_Queue_Exception */ protected function createTaskWebsiteOwnerVerification($projectData) { if (empty($projectData->link_1)) { return; } $checkAuthCode = new Local_Verification_WebsiteProject(); $authCode = $checkAuthCode->generateAuthCode(stripslashes($projectData->link_1)); $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_CheckProjectWebsite($projectData->project_id, $projectData->link_1, $authCode); $queue->send(serialize($command)); } /** * @throws Zend_Controller_Action_Exception * @deprecated */ public function fetchAction() { $this->_helper->layout()->disableLayout(); if ($this->_request->isXmlHttpRequest()) { $this->view->authMember = $this->_authMember; $this->fetchDataForIndexView(); $tableProject = new Default_Model_Project(); $this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId); if (false === isset($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $helperUserIsOwner = new Default_View_Helper_UserIsOwner(); $helperIsProjectActive = new Default_View_Helper_IsProjectActive(); - if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) AND (false - === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) + if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) + AND + (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) ) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $tablePageViews = new Default_Model_DbTable_StatPageViews(); $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), $this->_authMember->member_id); } $this->_helper->json(get_object_vars($this->view)); } public function claimAction() { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); if ($productInfo->claimable != Default_Model_Project::PROJECT_CLAIMABLE) { throw new Zend_Controller_Action_Exception('Method not available', 404); } $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); if (empty($productInfo->claimed_by_member)) { $modelProduct->setClaimedByMember($this->_authMember->member_id, $this->_projectId); $claimMail = new Default_Plugin_SendMail('tpl_mail_claim_product'); $claimMail->setTemplateVar('sender', $this->_authMember->mail); $claimMail->setTemplateVar('productid', $productInfo->project_id); $claimMail->setTemplateVar('producttitle', $productInfo->title); $claimMail->setTemplateVar('userid', $this->_authMember->member_id); $claimMail->setTemplateVar('username', $this->_authMember->username); $claimMail->setTemplateVar('usermail', $this->_authMember->mail); $claimMail->setReceiverMail(array('contact@opendesktop.org')); $claimMail->send(); $claimMailConfirm = new Default_Plugin_SendMail('tpl_mail_claim_confirm'); $claimMailConfirm->setTemplateVar('sender', 'contact@opendesktop.org'); $claimMailConfirm->setTemplateVar('producttitle', $productInfo->title); $claimMailConfirm->setTemplateVar('productlink', 'http://' . $this->getRequest()->getHttpHost() . $helperBuildProductUrl->buildProductUrl($productInfo->project_id)); $claimMailConfirm->setTemplateVar('username', $this->_authMember->username); $claimMailConfirm->setReceiverMail($this->_authMember->mail); $claimMailConfirm->send(); } $this->_helper->viewRenderer('index'); $this->indexAction(); } public function makerconfigAction() { $this->_helper->layout()->disableLayout(); $widgetProjectId = (int)$this->getParam('project_id'); if (false == isset($widgetProjectId)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $widgetDefaultModel = new Default_Model_DbTable_ProjectWidgetDefault(); $widgetDefault = $widgetDefaultModel->fetchConfig($widgetProjectId); if (!isset($widgetDefault)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } else { $this->view->widgetConfig = $widgetDefault; $productModel = new Default_Model_Project(); $this->view->product = $productModel->fetchProductDataFromMV($widgetProjectId); $this->view->supporting = $productModel->fetchProjectSupporterWithPlings($widgetProjectId); $plingModel = new Default_Model_DbTable_Plings(); $this->view->comments = $plingModel->getCommentsForProject($widgetProjectId, 10); $websiteOwner = new Local_Verification_WebsiteProject(); $this->view->authCode = ''; } } /** * ppload */ public function addpploadfileAction() { $this->_helper->layout()->disableLayout(); $log = Zend_Registry::get('logger'); $log->debug('**********' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); $error_text = ''; // Add file to ppload collection if (!empty($_FILES['file_upload']['tmp_name']) && $_FILES['file_upload']['error'] == UPLOAD_ERR_OK ) { $tmpFilename = dirname($_FILES['file_upload']['tmp_name']) . '/' . basename($_FILES['file_upload']['name']); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($tmpFilename, true) . "\n"); move_uploaded_file($_FILES['file_upload']['tmp_name'], $tmpFilename); $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $fileRequest = array( 'file' => $tmpFilename, 'owner_id' => $this->_authMember->member_id ); //Admins can upload files for users $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $member_id = $projectData->member_id; $fileRequest = array( 'file' => $tmpFilename, 'owner_id' => $member_id ); } if ($projectData->ppload_collection_id) { // Append to existing collection $fileRequest['collection_id'] = $projectData->ppload_collection_id; } //if (isset($_POST['file_description'])) { // $fileRequest['description'] = mb_substr($_POST['file_description'], 0, 140); //} $fileResponse = $pploadApi->postFile($fileRequest); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($fileResponse, true) . "\n"); unlink($tmpFilename); if (!empty($fileResponse->file->collection_id)) { if (!$projectData->ppload_collection_id) { // Save collection ID $projectData->ppload_collection_id = $fileResponse->file->collection_id; //20180219 ronald: we set the changed_at only by new files or new updates if ((int)$this->_authMember->member_id == (int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); } $projectData->ghns_excluded = 0; $projectData->save(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $projectData->member_id, Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray()); // Update profile information $memberTable = new Default_Model_DbTable_Member(); $memberSettings = $memberTable->find($this->_authMember->member_id)->current(); $mainproject = $projectTable->find($memberSettings->main_project_id)->current(); $profileName = ''; if ($memberSettings->firstname || $memberSettings->lastname ) { $profileName = trim($memberSettings->firstname . ' ' . $memberSettings->lastname); } else { if ($memberSettings->username) { $profileName = $memberSettings->username; } } $profileRequest = array( 'owner_id' => $this->_authMember->member_id, 'name' => $profileName, 'email' => $memberSettings->mail, 'homepage' => $memberSettings->link_website, 'description' => $mainproject->description ); $profileResponse = $pploadApi->postProfile($profileRequest); // Update collection information $collectionCategory = $projectData->project_category_id; if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) { $collectionCategory .= '-published'; } $collectionRequest = array( 'title' => $projectData->title, 'description' => $projectData->description, 'category' => $collectionCategory, 'content_id' => $projectData->project_id ); $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest); // Store product image as collection thumbnail $this->_updatePploadMediaCollectionthumbnail($projectData); } else { //20180219 ronald: we set the changed_at only by new files or new updates if ((int)$this->_authMember->member_id == (int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); } $projectData->ghns_excluded = 0; $projectData->save(); } //If this file is a video, we have to convert it for preview if (!empty($fileResponse->file->type) && in_array($fileResponse->file->type, Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES)) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_ConvertVideo($projectData->ppload_collection_id, $fileResponse->file->id, $fileResponse->file->type); $queue->send(serialize($command)); } //If this file is bigger than XXX MB (see application.ini), then create a webtorrent file $config = Zend_Registry::get('config'); $minFileSize = $config->torrent->media->min_filesize; if (!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_CreateTorrent($fileResponse->file); $queue->send(serialize($command)); } //If this is a cbr or cbz comic archive, then start an extracting job if ($this->endsWith($fileResponse->file->name, '.cbr') || $this->endsWith($fileResponse->file->name, '.cbz')) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_ExtractComic($fileResponse->file); $queue->send(serialize($command)); } $this->_helper->json(array( 'status' => 'ok', 'file' => $fileResponse->file )); return; } } $log->debug('********** END ' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } private function endsWith($haystack, $needle) { return $needle === "" || substr(strtolower($haystack), -strlen($needle)) === strtolower($needle); } /** * ppload */ public function updatepploadfileAction() { $this->_helper->layout()->disableLayout(); $log = Zend_Registry::get('logger'); $log->debug('**********' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); $error_text = ''; // Update a file in ppload collection if (!empty($_POST['file_id'])) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $fileResponse = $pploadApi->getFile($_POST['file_id']); if (isset($fileResponse->file->collection_id) && $fileResponse->file->collection_id == $projectData->ppload_collection_id ) { $fileRequest = array(); $tmpFilename = ''; if (!empty($_FILES['file_upload']['tmp_name']) && $_FILES['file_upload']['error'] == UPLOAD_ERR_OK ) { $tmpFilename = dirname($_FILES['file_upload']['tmp_name']) . '/' . basename($_FILES['file_upload']['name']); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($tmpFilename, true) . "\n"); move_uploaded_file($_FILES['file_upload']['tmp_name'], $tmpFilename); $fileRequest['file'] = $tmpFilename; //20180219 ronald: we set the changed_at only by new files or new updates if ((int)$this->_authMember->member_id == (int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); } $projectData->ghns_excluded = 0; $projectData->save(); } if (isset($_POST['file_description'])) { $fileRequest['description'] = mb_substr($_POST['file_description'], 0, 140); } if (isset($_POST['file_category'])) { $fileRequest['category'] = $_POST['file_category']; } if (isset($_POST['file_tags'])) { $fileRequest['tags'] = $_POST['file_tags']; } if (isset($_POST['ocs_compatible'])) { $fileRequest['ocs_compatible'] = $_POST['ocs_compatible']; } if (isset($_POST['file_version'])) { $fileRequest['version'] = $_POST['file_version']; } $fileResponse = $pploadApi->putFile($_POST['file_id'], $fileRequest); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($fileResponse, true) . "\n"); if ($tmpFilename) { unlink($tmpFilename); } if (isset($fileResponse->status) && $fileResponse->status == 'success' ) { //If this file is bigger than XXX MB (see application.ini), then create a webtorrent file $config = Zend_Registry::get('config'); $minFileSize = $config->torrent->media->min_filesize; if (!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_CreateTorrent($fileResponse->file); $queue->send(serialize($command)); } $this->_helper->json(array( 'status' => 'ok', 'file' => $fileResponse->file )); return; } else { $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse) . '; $fileResponse->status: ' . $fileResponse->status; } } else { $error_text .= 'PPload Response: ' . json_encode($fileResponse) . '; fileResponse->file->collection_id: ' . $fileResponse->file->collection_id . ' != $projectData->ppload_collection_id: ' . $projectData->ppload_collection_id; } } else { $error_text .= 'No CollectionId or no FileId. CollectionId: ' . $projectData->ppload_collection_id . ', FileId: ' . $_POST['file_id']; } $log->debug('********** END ' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function updatefiletagAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $tagId = null; if (isset($_POST['tag_id'])) { $tagId = $_POST['tag_id']; } $tagGroupId = null; if (isset($_POST['tag_group_id'])) { $tagGroupId = $_POST['tag_group_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->saveFileTagForProjectAndTagGroup($this->_projectId, $_POST['file_id'], $tagId, $tagGroupId); $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function deletefiletagAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $tagId = null; if (isset($_POST['tag_id'])) { $tagId = $_POST['tag_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->deleteFileTagForProject($this->_projectId, $_POST['file_id'], $tagId); $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function updatecompatibleAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $typeId = null; if (isset($_POST['is_compatible'])) { $is_compatible = $_POST['is_compatible']; } return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function startdownloadAction() { $this->_helper->layout()->disableLayout(); /** * Save Download-Data in Member_Download_History */ $file_id = $this->getParam('file_id'); $file_type = $this->getParam('file_type'); $file_name = $this->getParam('file_name'); $file_size = $this->getParam('file_size'); $projectId = $this->_projectId; $this->redirect('/dl?file_id=' . $file_id . '&file_type=' . $file_type . '&file_name=' . $file_name . '&file_size=' . $file_size . '&project_id=' . $projectId); - - -// if ($_SERVER['REQUEST_METHOD'] == 'POST') { - /* if(isset($file_id) && isset($projectId) && isset($memberId)) { - $memberDlHistory = new Default_Model_DbTable_MemberDownloadHistory(); - $data = array('project_id' => $projectId, 'member_id' => $memberId, 'file_id' => $file_id, 'file_type' => $file_type, 'file_name' => $file_name, 'file_size' => $file_size); - $memberDlHistory->createRow($data)->save(); - } - - $url = urldecode($urltring); - $this->redirect($url); - * - */ -// } else { -// $this->redirect('/ads?file_id='.$file_id); -// } } - /** - * ppload - */ - /*public function deletepploadcollectionAction() - { - $this->_helper->layout()->disableLayout(); - - $projectTable = new Default_Model_DbTable_Project(); - $projectData = $projectTable->find($this->_projectId)->current(); - - // Delete ppload collection - if ($projectData->ppload_collection_id) { - $pploadApi = new Ppload_Api(array( - 'apiUri' => PPLOAD_API_URI, - 'clientId' => PPLOAD_CLIENT_ID, - 'secret' => PPLOAD_SECRET - )); - - $collectionResponse = $pploadApi->deleteCollection($projectData->ppload_collection_id); - - if (isset($collectionResponse->status) - && $collectionResponse->status == 'success' - ) { - $projectData->ppload_collection_id = null; - $projectData->changed_at = new Zend_Db_Expr('NOW()'); - $projectData->save(); - - $activityLog = new Default_Model_ActivityLog(); - $activityLog->writeActivityLog( - $this->_projectId, - $projectData->member_id, - Default_Model_ActivityLog::PROJECT_EDITED, - $projectData->toArray() - ); - - $this->_helper->json(array('status' => 'ok')); - return; - } - } - - $this->_helper->json(array('status' => 'error')); - }*/ /** * ppload */ public function deletepploadfileAction() { $this->_helper->layout()->disableLayout(); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); $error_text = ''; // Delete file from ppload collection if (!empty($_POST['file_id'])) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $fileResponse = $pploadApi->getFile($_POST['file_id']); if (isset($fileResponse->file->collection_id) && $fileResponse->file->collection_id == $projectData->ppload_collection_id ) { $fileResponse = $pploadApi->deleteFile($_POST['file_id']); if (isset($fileResponse->status) && $fileResponse->status == 'success' ) { $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse); } } } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } /** * ppload */ public function deletepploadfilesAction() { $this->_helper->layout()->disableLayout(); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); // Delete all files in ppload collection if ($projectData->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $filesRequest = array( 'collection_id' => $projectData->ppload_collection_id, 'perpage' => 1000 ); $filesResponse = $pploadApi->getFiles($filesRequest); if (isset($filesResponse->status) && $filesResponse->status == 'success' ) { foreach ($filesResponse->files as $file) { $fileResponse = $pploadApi->deleteFile($file->id); if (!isset($fileResponse->status) || $fileResponse->status != 'success' ) { $this->_helper->json(array('status' => 'error')); return; } } } $this->_helper->json(array('status' => 'ok')); return; } $this->_helper->json(array('status' => 'error')); } public function saveproductAction() { $form = new Default_Form_Product(); // we don't need to test a file which doesn't exist in this case. The Framework stumbles if $_FILES is empty. if ($this->_request->isXmlHttpRequest() AND (count($_FILES) == 0)) { $form->removeElement('image_small_upload'); // $form->removeElement('image_big_upload'); $form->removeSubForm('gallery'); $form->removeElement('project_id'); //(workaround: Some Browsers send "0" in some cases.) } if (false === $form->isValid($_POST)) { $errors = $form->getMessages(); $messages = $this->getErrorMessages($errors); $this->_helper->json(array('status' => 'error', 'messages' => $messages)); } $formValues = $form->getValues(); $formValues['status'] = Default_Model_Project::PROJECT_INCOMPLETE; $modelProject = new Default_Model_Project(); $newProject = $modelProject->createProject($this->_authMember->member_id, $formValues, $this->_authMember->username); //$this->createSystemPlingForNewProject($newProject->project_id); //New Project in Session, for AuthValidation (owner) $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id); $this->_helper->json(array('status' => 'ok', 'project_id' => $newProject->project_id)); } /** * @param $errors * * @return array */ protected function getErrorMessages($errors) { $messages = array(); foreach ($errors as $element => $row) { if (!empty($row) && $element != 'submit') { foreach ($row as $validator => $message) { $messages[$element][] = $message; } } } return $messages; } public function searchAction() { // Filter-Parameter $params = $this->getAllParams(); $filterInput = new Zend_Filter_Input( array( '*' => 'StringTrim', 'projectSearchText' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), 'page' => 'digits', 'pci' => 'digits', 'ls' => 'digits', 't' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), 'pkg' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), 'lic' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'), 'arch' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags') ), array( 'projectSearchText' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'presence' => 'required' ), 'page' => array('digits', 'default' => '1'), 'f' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), //new Zend_Validate_InArray(array('f'=>'tags')), 'allowEmpty' => true ), 'pci' => array( 'digits', 'allowEmpty' => true ), 'ls' => array( 'digits', 'allowEmpty' => true ), 't' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'allowEmpty' => true ), 'pkg' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'allowEmpty' => true ), 'lic' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'allowEmpty' => true ), 'arch' => array( new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)), 'allowEmpty' => true ) ), $params); if ($filterInput->hasInvalid()) { $this->_helper->flashMessenger->addMessage('

There was an error. Please check your input and try again.

'); return; } $this->view->searchText = $filterInput->getEscaped('projectSearchText'); $this->view->page = $filterInput->getEscaped('page'); $this->view->searchField = $filterInput->getEscaped('f'); $this->view->pci = $filterInput->getEscaped('pci'); $this->view->ls = $filterInput->getEscaped('ls'); $this->view->t = $filterInput->getEscaped('t'); $this->view->pkg = $filterInput->getEscaped('pkg'); $this->view->arch = $filterInput->getEscaped('arch'); $this->view->lic = $filterInput->getEscaped('lic'); $this->view->store = $this->getParam('domain_store_id'); if (isset($params['isJson'])) { $this->_helper->layout()->disableLayout(); $filterScore = $this->view->ls ? 'laplace_score:[' . $this->view->ls . ' TO ' . ($this->view->ls + 9) . ']' : null; $filterCat = $this->view->pci ? 'project_category_id:(' . $this->view->pci . ')' : null; $filterTags = $this->view->t ? 'tags:(' . $this->view->t . ')' : null; $filterPkg = $this->view->pkg ? 'package_names:(' . $this->view->pkg . ')' : null; $filterArch = $this->view->arch ? 'arch_names:(' . $this->view->arch . ')' : null; $filterLic = $this->view->lic ? 'license_names:(' . $this->view->lic . ')' : null; // $param = array('q' => $this->view->searchText ,'store'=>$this->view->store,'page' => $this->view->page // , 'count' => 10, 'qf' => $this->view->searchField, 'fq' => array($filterCat, $filterScore, $filterTags,$filterPkg,$filterArch,$filterLic)); $param = array( 'q' => 'test', 'store' => null, 'page' => 1 , 'count' => 10 ); $viewHelperImage = new Default_View_Helper_Image(); $modelSearch = new Default_Model_Solr(); try { $result = $modelSearch->search($param); $products = $result['hits']; // var_dump($products); // die; $ps = array(); foreach ($products as $p) { $img = $viewHelperImage->Image($p->image_small, array( 'width' => 50, 'height' => 50 )); $ps[] = array( 'description' => $p->description , 'title' => $p->title , 'project_id' => $p->project_id , 'member_id' => $p->member_id , 'username' => $p->username , 'laplace_score' => $p->laplace_score , 'score' => $p->score , 'image_small' => $img ); } $this->_helper->json(array( 'status' => 'ok', 'products' => $ps, 'q' => $param )); } catch (Exception $e) { $this->_helper->json(array( 'status' => 'err', 'msg' => 'Not Found! Try again.' )); } } } public function startmediaviewajaxAction() { return $this->startvideoajaxAction(); } public function startvideoajaxAction() { $this->_helper->layout()->disableLayout(); $collection_id = null; $file_id = null; $memberId = $this->_authMember->member_id; $media_view_type_id = $this->getParam('type_id'); if (!$media_view_type_id) { // default $media_view_type_id = Default_Model_DbTable_MediaViews::MEDIA_TYPE_VIDEO; } if ($this->hasParam('collection_id') && $this->hasParam('file_id')) { $collection_id = $this->getParam('collection_id'); $file_id = $this->getParam('file_id'); $id = null; //Log media view try { $mediaviewsTable = new Default_Model_DbTable_MediaViews(); $id = $mediaviewsTable->getNewId(); $data = array( 'media_view_id' => $id, 'media_view_type_id' => $media_view_type_id, 'project_id' => $this->_projectId, 'collection_id' => $collection_id, 'file_id' => $file_id, 'start_timestamp' => new Zend_Db_Expr ('Now()'), 'ip' => $this->getRealIpAddr(), 'referer' => $this->getReferer() ); if (!empty($memberId)) { $data['member_id'] = $memberId; } $data['source'] = 'OCS-Webserver'; $mediaviewsTable->createRow($data)->save(); } catch (Exception $exc) { //echo $exc->getTraceAsString(); $errorLog = Zend_Registry::get('logger'); $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); } $this->_helper->json(array('status' => 'success', 'MediaViewId' => $id)); return; } $this->_helper->json(array('status' => 'error')); } function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } function getReferer() { $referer = null; if (!empty($_SERVER['HTTP_REFERER'])) { $referer = $_SERVER['HTTP_REFERER']; } return $referer; } public function stopmediaviewajaxAction() { return $this->stopvideoajaxAction(); } public function stopvideoajaxAction() { $this->_helper->layout()->disableLayout(); $view_id = null; if ($this->hasParam('media_view_id')) { $view_id = $this->getParam('media_view_id'); //Log media view stop try { $mediaviewsTable = new Default_Model_DbTable_MediaViews(); $data = array('stop_timestamp' => new Zend_Db_Expr ('Now()')); $mediaviewsTable->update($data, 'media_view_id = ' . $view_id); } catch (Exception $exc) { //echo $exc->getTraceAsString(); $errorLog = Zend_Registry::get('logger'); $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); } $this->_helper->json(array('status' => 'success', 'MediaViewId' => $view_id)); return; } $this->_helper->json(array('status' => 'error')); } protected function createPling($member_id, $project_id) { $projectplings = new Default_Model_ProjectPlings(); $newVals = array('project_id' => $project_id, 'member_id' => $member_id); $sql = $projectplings->select() ->where('member_id = ?', $this->_authMember->member_id) ->where('is_deleted = ?', 0) ->where('project_id = ?', $this->_projectId, 'INTEGER'); $result = $projectplings->fetchRow($sql); if (null === $result) { $projectplings->createRow($newVals)->save(); } } /** * @param $memberId * * @throws Zend_Db_Table_Exception */ protected function setViewDataForMyProducts($memberId) { $tableMember = new Default_Model_Member(); $this->view->member = $tableMember->find($memberId)->current(); $tableProduct = new Default_Model_Project(); $this->view->products = $tableProduct->fetchAllProjectsForMember($memberId); } protected function _initResponseHeader() { $duration = 1800; // in seconds $expires = gmdate("D, d M Y H:i:s", time() + $duration) . " GMT"; $this->getResponse()->setHeader('X-FRAME-OPTIONS', 'ALLOWALL', true)// ->setHeader('Last-Modified', $modifiedTime, true) ->setHeader('Expires', $expires, true)->setHeader('Pragma', 'no-cache', true) ->setHeader('Cache-Control', 'private, no-cache, must-revalidate', true); } /** * @param $hits * * @return array */ protected function generateProjectsArrayForView($hits) { $viewArray = array(); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); /** @var $hit Zend_Search_Lucene_Search_QueryHit */ foreach ($hits as $hit) { $project = $hit->getDocument(); if (null != $project->username) { $isUpdate = ($project->type_id == 2); if ($isUpdate) { $showUrl = $helperBuildProductUrl->buildProductUrl($project->pid) . '#anker_' . $project->project_id; $plingUrl = $helperBuildProductUrl->buildProductUrl($project->pid, 'pling'); } else { $showUrl = $helperBuildProductUrl->buildProductUrl($project->project_id); $plingUrl = $helperBuildProductUrl->buildProductUrl($project->project_id, 'pling'); } $projectArr = array( 'score' => $hit->score, 'id' => $project->project_id, 'type_id' => $project->type_id, 'title' => $project->title, 'description' => $project->description, 'image' => $project->image_small, 'plings' => 0, 'urlGoal' => $showUrl, 'urlPling' => $plingUrl, 'showUrlPling' => ($project->paypal_mail != null), 'member' => array( 'name' => $project->username, 'url' => 'member/' . $project->member_id, 'image' => $project->profile_image_url, 'id' => $project->member_id ) ); $viewArray[] = $projectArr; } } return $viewArray; } protected function setLayout() { $layoutName = 'flat_ui_template'; $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; if ($storeConfig && $storeConfig->layout_pagedetail) { $this->_helper->layout()->setLayout($storeConfig->layout_pagedetail); } else { $this->_helper->layout()->setLayout($layoutName); } } private function getFileDownloadCount($collection_id, $fileId) { $modelFiles = new Default_Model_DbTable_PploadFiles(); $countAll = $modelFiles->fetchCountDownloadsForFileAllTime($collection_id, $fileId); $countToday = $modelFiles->fetchCountDownloadsForFileToday($collection_id, $fileId); $count = (int)$countAll + (int)$countToday; return $count; } } diff --git a/application/modules/default/models/Jwt.php b/application/modules/default/models/Jwt.php index a47d3a4ed..e70f03b09 100644 --- a/application/modules/default/models/Jwt.php +++ b/application/modules/default/models/Jwt.php @@ -1,64 +1,72 @@ . * * Created: 10.10.2018 */ class Default_Model_Jwt { public static function encode($member_id) { $config = Zend_Registry::get('config')->settings->jwt; $member_data = self::getMemberData($member_id); $payload = self::buildPayload($member_data, $config); return JWT::encode($payload, $config->secret, $algo = 'HS256'); } private static function getMemberData($member_id) { $model = new Default_Model_Member(); return $model->fetchMemberData($member_id)->toArray(); } private static function buildPayload($member_data, $config) { $date = new DateTime(); $interval = DateInterval::createFromDateString($config->expire->cookie); $payload['exp'] = $date->add($interval)->getTimestamp(); $payload['vt'] = 4; //type=cookie_ltat $payload['user'] = $member_data['external_id']; $payload['hash'] = crc32($member_data['username'] . $member_data['mail'] . $member_data['password']); return $payload; } public static function decode($jwt, $verify = true) { $config = Zend_Registry::get('config')->settings->jwt; return JWT::decode($jwt, $config->secret, $verify); } + + public static function encodeFromArray(array $payload) + { + $config = Zend_Registry::get('config')->settings->jwt; + + return JWT::encode($payload, $config->secret, $algo = 'HS256'); + } + } \ No newline at end of file diff --git a/application/modules/default/models/PpLoad.php b/application/modules/default/models/PpLoad.php index f23bf25e4..fcafa7adb 100644 --- a/application/modules/default/models/PpLoad.php +++ b/application/modules/default/models/PpLoad.php @@ -1,148 +1,205 @@ . * * Created: 26.01.2017 */ class Default_Model_PpLoad { /** * @inheritDoc */ public function __construct() { } - public function isAuthmemberProjectCreator($creator_id) + public static function createDownloadUrl($collection_id, $file_name, array $params) { - $auth = Zend_Auth::getInstance(); - $authMember = $auth->getStorage()->read(); - if($authMember->member_id == $creator_id) - { - return true; + $valid_until = time() + 3600; // one hour valid + $hash = self::createDownloadHash($collection_id, $valid_until); + $url = PPLOAD_API_URI . 'files/download'; + foreach ($params as $key => $param) { + $url .= '/' . $key . '/' . $param; } - return false; + + return $url . '/s/' . $hash . '/t/' . $valid_until . '/' . $file_name; + } + + /** + * @param int $collection_id + * @param int $valid_until + * @return string + */ + public static function createDownloadHash($collection_id, $valid_until) + { + return hash('sha512', + PPLOAD_DOWNLOAD_SECRET . $collection_id . $valid_until); // order isn't important at all... just do the same when verifying } + /** + * @param int $collection_id + * @param string $file_name + * @param array $payload + * @return string + */ + public static function createDownloadUrlJwt($collection_id, $file_name, array $payload) + { + $valid_until = time() + 3600; // one hour valid + $hash = self::createDownloadHash($collection_id, $valid_until); + $payload['s'] = $hash; + $payload['t'] = $valid_until; + try { + $session = new Zend_Session_Namespace(); + $payload['stfp'] = $session->stat_fp; + $payload['stip'] = $session->stat_ipv6 ? $session->stat_ipv6 : $session->stat_ipv4; + } catch (Zend_Session_Exception $e) { + Zend_Registry::get('logger')->err(__METHOD__ . ' ' . $e->getMessage()); +// error_log(__METHOD__ . ' ' . $e->getMessage()); + } + $jwt = Default_Model_Jwt::encodeFromArray($payload); + + return PPLOAD_API_URI . 'files/download/j/' . $jwt . '/' . $file_name; + } + + /** + * @param int $projectId + * @param string $url + * @param string $filename + * @param string $fileDescription + * @return bool|mixed + * @throws Zend_Auth_Storage_Exception + * @throws Zend_Exception + */ public function uploadEmptyFileWithLink($projectId, $url, $filename, $fileDescription) { $projectId = (int)$projectId; $projectData = $this->getProjectData($projectId); if (empty($projectData)) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ppload upload error. no project data found. project_id:' - . $projectId) - ; + . $projectId); return false; } $pploadApi = $this->getPpLoadApi(); // create empty text file - // $fileDummy = '/dev/null'; $fileDummy = '../../data/files/empty'; $fileRequest = array( // 'file' => $fileDummy, 'local_file_path' => $fileDummy, 'local_file_name' => $filename, 'owner_id' => $projectData->member_id, 'tags' => 'link##' . urlencode($url) ); if ($projectData->ppload_collection_id) { // Append to existing collection $fileRequest['collection_id'] = $projectData->ppload_collection_id; } if (false == empty($fileDescription)) { $fileRequest['description'] = mb_substr($fileDescription, 0, 140); } //upload to ppload $fileResponse = $pploadApi->postFile($fileRequest); Zend_Registry::get('logger')->debug(__METHOD__ . ' - fileResponse: ' . print_r($fileResponse, true)); if (empty($fileResponse) OR empty($fileResponse->file) OR $fileResponse->status <> 'success') { - Zend_Registry::get('logger')->err(__METHOD__ . ' - ppload upload error. requestData:' - . print_r($fileRequest, true) . "\n" . 'response:' . print_r($fileResponse, true)) - ; + Zend_Registry::get('logger')->err(__METHOD__ + . ' - ppload upload error. requestData:' + . print_r($fileRequest, true) . "\n" . 'response:' + . print_r($fileResponse, true) + ); return false; } $log = Zend_Registry::get('logger'); if ($projectData->ppload_collection_id <> $fileResponse->file->collection_id) { $projectData->ppload_collection_id = $fileResponse->file->collection_id; - if($this->isAuthmemberProjectCreator($projectData->member_id)) - { + if ($this->isAuthmemberProjectCreator($projectData->member_id)) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { $auth = Zend_Auth::getInstance(); $authMember = $auth->getStorage()->read(); - $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); + $log->info('********** ' . __METHOD__ . ' Project ChangedAt is not set: Auth-Member (' . $authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); } $projectData->save(); - }else - { - if($this->isAuthmemberProjectCreator($projectData->member_id)) - { + } else { + if ($this->isAuthmemberProjectCreator($projectData->member_id)) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); $projectData->save(); } else { $auth = Zend_Auth::getInstance(); $authMember = $auth->getStorage()->read(); - $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); + $log->info('********** ' . __METHOD__ . ' Project ChangedAt is not set: Auth-Member (' . $authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n"); } } return $fileResponse; } /** - * @param $projectId + * @param int $projectId * * @return Zend_Db_Table_Row_Abstract + * @throws Zend_Db_Table_Exception */ protected function getProjectData($projectId) { $projectTable = new Default_Model_DbTable_Project(); - $projectData = $projectTable->find($projectId)->current(); - return $projectData; + return $projectTable->find($projectId)->current(); } /** * @return Ppload_Api */ protected function getPpLoadApi() { - $pploadApi = new Ppload_Api(array( + return new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); + } + + /** + * @param int $creator_id + * @return bool + * @throws Zend_Auth_Storage_Exception + */ + public function isAuthmemberProjectCreator($creator_id) + { + $auth = Zend_Auth::getInstance(); + $authMember = $auth->getStorage()->read(); + if ($authMember->member_id == $creator_id) { + return true; + } - return $pploadApi; + return false; } } \ No newline at end of file diff --git a/application/modules/default/models/Project.php b/application/modules/default/models/Project.php index 8c3e5fcaf..a4d439ca7 100644 --- a/application/modules/default/models/Project.php +++ b/application/modules/default/models/Project.php @@ -1,2049 +1,2049 @@ . **/ class Default_Model_Project extends Default_Model_DbTable_Project { const FILTER_NAME_PROJECT_ID_NOT_IN = 'project_id_not_in'; const FILTER_NAME_RANKING = 'ranking'; const FILTER_NAME_CATEGORY = 'category'; const FILTER_NAME_TAG = 'tag'; const FILTER_NAME_ORIGINAL = 'original'; const FILTER_NAME_FAVORITE = 'favorite'; const FILTER_NAME_MEMBER = 'member'; const FILTER_NAME_ORDER = 'order'; const FILTER_NAME_LOCATION = 'location'; const ITEM_TYPE_DUMMY = 0; const ITEM_TYPE_PRODUCT = 1; const ITEM_TYPE_UPDATE = 2; const TAG_LICENCE_GID = 7; const TAG_TYPE_ID = 1; const TAG_ISORIGINAL = 'original-product'; /** * @param int $status * @param int $id * * @throws Exception */ public function setStatus($status, $id) { if (false === in_array($status, $this->_allowedStatusTypes)) { throw new Exception('Wrong value for project status.'); } $updateValues = array( 'status' => $status, 'changed_at' => new Zend_Db_Expr('Now()') ); if (self::PROJECT_DELETED == $status) { $updateValues['deleted_at'] = new Zend_Db_Expr('NOW()'); } $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER')); } /** * @param int $member_id * @param int $id */ public function setClaimedByMember($member_id, $id) { $updateValues = array( 'claimed_by_member' => $member_id, 'changed_at' => new Zend_Db_Expr('Now()') ); $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER')); } /** * @param int $id */ public function resetClaimedByMember($id) { $updateValues = array( 'claimed_by_member' => new Zend_Db_Expr('NULL'), 'changed_at' => new Zend_Db_Expr('Now()') ); $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER')); } /** * @param int $id */ public function transferClaimToMember($id) { $project = $this->fetchProductInfo($id); //Update ppload $pploadFiles = new Default_Model_DbTable_PploadFiles(); $updateValues = array( 'owner_id' => $project->claimed_by_member ); $pploadFiles->update($updateValues, "collection_id = ".$project->ppload_collection_id); $pploadCollection = new Default_Model_DbTable_PploadCollections(); $updateValues = array( 'owner_id' => $project->claimed_by_member ); $pploadCollection->update($updateValues, "id = ".$project->ppload_collection_id); //And prohect $updateValues = array( 'member_id' => new Zend_Db_Expr('claimed_by_member'), 'claimable' => new Zend_Db_Expr('NULL'), 'claimed_by_member' => new Zend_Db_Expr('NULL') ); $this->update($updateValues, $this->_db->quoteInto('project_id=? and claimable = 1', $id, 'INTEGER')); } /** * @param int $project_id * @param $member_id * * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ public function setInActive($project_id, $member_id) { $project_id = (int)$project_id; $updateValues = array( 'status' => self::PROJECT_INACTIVE, 'deleted_at' => new Zend_Db_Expr('Now()') ); $this->update($updateValues, 'status > 40 AND project_id=' . $project_id); $this->setInActiveForUpdates($project_id); $this->setDeletedForComments($member_id,$project_id); } /** * @param int $id */ protected function setInActiveForUpdates($id) { $id = (int)$id; $updateValues = array( 'status' => self::PROJECT_INACTIVE, 'changed_at' => new Zend_Db_Expr('Now()') ); $this->update($updateValues, 'status > 40 AND pid=' . $id); } /** * @param int $member_id * @param int $id * * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ private function setDeletedForComments($member_id, $id) { $modelComments = new Default_Model_ProjectComments(); $modelComments->setAllCommentsForProjectDeleted($member_id, $id); } /** * @param int $id * * @return mixed * @throws Zend_Db_Statement_Exception */ public function fetchActiveBySourcePk($id) { $q = $this->select()->where('status = ?', self::PROJECT_ACTIVE)->where('source_pk = ?', (int)$id) ->where('source_type = "project"') ; return $q->query()->fetch(); } /** * @param int $member_id * @param bool $onlyActiveProjects * * @return mixed */ public function countAllProjectsForMember($member_id, $onlyActiveProjects = false) { $q = $this->select()->from($this, array('countAll' => new Zend_Db_Expr('count(*)')))->setIntegrityCheck(false) ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE)) ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD) ; $resultSet = $q->query()->fetchAll(); return $resultSet[0]['countAll']; } /** * @param int $member_id * @param bool $onlyActiveProjects * @param $catids * * @return mixed * @throws Zend_Cache_Exception * @throws Zend_Db_Statement_Exception */ public function countAllProjectsForMemberCatFilter($member_id, $onlyActiveProjects = false, $catids = null) { $q = $this->select()->from($this, array('countAll' => new Zend_Db_Expr('count(*)')))->setIntegrityCheck(false) ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE)) ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD) ; if (isset($catids)) { $q->where('project_category_id in (' . $this->_getCatIds($catids) . ')'); } $resultSet = $q->query()->fetchAll(); return $resultSet[0]['countAll']; } /** * @param $catids * * @return string * @throws Zend_Cache_Exception * @throws Zend_Db_Statement_Exception */ protected function _getCatIds($catids) { $sqlwhereCat = ""; $sqlwhereSubCat = ""; $idCategory = explode(',', $catids); if (false === is_array($idCategory)) { $idCategory = array($idCategory); } $sqlwhereCat .= implode(',', $idCategory); $modelCategory = new Default_Model_DbTable_ProjectCategory(); $subCategories = $modelCategory->fetchChildElements($idCategory); if (count($subCategories) > 0) { foreach ($subCategories as $element) { $sqlwhereSubCat .= "{$element['project_category_id']},"; } } return $sqlwhereSubCat . $sqlwhereCat; } /** * By default it will show all projects for a member included the unpublished elements. * * @param int $member_id * @param int|null $limit * @param int|null $offset * @param bool $onlyActiveProjects * * @return Zend_Db_Table_Rowset_Abstract */ public function fetchAllProjectsForMember($member_id, $limit = null, $offset = null, $onlyActiveProjects = false) { $q = $this->select()->from($this, array( '*', 'project_validated' => 'project.validated', 'project_uuid' => 'project.uuid', 'project_status' => 'project.status', 'project_created_at' => 'project.created_at', 'project_changed_at' => 'project.changed_at', 'member_type' => 'member.type', 'project_member_id' => 'member_id', 'laplace_score' => new Zend_Db_Expr('laplace_score(count_likes,count_dislikes)'), 'catTitle' => new Zend_Db_Expr('(SELECT title FROM project_category WHERE project_category_id = project.project_category_id)') ))->setIntegrityCheck(false)->join('member', 'project.member_id = member.member_id', array('username')) ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE)) ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD) ->order('project_changed_at DESC') ; if (isset($limit)) { $q->limit($limit, $offset); } return $this->generateRowSet($q->query()->fetchAll()); } /** * @param array $data * * @return Zend_Db_Table_Rowset_Abstract */ protected function generateRowSet($data) { $classRowSet = $this->getRowsetClass(); return new $classRowSet(array( 'table' => $this, 'rowClass' => $this->getRowClass(), 'stored' => true, 'data' => $data )); } /** * By default it will show all projects for a member included the unpublished elements. * * @param int $member_id * @param int|null $limit * @param int|null $offset * @param bool $onlyActiveProjects * * @param null $catids * * @return Zend_Db_Table_Rowset_Abstract * @throws Zend_Cache_Exception * @throws Zend_Db_Statement_Exception */ public function fetchAllProjectsForMemberCatFilter( $member_id, $limit = null, $offset = null, $onlyActiveProjects = false, $catids = null ) { $q = $this->select()->from($this, array( '*', 'project_validated' => 'project.validated', 'project_uuid' => 'project.uuid', 'project_status' => 'project.status', 'project_created_at' => 'project.created_at', 'project_changed_at' => 'project.changed_at', 'member_type' => 'member.type', 'project_member_id' => 'member_id', 'laplace_score' => new Zend_Db_Expr('laplace_score(count_likes,count_dislikes)'), 'catTitle' => new Zend_Db_Expr('(SELECT title FROM project_category WHERE project_category_id = project.project_category_id)') ))->setIntegrityCheck(false)->join('member', 'project.member_id = member.member_id', array('username')) ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE)) ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD) ->order('project_changed_at DESC') ; if (isset($catids)) { $q->where('project_category_id in (' . $this->_getCatIds($catids) . ')'); } if (isset($limit)) { $q->limit($limit, $offset); } return $this->generateRowSet($q->query()->fetchAll()); } /** * @param $collection_id * * @return null|Zend_Db_Table_Row_Abstract */ public function fetchProductForCollectionId($collection_id) { $sql = ' SELECT `p`.* FROM `project` AS `p` WHERE `p`.`ppload_collection_id` = :collectionId AND `p`.`status` >= :projectStatus AND `p`.`type_id` = :typeId '; $result = $this->_db->fetchRow($sql, array( 'collectionId' => $collection_id, 'projectStatus' => self::PROJECT_INACTIVE, 'typeId' => self::PROJECT_TYPE_STANDARD )); if ($result) { return $this->generateRowClass($result); } else { return null; } } /** * @param int $project_id * * @return null|Zend_Db_Table_Row_Abstract */ public function fetchProductInfo($project_id) { $sql = ' SELECT `p`.*, `p`.`validated` AS `project_validated`, `p`.`uuid` AS `project_uuid`, `p`.`status` AS `project_status`, `p`.`created_at` AS `project_created_at`, `p`.`major_updated_at` AS `project_major_updated_at`, `p`.`changed_at` AS `project_changed_at`, `p`.`member_id` AS `project_member_id`, `p`.`source_pk` AS `project_source_pk`, `p`.`version` AS `project_version`, `pc`.`title` AS `cat_title`, `m`.`username`, `m`.`avatar`, `m`.`profile_image_url`, `m`.`roleId`, `m`.`mail`, `m`.`paypal_mail`, `m`.`dwolla_id`, IFNULL(pr.score_with_pling, 500) AS laplace_score, `view_reported_projects`.`amount_reports` AS `amount_reports`, (SELECT `tag`.`tag_fullname` FROM `tag_object`, `tag` WHERE `tag_object`.`tag_id`=`tag`.`tag_id` AND `tag_object_id` = `p`.`project_id` AND `tag_object`.`is_deleted`=0 AND `tag_group_id` = :tag_licence_gid AND `tag_type_id` = :tag_type_id ORDER BY `tag_object`.`tag_created` DESC LIMIT 1) AS `project_license_title` FROM `project` AS `p` JOIN `member` AS `m` ON `p`.`member_id` = `m`.`member_id` AND `m`.`is_active` = 1 AND `m`.`is_deleted` = 0 JOIN `project_category` AS `pc` ON `p`.`project_category_id` = `pc`.`project_category_id` LEFT join stat_rating_project AS pr ON p.project_id = pr.project_id LEFT JOIN `view_reported_projects` ON ((`view_reported_projects`.`project_id` = `p`.`project_id`)) WHERE `p`.`project_id` = :projectId AND `p`.`status` >= :projectStatus AND (`p`.`type_id` = :typeIdStd OR `p`.`type_id` = :typeIdColl) '; $result = $this->_db->fetchRow($sql, array( 'projectId' => $project_id, 'projectStatus' => self::PROJECT_INACTIVE, - 'typeIdStd' => self::PROJECT_TYPE_STANDARD, - 'typeIdColl' => self::PROJECT_TYPE_COLLECTION, + 'typeIdStd' => self::PROJECT_TYPE_STANDARD, + 'typeIdColl' => self::PROJECT_TYPE_COLLECTION, 'tag_licence_gid' => self::TAG_LICENCE_GID, 'tag_type_id' => self::TAG_TYPE_ID )); if ($result) { return $this->generateRowClass($result); } else { return null; } } /** * @param $project_id * * @return Zend_Db_Table_Rowset_Abstract */ public function fetchProjectUpdates($project_id) { $projectSel = $this->select()->setIntegrityCheck(false)->from($this->_name) ->join('member', 'project.member_id = member.member_id', array('*')) ->where('project.pid=?', $project_id, 'INTEGER')->where('project.status>?', self::PROJECT_INACTIVE) ->where('project.type_id=?', self::PROJECT_TYPE_UPDATE)->order('RAND()') ; return $this->fetchAll($projectSel); } /** * @param $project_id * * @return Zend_Db_Table_Rowset_Abstract */ public function fetchAllProjectUpdates($project_id) { $projectSel = $this->select()->setIntegrityCheck(false)->from($this->_name)->where('project.pid=?', $project_id, 'INTEGER') ->where('project.status>?', self::PROJECT_INACTIVE)->where('project.type_id=?', self::PROJECT_TYPE_UPDATE) ; return $this->fetchAll($projectSel); } /** * @param $project * @param int $count * * @return Zend_Db_Table_Rowset_Abstract */ public function fetchSimilarProjects($project, $count = 10) { $count = (int)$count; $sql = " SELECT * FROM `stat_projects` AS `p` WHERE `p`.`project_category_id` = :cat_id AND `project_id` <> :project_id ORDER BY `p`.`changed_at` DESC LIMIT {$count} "; $result = $this->_db->fetchAll($sql, array( 'cat_id' => $project->project_category_id, 'project_id' => $project->project_id )); return $this->generateRowSet($result); } /** * @param Zend_Db_Table_Row $project * @param int $count * * @return Zend_Db_Table_Rowset_Abstract * @throws Zend_Exception */ public function fetchMoreProjects($project, $count = 6) { $q = $this->select()->from(array('project' => 'stat_projects'), array( 'project_id', 'image_small', 'title', 'catTitle' => 'cat_title', 'changed_at' ))->setIntegrityCheck(false) ->where('project.status = ?', self::PROJECT_ACTIVE) ->where('project.member_id = ?', $project->member_id, 'INTEGER') ->where('project.project_id != ?', $project->project_id, 'INTEGER') ->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD) ->where('project.amount_reports is null') ->where('project.project_category_id = ?', $project->project_category_id, 'INTEGER') ->limit($count) ->order('project.project_created_at DESC') ; $tagFilter = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; if ($tagFilter) { $q = $this->generateTagFilter($q, array(self::FILTER_NAME_TAG => $tagFilter)); } $result = $this->fetchAll($q); return $result; } /** * @param Zend_Db_Select $statement * @param array $filterArrayValue * * @return Zend_Db_Select */ protected function generateTagFilter(Zend_Db_Select $statement, $filterArrayValue) { if (false == isset($filterArrayValue[self::FILTER_NAME_TAG])) { return $statement; } $filter = $filterArrayValue[self::FILTER_NAME_TAG]; if (is_array($filter)) { $tagList = $filter; //build where statement für projects $selectAnd = $this->select()->from(array('project' => 'stat_projects')); foreach($tagList as $item) { #and $selectAnd->where('find_in_set(?, tag_ids)', $item); } $statement->where(implode(' ', $selectAnd->getPart('where'))); /* $statement->join(array( 'tags' => new Zend_Db_Expr('(SELECT DISTINCT project_id FROM stat_project_tagids WHERE tag_id in (' . implode(',', $filter) . '))') ), 'project.project_id = tags.project_id', array()); * */ } else { $statement->where('find_in_set(?, tag_ids)', $filter); } return $statement; } /** * @param $project * @param int $count * * @return Zend_Db_Table_Rowset_Abstract * @throws Zend_Db_Statement_Exception * @throws Zend_Exception * @todo improve processing speed */ public function fetchMoreProjectsOfOtherUsr($project, $count = 8) { $sql = " SELECT count(1) AS `count` FROM `stat_projects` WHERE `status` = :current_status AND `member_id` <> :current_member_id AND `project_category_id` = :category_id AND `type_id` = :project_type "; $result = $this->_db->query($sql, array( 'current_status' => self::PROJECT_ACTIVE, 'current_member_id' => $project->member_id, 'category_id' => $project->project_category_id, 'project_type' => self::PROJECT_TYPE_STANDARD ))->fetch() ; if ($result['count'] > $count) { $offset = rand(0, $result['count'] - $count); } else { $offset = 0; } $q = $this->select()->from(array('project' => 'stat_projects'), array( 'project_id', 'image_small', 'title', 'catTitle' => 'cat_title', 'changed_at' ))->setIntegrityCheck(false)->where('status = ?', self::PROJECT_ACTIVE) ->where('member_id != ?', $project->member_id, 'INTEGER')->where('type_id = ?', 1) ->where('amount_reports is null') ->where('project_category_id = ?', $project->project_category_id, 'INTEGER')->limit($count, $offset) ->order('project_created_at DESC') ; $tagFilter = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; if ($tagFilter) { $q = $this->generateTagFilter($q, array(self::FILTER_NAME_TAG => $tagFilter)); } $result = $this->fetchAll($q); return $result; } /** * @param int $project_id * * @return Zend_Db_Table_Rowset_Abstract */ public function fetchProjectSupporter($project_id) { $plingTable = new Default_Model_DbTable_Plings(); return $plingTable->getSupporterForProjectId($project_id); } /** * @param int $project_id * * @return Zend_Db_Table_Rowset_Abstract */ public function fetchProjectSupporterWithPlings($project_id) { $plingTable = new Default_Model_DbTable_Plings(); return $plingTable->getSupporterWithPlingsForProjectId($project_id); } /** * @param $projectId * @param $sources */ public function updateGalleryPictures($projectId, $sources) { $galleryPictureTable = new Default_Model_DbTable_ProjectGalleryPicture(); $galleryPictureTable->clean($projectId); $galleryPictureTable->insertAll($projectId, $sources); } /** * @param $projectId * * @return array */ public function getGalleryPictureSources($projectId) { $galleryPictureTable = new Default_Model_DbTable_ProjectGalleryPicture(); $stmt = $galleryPictureTable->select()->where('project_id = ?', $projectId)->order(array('sequence')); $pics = array(); foreach ($galleryPictureTable->fetchAll($stmt) as $pictureRow) { $pics[] = $pictureRow['picture_src']; } return $pics; } /** * @param int $project_id * * @return array * @throws Zend_Db_Statement_Exception */ public function fetchProjectViews($project_id) { $sql = " SELECT `project_id`, `count_views`, `count_visitor`, `last_view` FROM `stat_page_views_mv` WHERE `project_id` = ? "; $database = Zend_Db_Table::getDefaultAdapter(); $sql = $database->quoteInto($sql, $project_id, 'INTEGER', 1); $resultSet = $database->query($sql)->fetchAll(); if (count($resultSet) > 0) { $result = $resultSet[0]['count_views']; } else { $result = 0; } return $result; } /** * @param int $member_id * * @return int * @throws Zend_Db_Statement_Exception */ public function fetchOverallPageViewsByMember($member_id) { $sql = " SELECT sum(`stat`.`amount`) AS `page_views` FROM `project` JOIN (SELECT `project_id`, count(`project_id`) AS `amount` FROM `stat_page_views` GROUP BY `project_id`) AS `stat` ON `stat`.`project_id` = `project`.`project_id` WHERE `project`.`member_id` = :member_id AND `project`.`status` = :project_status GROUP BY `member_id` "; $result = $this->_db->query($sql, array('member_id' => $member_id, 'project_status' => self::PROJECT_ACTIVE)); if ($result->rowCount() > 0) { $row = $result->fetch(); return $row['page_views']; } else { return 0; } } /** * @return array * @throws Zend_Db_Statement_Exception */ public function getStatsForNewProjects() { $sql = " SELECT DATE_FORMAT(`time`, '%M %D') AS `projectdate`, count(1) AS `daycount` FROM `activity_log` WHERE `activity_type_id` = 0 GROUP BY DATE_FORMAT(`time`, '%Y%M%D') ORDER BY `time` DESC LIMIT 14 ;"; $database = Zend_Db_Table::getDefaultAdapter(); $resultSet = $database->query($sql)->fetchAll(); return $resultSet; } /** * @param int $idCategory * @param int|null $limit * * @return Zend_Db_Table_Rowset_Abstract * @throws Zend_Cache_Exception * @throws Zend_Db_Statement_Exception */ public function fetchProductsByCategory($idCategory, $limit = null) { $select = $this->select()->setIntegrityCheck(false)->from($this->_name)->where('project.project_category_id in (?)', $idCategory) ->where('project.status = ?', self::PROJECT_ACTIVE)->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD) ->joinLeft(array( 'pling_amount' => new Zend_Db_Expr('(SELECT project_id as plinged_project_id, SUM(amount) AS sumAmount, count(1) as countPlings FROM plings where status_id >= 2 group by project_id order by sumAmount DESC)') ), 'pling_amount.plinged_project_id = project.project_id') ->joinLeft('project_category', 'project_category.project_category_id = project.project_category_id', array('cat_title' => 'title'))->order('pling_amount.sumAmount DESC') ; if (false === is_null($limit)) { $select->limit($limit); } $modelCategory = new Default_Model_DbTable_ProjectCategory(); $subCategories = $modelCategory->fetchChildElements($idCategory); if (count($subCategories) > 0) { $sqlwhere = ''; foreach ($subCategories as $element) { $sqlwhere .= "{$element['project_category_id']},"; } $sqlwhere = substr($sqlwhere, 0, -1); if (!empty($sqlwhere)) { $sqlwhere = explode(',', $sqlwhere); } $select->orWhere('project.project_category_id in (?)', $sqlwhere); } return $this->fetchAll($select); } /** * @param int|array $idCategory id of a category or an array of id's * @param bool $withSubCat if was set true it will also count products in sub categories * @param null $store_id * * @return int count of products in given category * @throws Zend_Exception * @deprecated */ public function countProductsInCategory($idCategory = null, $withSubCat = true, $store_id = null) { if (empty($idCategory)) { throw new Zend_Exception('idCategory param was not set'); } if (false == is_array($idCategory)) { $idCategory = array($idCategory); } if (isset($store_id)) { $configurations = Zend_Registry::get('application_store_config_id_list'); $store_config = isset($configurations[$store_id]) ? $configurations[$store_id] : null; } else { $store_config = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; } $tagFilter = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; $cacheName = __FUNCTION__ . '_' . md5(serialize($idCategory) . $withSubCat . serialize($tagFilter)); /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); if (false !== ($resultSet = $cache->load($cacheName))) { return (int)$resultSet[0]['count_active_projects']; } $select = $this->select()->setIntegrityCheck(false)->from('stat_projects', array('count_active_projects' => 'COUNT(1)')) ->where('status = ? ', self::PROJECT_ACTIVE)->where('type_id = ?', self::PROJECT_TYPE_STANDARD) ; $select = $this->generateTagFilter($select, array(self::FILTER_NAME_TAG => $tagFilter)); if ($withSubCat) { $modelCategory = new Default_Model_DbTable_ProjectCategory(); $subCategories = $modelCategory->fetchChildIds($idCategory); $inCategories = implode(',', array_unique(array_merge($idCategory, $subCategories))); } else { $inCategories = implode(',', $idCategory); } $select->where('project_category_id in (' . $inCategories . ')'); $resultSet = $this->fetchAll($select)->toArray(); $cache->save($resultSet, $cacheName, array(), 60); return (int)$resultSet[0]['count_active_projects']; } /** * @param int|array $idCategory * * @return int * @throws Zend_Exception */ public function countActiveMembersForCategory($idCategory) { $cacheName = __FUNCTION__ . md5(serialize($idCategory)); $cache = Zend_Registry::get('cache'); $result = $cache->load($cacheName); if ($result) { return (int)$result['count_active_members']; } $sqlwhereCat = ""; $sqlwhereSubCat = ""; if (false === is_array($idCategory)) { $idCategory = array($idCategory); } $sqlwhereCat .= implode(',', $idCategory); $modelCategory = new Default_Model_DbTable_ProjectCategory(); $subCategories = $modelCategory->fetchChildElements($idCategory); if (count($subCategories) > 0) { foreach ($subCategories as $element) { $sqlwhereSubCat .= "{$element['project_category_id']},"; } } $selectWhere = 'AND p.project_category_id in (' . $sqlwhereSubCat . $sqlwhereCat . ')'; $sql = "SELECT count(1) AS `count_active_members` FROM ( SELECT count(1) AS `count_active_projects` FROM `project` `p` WHERE `p`.`status` = 100 AND `p`.`type_id` = 1 {$selectWhere} GROUP BY p.member_id ) AS `A`;"; $result = $this->_db->fetchRow($sql); $cache->save($result, $cacheName); return (int)$result['count_active_members']; } /** * @param int $project_id * * @return bool */ public function isProjectFeatured($project_id) { $sql_object = "SELECT `project_id` FROM `project` WHERE `project_id`= :project_id AND `status` = 100 AND `type_id` = 1 AND `featured` = 1"; $r = $this->getAdapter()->fetchRow($sql_object, array('project_id' => $project_id)); if ($r) { return true; } else { return false; } } /** * @param int $project_id * * @return bool */ public function isProjectClone($project_id) { $sql_object = "SELECT c.project_clone_id FROM project_clone c WHERE c.is_valid = 1 AND c.is_deleted = 0 AND c.project_id_parent IS NOT NULL AND c.project_id = :project_id"; $r = $this->getAdapter()->fetchRow($sql_object, array('project_id' => $project_id)); if ($r) { return true; } else { return false; } } /** * @param bool $in_current_store * * @return int * @throws Zend_Exception */ public function fetchTotalProjectsCount($in_current_store = false) { $sql = "SELECT count(1) AS `total_project_count` FROM `stat_projects`"; if ($in_current_store) { $store_tags = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null; /* if ($store_tags) { $sql .= ' JOIN (SELECT DISTINCT project_id FROM stat_project_tagids WHERE tag_id in (' . implode(',', $store_tags) . ')) AS tags ON stat_projects.project_id = tags.project_id'; } * */ $info = new Default_Model_Info(); $activeCategories = $info->getActiveCategoriesForCurrentHost(); $sql .= ' WHERE project_category_id IN (' . implode(',', $activeCategories) . ')'; //Store Tag Filter if ($store_tags) { $tagList = $store_tags; //build where statement für projects $sql .= " AND ("; if(!is_array($tagList)) { $tagList = array($tagList); } foreach($tagList as $item) { #and $sql .= ' find_in_set('.$item.', tag_ids) AND '; } $sql .= ' 1=1)';; } } $result = $this->_db->fetchRow($sql); return (int)$result['total_project_count']; } /** * @param $member_id * * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ public function setAllProjectsForMemberDeleted($member_id) { $sql = "SELECT `project_id` FROM `project` WHERE `member_id` = :memberId AND `type_id` = :typeId AND `status` > :project_status"; $projectForDelete = $this->_db->fetchAll($sql, array( 'memberId' => $member_id, 'typeId' => self::PROJECT_TYPE_STANDARD, 'project_status' => self::PROJECT_DELETED )); foreach ($projectForDelete as $item) { $this->setDeleted($member_id, $item['project_id']); } // set personal page deleted $sql = "SELECT project_id FROM project WHERE member_id = :memberId AND type_id = :typeId"; $projectForDelete = $this->_db->fetchAll($sql, array( 'memberId' => $member_id, 'typeId' => self::PROJECT_TYPE_PERSONAL )); foreach ($projectForDelete as $item) { $this->setDeleted($member_id, $item['project_id']); } /* $sql = "UPDATE project SET `status` = :statusCode, deleted_at = NOW() WHERE member_id = :memberId AND type_id = :typeId"; $this->_db->query($sql, array( 'statusCode' => self::PROJECT_DELETED, 'memberId' => $member_id, 'typeId' => self::PROJECT_TYPE_PERSONAL ))->execute(); */ } /** * @param int $member_id * @param int $id * * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ public function setDeleted($member_id, $id) { $id = (int)$id; $updateValues = array( 'status' => self::PROJECT_DELETED, 'deleted_at' => new Zend_Db_Expr('Now()') ); $this->update($updateValues, 'status > 30 AND project_id=' . $id); $memberLog = new Default_Model_MemberDeactivationLog(); $memberLog->logProjectAsDeleted($member_id, $id); $this->setDeletedForUpdates($member_id, $id); $this->setDeletedForComments($member_id, $id); $this->setDeletedInMaterializedView($id); } /** * @param $member_id * @param int $id */ protected function setDeletedForUpdates($member_id, $id) { $id = (int)$id; $updateValues = array( 'status' => self::PROJECT_DELETED, 'deleted_at' => new Zend_Db_Expr('Now()') ); $this->update($updateValues, 'status > 30 AND pid=' . $id); } /** * @param $id * * @throws Zend_Db_Statement_Exception */ private function setDeletedInMaterializedView($id) { $sql = "UPDATE `stat_projects` SET `status` = :new_status WHERE `project_id` = :project_id"; $result = $this->_db->query($sql, array('new_status' => self::PROJECT_DELETED, 'project_id' => $id))->execute(); } /** * @param int $member_id * * @throws Zend_Exception */ public function setAllProjectsForMemberActivated($member_id) { $sql = "SELECT `p`.`project_id` FROM `project` `p` JOIN `member_deactivation_log` `l` ON `l`.`object_type_id` = 3 AND `l`.`object_id` = `p`.`project_id` AND `l`.`deactivation_id` = `p`.`member_id` WHERE `p`.`member_id` = :memberId"; $projectForDelete = $this->_db->fetchAll($sql, array( 'memberId' => $member_id )); foreach ($projectForDelete as $item) { $this->setActive($member_id, $item['project_id']); } } /** * @param int $member_id * @param int $id * * @throws Zend_Exception */ public function setActive($member_id, $id) { $updateValues = array( 'status' => self::PROJECT_ACTIVE, 'deleted_at' => null ); $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER')); $memberLog = new Default_Model_MemberDeactivationLog(); $memberLog->removeLogProjectAsDeleted($member_id, $id); $this->setActiveForUpdates($member_id, $id); $this->setActiveForComments($member_id, $id); } /** * @param int $id */ protected function setActiveForUpdates($member_id, $id) { $updateValues = array( 'status' => self::PROJECT_ACTIVE, 'deleted_at' => null ); $this->update($updateValues, $this->_db->quoteInto('pid=?', $id, 'INTEGER')); } /** * @param int $member_id * @param int $project_id */ private function setActiveForComments($member_id, $project_id) { $modelComments = new Default_Model_ProjectComments(); $modelComments->setAllCommentsForProjectActivated($member_id, $project_id); } /** * @param array $inputFilterParams * @param int|null $limit * @param int|null $offset * * @return array * @throws Zend_Cache_Exception * @throws Zend_Db_Select_Exception * @throws Zend_Exception */ public function fetchProjectsByFilter($inputFilterParams, $limit = null, $offset = null) { $cacheName = __FUNCTION__ . '_' . md5(serialize($inputFilterParams) . (string)$limit . (string)$offset); /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); if (false === ($returnValue = $cache->load($cacheName))) { $statement = $this->generateStatement($inputFilterParams, $limit, $offset); if (APPLICATION_ENV == 'development') { Zend_Registry::get('logger')->debug(__METHOD__ . ' - ' . $statement->__toString()); } /** @var Zend_Db_Table_Rowset $fetchedElements */ $fetchedElements = $this->fetchAll($statement); $statement->reset('limitcount')->reset('limitoffset'); $statement->reset('columns')->columns(array('count' => new Zend_Db_Expr('count(*)'))); $countElements = $this->fetchRow($statement); $returnValue = array('elements' => $fetchedElements, 'total_count' => $countElements->count); $cache->save($returnValue, $cacheName, array(), 120); } return $returnValue; } /** * @param array $inputFilterParams * @param int|null $limit * @param int|null $offset * * @return Zend_Db_Select * @throws Zend_Cache_Exception * @throws Zend_Db_Statement_Exception */ protected function generateStatement($inputFilterParams, $limit = null, $offset = null) { $statement = $this->generateBaseStatement(); $statement = $this->generateCategoryFilter($statement, $inputFilterParams); $statement = $this->generateOrderFilter($statement, $inputFilterParams); $statement = $this->generateTagFilter($statement, $inputFilterParams); // $statement = $this->generateOriginalFilter($statement, $inputFilterParams); $statement = $this->generateFavoriteFilter($statement, $inputFilterParams); $statement = $this->generateReportedSpamFilter($statement); $statement->limit($limit, $offset); return $statement; } /** * @return Zend_Db_Select */ protected function generateBaseStatement() { $statement = $this->select()->setIntegrityCheck(false); //$statement->from(array('project' => $this->_name), array( $statement->from(array('project' => 'stat_projects'), array( '*' )); $statement->where('project.status = ?', self::PROJECT_ACTIVE)->where('project.type_id IN (?)', array(self::PROJECT_TYPE_STANDARD, self::PROJECT_TYPE_COLLECTION)); return $statement; } /** * @param Zend_Db_Select $statement * @param array $filterArrayValue * * @return Zend_Db_Select * @throws Zend_Cache_Exception * @throws Zend_Db_Statement_Exception */ protected function generateCategoryFilter(Zend_Db_Select $statement, $filterArrayValue) { if (false == isset($filterArrayValue[self::FILTER_NAME_CATEGORY])) { return $statement; } $filter = $filterArrayValue[self::FILTER_NAME_CATEGORY]; if (false === is_array($filter)) { $filter = array($filter); } // fetch child elements for each category $modelProjectCategories = new Default_Model_DbTable_ProjectCategory(); $childElements = $modelProjectCategories->fetchChildIds($filter); $allCategories = array_unique(array_merge($filter, $childElements)); $stringCategories = implode(',', $allCategories); $statement->where("( project.project_category_id IN ({$stringCategories}) )"); return $statement; } /** * @param Zend_Db_Select $statement * @param array $filterArrayValue * * @return Zend_Db_Select */ protected function generateOrderFilter(Zend_Db_Select $statement, $filterArrayValue) { if (!isset($filterArrayValue[self::FILTER_NAME_ORDER])) { $filterValue = ''; } else { $filterValue = $filterArrayValue[self::FILTER_NAME_ORDER]; } switch ($filterValue) { case 'latest': $statement->order('project.major_updated_at DESC'); //$statement->order('project.changed_at DESC'); break; case 'rating': //$statement->order(array('amount_received DESC', 'count_plings DESC', 'latest_pling DESC', 'project.created_at DESC')); //$statement->order(array(new Zend_Db_Expr('(round(((count_likes + 6) / ((count_likes + count_dislikes) + 12)),2) * 100) DESC'),'amount_received DESC', 'count_plings DESC', 'latest_pling DESC', 'project.created_at DESC')); /*$statement->order(array( new Zend_Db_Expr('(round(((count_likes + 6) / ((count_likes + count_dislikes) + 12)),2) * 100) DESC'), 'project.created_at DESC' ));*/ $statement->order('project.laplace_score DESC'); break; case 'plinged': $statement->order('project.count_plings DESC'); break; case 'test': $statement->order('project.laplace_score_test DESC'); break; case 'top': $statement->order('project.laplace_score_old DESC'); break; case 'download': $statement->order('project.count_downloads_hive DESC'); break; case 'downloadQuarter': $statement->order('project.count_downloads_quarter DESC'); break; case 'hot': $statement->order(array( new Zend_Db_Expr('(round(((count_likes + 6) / ((count_likes + count_dislikes) + 12)),2) * 100) DESC'), 'count_plings DESC', 'project.created_at DESC' )); $statement->where(' project.created_at >= (NOW()- INTERVAL 14 DAY)'); break; case 'alpha': default: $statement->order('project.title'); } return $statement; } /** * @param Zend_Db_Select $statement * @param array $filterArrayValue * * @return Zend_Db_Select */ /*protected function generateOriginalFilter(Zend_Db_Select $statement, $filterArrayValue) { if (false == isset($filterArrayValue[self::FILTER_NAME_ORIGINAL])) { return $statement; } $filter = $filterArrayValue[self::FILTER_NAME_ORIGINAL]; if (is_array($filter)) { // todo maybe for other tags filter } else { $statement->where('find_in_set(?, tags)', $filter); } return $statement; }*/ /** * @param Zend_Db_Select $statement * @param array $filterArrayValue * * @return Zend_Db_Select */ protected function generateFavoriteFilter(Zend_Db_Select $statement, $filterArrayValue) { if (false == isset($filterArrayValue[self::FILTER_NAME_FAVORITE])) { return $statement; } $filterMemberId = $filterArrayValue[self::FILTER_NAME_FAVORITE]; if ( null != $filterMemberId) { $statement->where('project_follower.member_id = ?', $filterMemberId); $statement->setIntegrityCheck(false)->join('project_follower', 'project.project_id = project_follower.project_id', array('project_follower_id')); } return $statement; } /** * @param Zend_Db_Select $statement * * @return Zend_Db_Select */ protected function generateReportedSpamFilter(Zend_Db_Select $statement) { return $statement->where('(amount_reports is null)'); } /** * @param int $member_id * @param array $values * @param string $username * * @return Zend_Db_Table_Row_Abstract * @throws Exception * @throws Zend_Db_Table_Exception */ public function createProject($member_id, $values, $username) { $values = (array)$values; if (empty($member_id)) { throw new Zend_Db_Table_Exception('member_id is not set'); } if (empty($username)) { throw new Zend_Db_Table_Exception('username is not set'); } // check important values for a new project $values['uuid'] = (!array_key_exists('uuid', $values)) ? Local_Tools_UUID::generateUUID() : $values['uuid']; $values['member_id'] = (!array_key_exists('member_id', $values)) ? $member_id : $values['member_id']; $values['status'] = (!array_key_exists('status', $values)) ? self::PROJECT_INACTIVE : $values['status']; $values['type_id'] = (!array_key_exists('type_id', $values)) ? self::ITEM_TYPE_PRODUCT : $values['type_id']; $values['created_at'] = (!array_key_exists('created_at', $values)) ? new Zend_Db_Expr('NOW()') : $values['created_at']; $values['start_date'] = (!array_key_exists('start_date', $values)) ? new Zend_Db_Expr('NULL') : $values['start_date']; $values['creator_id'] = (!array_key_exists('creator_id', $values)) ? $member_id : $values['creator_id']; $values['gitlab_project_id'] = (empty($values['gitlab_project_id'])) ? new Zend_Db_Expr('NULL') : $values['gitlab_project_id']; if ($username == 'pling editor') { $values['claimable'] = (!array_key_exists('claimable', $values)) ? self::PROJECT_CLAIMABLE : $values['claimable']; } $savedRow = $this->save($values); return $savedRow; } /** * @param int $project_id * @param array $values * * @return Zend_Db_Table_Row_Abstract * @throws Exception * @throws Zend_Db_Table_Exception */ public function updateProject($project_id, $values) { $values = (array)$values; $projectData = $this->find($project_id)->current(); if (empty($projectData)) { throw new Zend_Db_Table_Exception('project_id not found'); } $values['gitlab_project_id'] = (empty($values['gitlab_project_id'])) ? new Zend_Db_Expr('NULL') : $values['gitlab_project_id']; $projectData->setFromArray($values)->save(); return $projectData; } /** * @param int $member_id * * @return array|mixed */ public function fetchMainProject($member_id) { $sql = "SELECT * FROM {$this->_name} WHERE type_id = :type AND member_id = :member"; // $this->_db->getProfiler()->setEnabled(true); $result = $this->_db->fetchRow($sql, array('type' => self::PROJECT_TYPE_PERSONAL, 'member' => (int)$member_id)); // $dummy = $this->_db->getProfiler()->getLastQueryProfile()->getQuery(); // $this->_db->getProfiler()->setEnabled(true); if (count($result) > 0) { return $result; } else { return array(); } } /** * @param $project_id * * @return Zend_Db_Table_Row_Abstract * @throws Zend_Db_Statement_Exception */ public function fetchProductDataFromMV($project_id) { $sql = "SELECT * FROM `stat_projects` WHERE `project_id` = :project_id"; $resultSet = $this->_db->query($sql, array('project_id' => $project_id))->fetch(); if (false === $resultSet) { return $this->generateRowClass(array()); } return $this->generateRowClass($resultSet); } /** * @return array */ public function fetchGhnsExcludedProjects() { $sql = " SELECT `p`.`project_id`, `p`.`title`, `l`.`member_id` AS `exclude_member_id`, `l`.`time` AS `exclude_time`, `m`.`username` AS `exclude_member_name` FROM `project` `p` JOIN `activity_log` `l` ON `l`.`project_id` = `p`.`project_id` AND `l`.`activity_type_id` = 314 INNER JOIN `member` `m` ON `m`.`member_id` = `l`.`member_id` WHERE `p`.`ghns_excluded` = 1 "; $list = $this->_db->fetchAll($sql); return $list; } public function getUserCreatingCategorys($member_id) { $sql = " select c.title as category1, count(1) as cnt from project p join project_category c on p.project_category_id = c.project_category_id where p.status = 100 and p.member_id =:member_id and p.type_id = 1 group by c.title order by cnt desc, c.title asc "; $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); return $result; } /** * @return array */ public function getUserActiveProjects($member_id, $limit = null, $offset = null) { // for member me page $sql = " SELECT `p`.`project_id`, `p`.`title`, `p`.`created_at` AS `project_created_at`, `p`.`changed_at` AS `project_changed_at`, `pr`.`likes` AS count_likes, `pr`.`dislikes`AS count_dislikes, IFNULL(pr.score_with_pling, 500) AS laplace_score, `p`.`member_id`, `cat`.`title` AS `catTitle`, `p`.`project_category_id`, `p`.`image_small`, (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`, c.cnt cntCategory FROM `project` `p` join project_category cat on p.project_category_id = cat.project_category_id LEFT join stat_rating_project AS pr ON p.project_id = pr.project_id left join stat_cnt_projects_catid_memberid c on p.project_category_id = c.project_category_id and p.member_id = c.member_id WHERE `p`.`status` =100 and `p`.`type_id` = 1 AND `p`.`member_id` = :member_id ORDER BY cntCategory desc,catTitle asc, `p`.`changed_at` DESC "; if (isset($limit)) { $sql = $sql . ' limit ' . $limit; } if (isset($offset)) { $sql = $sql . ' offset ' . $offset; } $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); if ($result) { return $this->generateRowClass($result); } else { return null; } } /** * @return array */ public function getUserActiveProjectsDuplicatedSourceurl($member_id, $limit = null, $offset = null) { // for member me page $sql = " select * from ( SELECT `p`.`project_id`, `p`.`title`, `p`.`created_at` AS `project_created_at`, `p`.`changed_at` AS `project_changed_at`, `pr`.`likes` AS count_likes, `pr`.`dislikes`AS count_dislikes, IFNULL(pr.score_with_pling, 500) AS laplace_score, `p`.`member_id`, `cat`.`title` AS `catTitle`, `p`.`project_category_id`, `p`.`image_small`, (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`, c.cnt cntCategory, (select count(1) from stat_projects_source_url s where TRIM(TRAILING '/' FROM p.source_url) = s.source_url) as cntDuplicates FROM `project` `p` join project_category cat on p.project_category_id = cat.project_category_id left join stat_cnt_projects_catid_memberid c on p.project_category_id = c.project_category_id and p.member_id = c.member_id LEFT join stat_rating_project AS pr ON p.project_id = pr.project_id WHERE `p`.`status` =100 and `p`.`type_id` = 1 AND `p`.`member_id` = :member_id ORDER BY cntCategory desc,catTitle asc, `p`.`changed_at` DESC ) t where t.cntDuplicates >1 "; if (isset($limit)) { $sql = $sql . ' limit ' . $limit; } if (isset($offset)) { $sql = $sql . ' offset ' . $offset; } $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); if ($result) { return $this->generateRowClass($result); } else { return null; } } /** * @return cnt */ public function getOriginalProjectsForMemberCnt($member_id) { $sql = " SELECT count(1) as cnt FROM stat_projects p inner join tag_object t on tag_id = 2451 and tag_group_id=11 and tag_type_id = 1 and is_deleted = 0 and t.tag_object_id = p.project_id WHERE member_id = :member_id "; $result = $this->_db->fetchRow($sql, array('member_id' => $member_id)); if ($result) { return $result['cnt']; } else { return 0; } } /** * @return cnt */ public function getOriginalProjectsForMember($member_id, $limit=null, $offset=null) { $sql = " SELECT * FROM stat_projects p inner join tag_object t on tag_id = 2451 and tag_group_id=11 and tag_type_id = 1 and is_deleted = 0 and t.tag_object_id = p.project_id WHERE member_id = :member_id "; if (isset($limit)) { $sql = $sql . ' limit ' . $limit; } if (isset($offset)) { $sql = $sql . ' offset ' . $offset; } $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); if ($result) { return $this->generateRowClass($result); } else { return null; } } /** * @return array */ public function getUnpublishedProjectsForMemberCnt($member_id) { // for member me page $sql = " SELECT count(1) as cnt FROM `project` `p` WHERE `p`.`status` = 40 and `p`.`type_id` = 1 AND `p`.`member_id` = :member_id "; $result = $this->_db->fetchRow($sql, array('member_id' => $member_id)); if ($result) { return $result['cnt']; } else { return 0; } } /** * @return array */ public function getUnpublishedProjectsForMember($member_id, $limit = null, $offset = null) { // for member me page $sql = " SELECT `p`.`project_id`, `p`.`title`, `p`.`created_at` AS `project_created_at`, `p`.`changed_at` AS `project_changed_at`, `pr`.`likes` AS count_likes, `pr`.`dislikes`AS count_dislikes, IFNULL(pr.score_with_pling, 500) AS laplace_score, `p`.`member_id`, `cat`.`title` AS `catTitle`, `p`.`project_category_id`, `p`.`image_small`, (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings` FROM `project` `p` join project_category cat on p.project_category_id = cat.project_category_id LEFT join stat_rating_project AS pr ON p.project_id = pr.project_id WHERE `p`.`status` = 40 and `p`.`type_id` = 1 AND `p`.`member_id` = :member_id ORDER BY catTitle asc, `p`.`changed_at` DESC "; if (isset($limit)) { $sql = $sql . ' limit ' . $limit; } if (isset($offset)) { $sql = $sql . ' offset ' . $offset; } $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); if ($result) { return $this->generateRowClass($result); } else { return null; } } public function fetchFilesForProjects($projects) { $ids=[]; foreach ($projects as $p) { $ids[] = $p->project_id; } $sql = " select p.project_id ,f.id ,f.name ,f.type ,f.size ,f.title ,f.collection_id from stat_projects p, ppload.ppload_files f where p.ppload_collection_id = f.collection_id and f.active = 1 and p.project_id in ( ".implode(',', $ids).") "; $result = $this->_db->fetchAll($sql); return $result; } public function fetchFilesForProject($project_id) { $sql = " select f.id ,f.name ,f.type ,f.size ,f.title ,f.collection_id from stat_projects p, ppload.ppload_files f where p.ppload_collection_id = f.collection_id and f.active = 1 and p.project_id = :project_id "; $result = $this->_db->fetchAll($sql,array("project_id"=>$project_id)); return $result; } /** * @param int $member_id * @param int|null $limit * @param int|null $offset * * @return null|Zend_Db_Table_Row_Abstract */ public function fetchAllFeaturedProjectsForMember($member_id, $limit = null, $offset = null) { // for member me page $sql = " SELECT `p`.`project_id`, `p`.`title`, `p`.`created_at` AS `project_created_at`, `p`.`changed_at` AS `project_changed_at`, `p`.`count_likes`, `p`.`count_dislikes`, `p`.`laplace_score`, `p`.`member_id`, `p`.`cat_title` AS `catTitle`, `p`.`image_small`, (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings` FROM `stat_projects` `p` WHERE `p`.`status` =100 AND `p`.`type_id` = 1 AND `featured` = 1 AND `p`.`member_id` = :member_id ORDER BY `p`.`changed_at` DESC "; if (isset($limit)) { $sql = $sql . ' limit ' . $limit; } if (isset($offset)) { $sql = $sql . ' offset ' . $offset; } $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); if ($result) { return $this->generateRowClass($result); } else { return null; } } /** * @param int $member_id * @param int|null $limit * @param int|null $offset * * @return null|Zend_Db_Table_Row_Abstract */ public function fetchAllCollectionsForMember($member_id, $limit = null, $offset = null) { // for member me page $sql = " SELECT `p`.`project_id`, `p`.`title`, `p`.`created_at` AS `project_created_at`, `p`.`changed_at` AS `project_changed_at`, `p`.`count_likes`, `p`.`count_dislikes`, `p`.`laplace_score`, `p`.`member_id`, `p`.`cat_title` AS `catTitle`, `p`.`image_small`, (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings` FROM `stat_projects` `p` WHERE `p`.`status` =100 AND `p`.`type_id` = 3 AND `p`.`member_id` = :member_id ORDER BY `p`.`changed_at` DESC "; if (isset($limit)) { $sql = $sql . ' limit ' . $limit; } if (isset($offset)) { $sql = $sql . ' offset ' . $offset; } $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); if ($result) { return $this->generateRowClass($result); } else { return null; } } /** * @param string $orderby * @param int|null $limit * @param int|null $offset * * @return array */ public function fetchDuplicatedSourceProjects($orderby = 'source_url asc', $limit = null, $offset = null) { $sql = " SELECT `source_url` ,count(1) AS `cnt`, GROUP_CONCAT(`p`.`project_id` ORDER BY `p`.`created_at`) `pids` FROM `stat_projects_source_url` `p` GROUP BY `source_url` HAVING count(1)>1 "; if (isset($orderby)) { $sql = $sql . ' order by ' . $orderby; } if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } if (isset($offset)) { $sql .= ' offset ' . (int)$offset; } $result = $this->_db->fetchAll($sql); return $result; } /** * @return mixed */ public function getTotalCountDuplicates() { $sql = " SELECT count(1) AS `cnt` FROM ( SELECT `source_url` ,count(1) AS `cnt`, GROUP_CONCAT(`p`.`project_id` ORDER BY `p`.`created_at`) `pids` FROM `stat_projects_source_url` `p` GROUP BY `p`.`source_url` HAVING count(1)>1 ) `a` "; $result = $this->_db->fetchAll($sql); return $result[0]['cnt'];; } /** * @param string $source_url * * @return mixed */ public function getCountSourceUrl($source_url) { $last = substr($source_url, -1); if ($last == '/') { $source_url = substr($source_url, 0, -1); } $sql = " SELECT count(1) AS `cnt` FROM `stat_projects_source_url` `p` WHERE `p`.`source_url`= :source_url "; $result = $this->_db->fetchAll($sql, array('source_url' => $source_url)); return $result[0]['cnt']; } public function getSourceUrlProjects($source_url) { $last = substr($source_url, -1); if ($last == '/') { $source_url = substr($source_url, 0, -1); } $sql = " SELECT p.project_id, pj.title, pj.member_id, pj.created_at, pj.changed_at, m.username FROM stat_projects_source_url p inner join project pj on p.project_id = pj.project_id and pj.status=100 inner join member m on pj.member_id = m.member_id WHERE p.source_url= :source_url "; $result = $this->_db->fetchAll($sql, array('source_url' => $source_url)); return $result; } /** * @param int $member_id * * @return mixed */ public function getCountProjectsDuplicateSourceurl($member_id) { $sql = " SELECT count(1) AS `cnt` FROM ( SELECT `p`.`source_url` ,(SELECT count(1) FROM `stat_projects_source_url` `pp` WHERE `pp`.`source_url`=`p`.`source_url`) `cnt` FROM `stat_projects_source_url` `p` WHERE `p`.`member_id` = :member_id ) `t` WHERE `t`.`cnt`>1 "; $result = $this->_db->fetchAll($sql, array('member_id' => $member_id)); return $result[0]['cnt']; } /** * @param $ids * * @return Zend_Db_Table_Row_Abstract * @throws Zend_Db_Statement_Exception */ public function fetchProjects($ids) { $sql = "SELECT * FROM stat_projects WHERE project_id in (" . $ids . ") order by project_id"; $resultSet = $this->_db->fetchAll($sql); return $this->generateRowSet($resultSet); } /** * @param $project_id * @return true/false * @throws Zend_Db_Statement_Exception */ public function validateDeleteProjectFromSpam($project_id) { //produkt ist ueber 6 monate alt oder produkt hat ueber 5 kommentare oder produkt hat minimum 1 pling // darf nicht gelöscht werden $sql ='select count_comments ,created_at , (created_at+ INTERVAL 6 MONTH < NOW()) is_old ,(select count(1) from project_plings f where f.project_id = p.project_id and f.is_deleted = 0) plings FROM project p where project_id =:project_id'; $result = $this->_db->fetchRow($sql, array( 'project_id' => $project_id, )); if($result['count_comments'] >5 || $result['is_old'] ==1 || $result['plings']>0) { return false; } return true; } } diff --git a/application/modules/default/models/Views.php b/application/modules/default/models/Views.php index ac86d34ca..5eac386a7 100644 --- a/application/modules/default/models/Views.php +++ b/application/modules/default/models/Views.php @@ -1,110 +1,115 @@ . * */ class Default_Model_Views { const OBJECT_TYPE_PRODUCT = 10; const OBJECT_TYPE_MEMBERPAGE = 20; const OBJECT_TYPE_LOGIN = 30; const OBJECT_TYPE_LOGOUT = 32; const OBJECT_TYPE_DOWNLOAD = 40; const OBJECT_TYPE_COLLECTION = 50; public static function saveViewProduct($product_id) { - self::saveViewObject(self::OBJECT_TYPE_PRODUCT, $product_id); + $sql = ("INSERT IGNORE INTO `stat_object_view` (`seen_at`, `ip_inet`, `object_type`, `object_id`, `ipv4`, `ipv6`, `fingerprint`, `user_agent`, `member_id_viewer`) VALUES (:seen, :ip_inet, :object_type, :product_id, :ipv4, :ipv6, :fp, :ua, :member)"); + self::saveViewObject(self::OBJECT_TYPE_PRODUCT, $product_id, $sql); } - public static function saveViewObject($object_type, $object_id) + protected static function saveViewObject($object_type, $object_id, $sql) { - $sql = ("INSERT IGNORE INTO `stat_page_impression` (`seen_at`, `ip_inet`, `object_type`, `object_id`, `ipv4`, `ipv6`, `fingerprint`, `user_agent`, `member_id_viewer`) VALUES (:seen, :ip_inet, :object_type, :product_id, :ipv4, :ipv6, :fp, :ua, :member)"); $session = new Zend_Session_Namespace(); $view_member_id = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity()->member_id : null; $ipClient = Zend_Controller_Front::getInstance()->getRequest()->getClientIp(); $remoteAddress = self::getRemoteAddress($ipClient); $ipClientv6 = filter_var($remoteAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? $remoteAddress : null; $ipClientv4 = filter_var($remoteAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ? $remoteAddress : null; $session_ipv6 = isset($session->stat_ipv6) ? inet_pton($session->stat_ipv6) : null; $session_ipv4 = isset($session->stat_ipv4) ? inet_pton($session->stat_ipv4) : null; $session_remote = isset($remoteAddress) ? inet_pton($remoteAddress) : null; $ip_inet = isset($session_ipv6) ? $session_ipv6 : (isset($session_ipv4) ? $session_ipv4 : $session_remote); + $time = (round(time() / 300)) * 300; + $seen_at = date('Y-m-d H:i:s', $time); try { Zend_Db_Table::getDefaultAdapter()->query($sql, array( - 'seen' => round(time() / 300), + 'seen' => $seen_at, 'ip_inet' => $ip_inet, 'object_type' => $object_type, 'product_id' => $object_id, 'ipv6' => $session->stat_ipv6 ? $session->stat_ipv6 : $ipClientv6, 'ipv4' => $session->stat_ipv4 ? $session->stat_ipv4 : $ipClientv4, 'fp' => $session->stat_fp ? $session->stat_fp : null, 'ua' => $_SERVER['HTTP_USER_AGENT'] ? $_SERVER['HTTP_USER_AGENT'] : null, 'member' => $view_member_id )); } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR write - ' . print_r($e, true)); } } public static function getRemoteAddress($ipClient) { $iplist = explode(',', $ipClient); foreach ($iplist as $ip) { if (self::validate_ip($ip)) { return $ip; } } return null; } public static function validate_ip($ip) { $filter = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; if (APPLICATION_ENV == 'development') { $filter = FILTER_FLAG_NO_RES_RANGE; } if (filter_var($ip, FILTER_VALIDATE_IP, $filter) === false) { return false; } return true; } public static function saveViewMemberpage($member_id) { - self::saveViewObject(self::OBJECT_TYPE_MEMBERPAGE, $member_id); + $sql = ("INSERT IGNORE INTO `stat_object_view` (`seen_at`, `ip_inet`, `object_type`, `object_id`, `ipv4`, `ipv6`, `fingerprint`, `user_agent`, `member_id_viewer`) VALUES (:seen, :ip_inet, :object_type, :product_id, :ipv4, :ipv6, :fp, :ua, :member)"); + self::saveViewObject(self::OBJECT_TYPE_MEMBERPAGE, $member_id, $sql); } - public static function saveViewDownload($file_id) + public static function saveFileDownload($file_id) { - self::saveViewObject(self::OBJECT_TYPE_DOWNLOAD, $file_id); + $sql = ("INSERT IGNORE INTO `stat_object_download` (`seen_at`, `ip_inet`, `object_type`, `object_id`, `ipv4`, `ipv6`, `fingerprint`, `user_agent`, `member_id_viewer`) VALUES (:seen, :ip_inet, :object_type, :product_id, :ipv4, :ipv6, :fp, :ua, :member)"); + self::saveViewObject(self::OBJECT_TYPE_DOWNLOAD, $file_id, $sql); } public static function saveViewCollection($_projectId) { - self::saveViewObject(self::OBJECT_TYPE_COLLECTION, $_projectId); + $sql = ("INSERT IGNORE INTO `stat_object_view` (`seen_at`, `ip_inet`, `object_type`, `object_id`, `ipv4`, `ipv6`, `fingerprint`, `user_agent`, `member_id_viewer`) VALUES (:seen, :ip_inet, :object_type, :product_id, :ipv4, :ipv6, :fp, :ua, :member)"); + self::saveViewObject(self::OBJECT_TYPE_COLLECTION, $_projectId, $sql); } } \ No newline at end of file diff --git a/library/Local/CrawlerDetect.php b/library/Local/CrawlerDetect.php index a3aff3f72..2919221b3 100644 --- a/library/Local/CrawlerDetect.php +++ b/library/Local/CrawlerDetect.php @@ -1,114 +1,117 @@ . **/ /** crawler detection * @param $USER_AGENT * @return bool */ function crawlerDetect($USER_AGENT) { // If the user agent is empty, we assume that it is not a bot. if (empty($USER_AGENT)) { return false; } $crawlers = array( array('Googlebot', 'Googlebot'), array('MSN', 'MSN'), array('msnbot-media', 'MSN'), array('bingbot', 'MSN'), array('MegaIndex.ru' , 'MegaIndex.ru'), array('Baiduspider', 'Baiduspider'), array('YandexBot', 'YandexBot'), - array('AhrefsBot', 'ahrefs.com/robot'), + array('AhrefsBot', 'Mozilla/5.0 (compatible; AhrefsBot/6.1; +http://ahrefs.com/robot/)'), array('ltx71', 'ltx71'), array('msnbot', 'MSN'), array('Rambler', 'Rambler'), array('Yahoo', 'Yahoo'), array('AbachoBOT', 'AbachoBOT'), array('accoona', 'Accoona'), array('AcoiRobot', 'AcoiRobot'), array('ASPSeek', 'ASPSeek'), array('CrocCrawler', 'CrocCrawler'), array('Dumbot', 'Dumbot'), array('FAST-WebCrawler', 'FAST-WebCrawler'), array('GeonaBot', 'GeonaBot'), array('Gigabot', 'Gigabot'), array('Lycos', 'Lycos spider'), array('MSRBOT', 'MSRBOT'), array('Scooter', 'Altavista robot'), array('AltaVista', 'Altavista robot'), array('IDBot', 'ID-Search Bot'), array('eStyle', 'eStyle Bot'), array('Scrubby', 'Scrubby robot'), - array('MJ12bot','http://mj12bot.com/'), + array('MJ12bot','Mozilla/5.0 (compatible; MJ12bot/v1.4.8; http://mj12bot.com/)'), array('SemrushBot', 'SemrushBot'), array('bingbot','bingbot'), array('DotBot','http://www.opensiteexplorer.org/dotbot'), array('SEOkicks','https://www.seokicks.de/robot.html'), array('CCBot','CCBot/2.0 (https://commoncrawl.org/faq/)'), array('Sogou','Sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)'), array('Bytespider','Bytespider;https://zhanzhang.toutiao.com/'), array('BLEXBot','BLEXBot/1.0; +http://webmeup-crawler.com/'), array('Applebot','Applebot/0.1; +http://www.apple.com/go/applebot'), array('serpstatbot','serpstatbot/1.0 (advanced backlink tracking bot; curl/7.58.0; http://serpstatbot.com/; abuse@serpstatbot.com)'), array('Linespider','Linespider/1.1;+https://lin.ee/4dwXkTH'), array('Yeti','Yeti/1.1; +http://naver.me/spd'), array('Feedspot','Feedspot/1.0 (+https://www.feedspot.com/fs/fetcher; like FeedFetcher-Google)'), array('fantastic_search_engine_crawler','fantastic_search_engine_crawler/2.0 (Linux) fantastic-crawler@umich.edu'), array('Qwantify','Qwantify/Bleriot/1.1; +https://help.qwant.com/bot'), array('coccocbot','coccocbot-web/1.0; +http://help.coccoc.com/searchengine'), array('nagios-plugins','check_http/v2.2.1 (nagios-plugins 2.2.1)'), array('urlwatch','urlwatch/2.17 (+https://thp.io/2008/urlwatch/info.html)'), array('Buck','Buck/2.2; (+https://app.hypefactors.com/media-monitoring/about.html)'), array('Anitya','Anitya 0.17.2 at release-monitoring.org'), array('MauiBot','MauiBot (crawler.feedback+dc@gmail.com)'), array('istellabot','istellabot/t.1.13'), array('SeznamBot','Mozilla/5.0 (compatible; SeznamBot/3.2-test1; +http://napoveda.seznam.cz/en/seznambot-intro/)'), array('TelegramBot','TelegramBot (like TwitterBot)'), array('Synapse','Synapse/1.0.0'), array('VelenPublicWebCrawler','Mozilla/5.0 (compatible; VelenPublicWebCrawler/1.0; +https://velen.io)'), array('MagiBot','Mozilla/5.0 (compatible; MagiBot/1.0.0; Matarael; +https://magi.com/bots)'), array('linkfluence','Mozilla/5.0 (compatible; YaK/1.0; http://linkfluence.com/; bot@linkfluence.com)'), array('repology','repology-linkchecker/1 (+https://repology.org/bots)'), array('yacybot','Mozilla/5.0 (compatible; yacybot/1.921/custom +https://searx.everdot.org/about)'), array('facebookexternalhit','facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'), array('ZoominfoBot','ZoominfoBot (zoominfobot at zoominfo dot com)'), array('curl','curl/7.66.0'), array('ZoomBot','ZoomBot (Linkbot 1.0 http://suite.seozoom.it/bot.html)'), array('PaperLiBot','Mozilla/5.0 (compatible; PaperLiBot/2.1; https://support.paper.li/entries/20023257-what-is-paper-li)'), array('python-requests','python-requests/2.22.0'), array('Cliqzbot','Mozilla/5.0 (compatible; Cliqzbot/3.0; +http://cliqz.com/company/cliqzbot)'), array('YisouSpider','YisouSpider'), - array('trendictionbot','Mozilla/5.0 (Windows NT 10.0; Win64; x64; trendictionbot0.5.0; trendiction search; http://www.trendiction.de/bot; please let us know of any problems; web at trendiction.com) Gecko/20170101 Firefox/67.0') + array('trendictionbot','Mozilla/5.0 (Windows NT 10.0; Win64; x64; trendictionbot0.5.0; trendiction search; http://www.trendiction.de/bot; please let us know of any problems; web at trendiction.com) Gecko/20170101 Firefox/67.0'), + array('Jetslide','Mozilla/5.0 (compatible; Jetslide; +http://jetsli.de/crawler)'), + array('Seekport','Mozilla/5.0 (compatible; Seekport Crawler; http://seekport.com/)'), + array('GarlikCrawler','GarlikCrawler/1.2 (http://garlik.com/, crawler@garlik.com)') ); foreach ($crawlers as $c) { if (stristr($USER_AGENT, $c[0])) { return true; } } return false; } diff --git a/sql_code/20200115_create_stat_object_view.sql b/sql_code/20200115_create_stat_object_view.sql new file mode 100644 index 000000000..c68dc908a --- /dev/null +++ b/sql_code/20200115_create_stat_object_view.sql @@ -0,0 +1,39 @@ +USE `pling`; + +DROP TABLE IF EXISTS `stat_object_view`; +CREATE TABLE `stat_object_view` ( + `object_id` int(11) NOT NULL, + `object_type` int(11) NOT NULL, + `seen_at` datetime NOT NULL, + `ip_inet` varbinary(16) NOT NULL, + `member_id_viewer` int(11) DEFAULT '0', + `ipv6` varchar(50) DEFAULT '', + `ipv4` varchar(50) DEFAULT '', + `fingerprint` varchar(50) DEFAULT '', + `user_agent` varchar(255) DEFAULT '', + `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`object_id`,`object_type`,`seen_at`,`ip_inet`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1 + PARTITION BY HASH (EXTRACT(YEAR_MONTH FROM (`seen_at`))) + PARTITIONS 48 +; + +INSERT stat_object_view SELECT object_id,object_type,from_unixtime(`seen_at` * 300) as seen_at, ip_inet, member_id_viewer, ipv6, ipv4, fingerprint, user_agent, created_at FROM stat_page_impression; + +DROP TABLE IF EXISTS `stat_object_download`; +CREATE TABLE `stat_object_download` ( + `object_id` INT(11) NOT NULL, + `object_type` INT(11) NOT NULL, + `seen_at` DATETIME NOT NULL, + `ip_inet` VARBINARY(16) NOT NULL, + `member_id_viewer` INT(11) DEFAULT '0', + `ipv6` VARCHAR(50) DEFAULT '', + `ipv4` VARCHAR(50) DEFAULT '', + `fingerprint` VARCHAR(50) DEFAULT '', + `user_agent` VARCHAR(255) DEFAULT '', + `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`object_id` , `object_type` , `seen_at` , `ip_inet`) +) ENGINE=INNODB DEFAULT CHARSET=LATIN1 PARTITION BY HASH (EXTRACT(YEAR_MONTH FROM (`seen_at`))) PARTITIONS 48 +; + +INSERT stat_object_download SELECT object_id,object_type, seen_at, ip_inet, member_id_viewer, ipv6, ipv4, fingerprint, user_agent, created_at FROM stat_file_download;