member->username; ?>
member->firstname ) :?> member->firstname; ?> member->lastname; ?>member->pling_excluded == 1 ? ' checked=\'checked\' ' : ''; ?> /> user-pling-excluded
diff --git a/application/modules/backend/controllers/CdiscourseController.php b/application/modules/backend/controllers/CdiscourseController.php index df91fb7c6..b201ba707 100644 --- a/application/modules/backend/controllers/CdiscourseController.php +++ b/application/modules/backend/controllers/CdiscourseController.php @@ -1,343 +1,331 @@ . * * Created: 06.08.2018 */ class Backend_CdiscourseController extends Local_Controller_Action_CliAbstract { const filename = "members"; const filename_errors = "members"; protected $logfile; protected $errorlogfile; /** @var Zend_Config */ protected $config; protected $log; /** * @inheritDoc */ public function __construct( Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array() ) { parent::__construct($request, $response, $invokeArgs); $this->config = Zend_Registry::get('config')->settings->server->forum; $this->log = new Local_Log_File($this->config->user_logfilename, self::filename); $this->_helper->viewRenderer->setNoRender(false); } /** * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ public function runAction() { ini_set('memory_limit', '1024M'); $force = (boolean)$this->getParam('force', false); $method = $this->getParam('method', 'create'); $this->log->info("METHOD: {$method}\n--------------\n"); if ('delete' == $method) { //$this->deleteMember($this->getParam('member_id')); echo "not implemented"; return; } if ($this->hasParam('member_id')) { $memberId = $this->getParam('member_id'); $operator = $this->getParam('op', null); $members = $this->getMemberList($memberId, $operator); } else { $members = $this->getMemberList(); } if ('create' == $method) { $this->exportMembers($members, $force); return; } if ('update' == $method) { //$this->updateMembers($members); echo "not implemented"; return; } if ('validate' == $method) { //$this->validateMembers($members); echo "not implemented"; return; } if ('block' == $method) { $this->blockMembers($members); return; } if ('posts' == $method) { $this->postsMembers($members); return; } - if ('delete' == $method) { + if ('posts_delete' == $method) { $this->deletePostsMembers($members); return; } - if ('undelete' == $method) { + if ('posts_undelete' == $method) { $this->undeletePostsMembers($members); return; } if ('silence' == $method) { $this->silenceMembers($members); return; } } /** * @param null $member_id * @param string $operator * * @return Zend_Db_Statement_Interface * @throws Zend_Db_Statement_Exception */ private function getMemberList($member_id = null, $operator = "=") { $filter = ""; if (empty($operator)) { $operator = "="; } if ($operator == "gt") { $operator = ">"; } if ($operator == "lt") { $operator = "<"; } if (isset($member_id)) { $filter = " AND `m`.`member_id` {$operator} " . $member_id; } $sql = " SELECT `mei`.`external_id`,`m`.`member_id`, `m`.`username`, `me`.`email_address`, `m`.`password`, `m`.`roleId`, `m`.`firstname`, `m`.`lastname`, `m`.`profile_image_url`, `m`.`created_at`, `m`.`changed_at`, `m`.`source_id`, `m`.`biography`, `m`.`is_active`, `me`.`email_checked` FROM `member` AS `m` LEFT JOIN `member_email` AS `me` ON `me`.`email_member_id` = `m`.`member_id` AND `me`.`email_primary` = 1 LEFT JOIN `member_external_id` AS `mei` ON `mei`.`member_id` = `m`.`member_id` WHERE `m`.`is_active` = 1 AND `m`.`is_deleted` = 0 AND `me`.`email_checked` IS NOT NULL AND `me`.`email_deleted` = 0 AND LOCATE('_deactivated', `m`.`username`) = 0 AND LOCATE('_deactivated', `me`.`email_address`) = 0 " . $filter . " ORDER BY `m`.`member_id` ASC "; $result = Zend_Db_Table::getDefaultAdapter()->query($sql); $this->log->info("Load : " . $result->rowCount() . " members..."); return $result; } /** * @param Zend_Db_Statement_Interface $members * * @param bool $force * * @return bool * @throws Zend_Db_Statement_Exception * @throws Zend_Exception */ private function exportMembers($members, $force = false) { // only usernames which are valid in github/gitlab $usernameValidChars = new Local_Validate_UsernameValid(); $emailValidate = new Zend_Validate_EmailAddress(); $modelSubSystem = new Default_Model_Ocs_Forum($this->config); while ($member = $members->fetch()) { $this->log->info("process " . Zend_Json::encode($member)); echo "process " . Zend_Json::encode($member) . PHP_EOL; //if (false === $usernameValidChars->isValid($member['username'])) { // file_put_contents($this->errorlogfile, print_r($member, true) . "user name validation error" . "\n\n", FILE_APPEND); // continue; //} if (false === $emailValidate->isValid($member["email_address"])) { $this->log->info("messages [\"email address validation error\"] "); echo "response [\"email address validation error\"]" . PHP_EOL; continue; } try { //Export User, if he not exists $result = $modelSubSystem->createUserFromArray($member, $force); if (false === $result AND $modelSubSystem->hasRateLimitError()) { $this->log->info("RateLimitError: Wait " . $modelSubSystem->getRateLimitWaitSeconds() . " seconds for next execution."); sleep((int)$modelSubSystem->getRateLimitWaitSeconds()+5); $modelSubSystem = new Default_Model_Ocs_Forum($this->config); $modelSubSystem->createUserFromArray($member, $force); } } catch (Exception $e) { $this->log->info($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } $messages = $modelSubSystem->getMessages(); $this->log->info("messages " . Zend_Json::encode($messages)); echo "response " . Zend_Json::encode($messages) . PHP_EOL; } return true; } private function blockMembers($members) { $modelSubSystem = new Default_Model_Ocs_Forum($this->config); while ($member = $members->fetch()) { $result = $modelSubSystem->blockUser($member); if (false == $result) { $this->log->info('Fail'); } $messages = $modelSubSystem->getMessages(); if (false === empty($messages)) { $this->log->info("Message : " . Zend_Json::encode($messages)); } } } private function postsMembers($members) { $modelSubSystem = new Default_Model_Ocs_Forum($this->config); while ($member = $members->fetch()) { $result = $modelSubSystem->getPostsFromUser($member); if (false == $result) { $this->log->info('Fail'); } $this->log->info("Posts : " . Zend_Json::encode($result)); $messages = $modelSubSystem->getMessages(); if (false === empty($messages)) { $this->log->info("Message : " . Zend_Json::encode($messages)); } } } private function deletePostsMembers($members) { $modelSubSystem = new Default_Model_Ocs_Forum($this->config); while ($member = $members->fetch()) { - $result = $modelSubSystem->getPostsFromUser($member); - if (false == $result) { - $this->log->info('Fail'); - } - foreach ($result['posts'] as $item) { - $result = $modelSubSystem->deletePostFromUser($item['id']); - } + $result = $modelSubSystem->blockUserPosts($member); $this->log->info("Posts : " . Zend_Json::encode($result)); $messages = $modelSubSystem->getMessages(); if (false === empty($messages)) { $this->log->info("Message : " . Zend_Json::encode($messages)); } } } private function undeletePostsMembers($members) { $modelSubSystem = new Default_Model_Ocs_Forum($this->config); while ($member = $members->fetch()) { - $result = $modelSubSystem->getPostsFromUser($member); - if (false == $result) { - $this->log->info('Fail'); - } - foreach ($result['posts'] as $item) { - $result = $modelSubSystem->undeletePostFromUser($item['id']); - } + $result = $modelSubSystem->unblockUserPosts($member); $this->log->info("Posts : " . Zend_Json::encode($result)); $messages = $modelSubSystem->getMessages(); if (false === empty($messages)) { $this->log->info("Message : " . Zend_Json::encode($messages)); } } } private function silenceMembers($members) { $modelSubSystem = new Default_Model_Ocs_Forum($this->config); while ($member = $members->fetch()) { $result = $modelSubSystem->silenceUser($member); if (false == $result) { $this->log->info('Fail'); } $messages = $modelSubSystem->getMessages(); if (false === empty($messages)) { $this->log->info("Message : " . Zend_Json::encode($messages)); } } } public function groupAction() { $groupname = $this->getParam('name', null); $modelSubSystem = new Default_Model_Ocs_Forum($this->config); //$result = $modelSubSystem->createGroup($groupname); // //echo $result; // //$result = $modelSubSystem->deleteGroup($result); // //echo $result; $result = $modelSubSystem->getUserByEmail("info@dschinnweb.de"); print_r($result); echo json_encode($result); } private function deleteMember($member) { $modelSubSystem = new Default_Model_Ocs_Forum($this->config); try { //Export User, if he not exists $modelSubSystem->deleteUser($member); } catch (Exception $e) { $this->log->info($e->getMessage() . PHP_EOL . $e->getTraceAsString()); } $messages = $modelSubSystem->getMessages(); $this->log->info("messages " . Zend_Json::encode($messages)); echo "response " . Zend_Json::encode($messages) . PHP_EOL; } } \ No newline at end of file diff --git a/application/modules/backend/controllers/SpamkeywordsController.php b/application/modules/backend/controllers/SpamkeywordsController.php new file mode 100644 index 000000000..e7f757fb6 --- /dev/null +++ b/application/modules/backend/controllers/SpamkeywordsController.php @@ -0,0 +1,119 @@ +. + * + * Created: 11.01.2019 + */ + +class Backend_SpamkeywordsController extends Local_Controller_Action_Backend +{ + const RESULT_OK = "OK"; + const RESULT_ERROR = "ERROR"; + + /** @var Default_Model_DbTable_SpamKeywords */ + protected $_model; + + protected $_modelName = 'Default_Model_DbTable_SpamKeywords'; + + + /** + * + */ + public function init() + { + $this->_model = new $this->_modelName(); + + $this->view->pageTitle = 'Manage Spam Keywords'; + + parent::init(); + } + + public function indexAction() + { + + } + + public function createAction() + { + $jTableResult = array(); + try { + $newRow = $this->_model->createRow($this->getAllParams()); + $result = $newRow->save(); + + $jTableResult['Result'] = self::RESULT_OK; + $jTableResult['Record'] = $newRow->toArray(); + } catch (Exception $e) { + Zend_Registry::get('logger')->err(__METHOD__ . ' - ' . print_r($e, true)); + $translate = Zend_Registry::get('Zend_Translate'); + $jTableResult['Result'] = self::RESULT_ERROR; + $jTableResult['Message'] = $translate->_('Error while processing data.'); + } + + $this->_helper->json($jTableResult); + } + + public function updateAction() + { + $jTableResult = array(); + try { + $record = $this->_model->save($this->getAllParams()); + + $jTableResult = array(); + $jTableResult['Result'] = self::RESULT_OK; + $jTableResult['Record'] = $record->toArray(); + } catch (Exception $e) { + Zend_Registry::get('logger')->err(__METHOD__ . ' - ' . print_r($e, true)); + $translate = Zend_Registry::get('Zend_Translate'); + $jTableResult['Result'] = self::RESULT_ERROR; + $jTableResult['Message'] = $translate->_('Error while processing data.'); + } + + $this->_helper->json($jTableResult); + } + + public function deleteAction() + { + $id = (int)$this->getParam('spam_key_id', null); + + $this->_model->Delete(array('spam_key_id = ?' => $id)); + + $jTableResult = array(); + $jTableResult['Result'] = self::RESULT_OK; + + $this->_helper->json($jTableResult); + } + + public function listAction() + { + $startIndex = (int)$this->getParam('jtStartIndex'); + $pageSize = (int)$this->getParam('jtPageSize'); + $sorting = $this->getParam('jtSorting'); + + $result = $this->_model->listAll($startIndex, $pageSize, $sorting); + + $jTableResult = array(); + $jTableResult['Result'] = self::RESULT_OK; + $jTableResult['Records'] = $result['rows']; + $jTableResult['TotalRecordCount'] = $result['totalCount']; + + $this->_helper->json($jTableResult); + } + +} \ No newline at end of file diff --git a/application/modules/backend/views/scripts/spamkeywords/index.phtml b/application/modules/backend/views/scripts/spamkeywords/index.phtml new file mode 100644 index 000000000..5e6d88b6b --- /dev/null +++ b/application/modules/backend/views/scripts/spamkeywords/index.phtml @@ -0,0 +1,120 @@ +. + **/ +?> + + + + + +
+ + + \ No newline at end of file diff --git a/application/modules/default/controllers/ProductController.php b/application/modules/default/controllers/ProductController.php index 1409f0685..d621140a8 100644 --- a/application/modules/default/controllers/ProductController.php +++ b/application/modules/default/controllers/ProductController.php @@ -1,2636 +1,2650 @@ . **/ 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']; } 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 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( $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($this->view->product ); $fmodel =new Default_Model_DbTable_PploadFiles(); $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); $this->view->filesJson = Zend_Json::encode($files); $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 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); $this->view->product = $productInfo; if (empty($this->view->product)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $this->view->cat_id = $this->view->product->project_category_id; //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; $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); } if (APPLICATION_ENV != 'searchbotenv') { $tablePageViews = new Default_Model_DbTable_StatPageViews(); $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(), $this->_authMember->member_id); } $fmodel =new Default_Model_DbTable_PploadFiles(); $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); $this->view->filesJson = Zend_Json::encode($files); //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; } } } $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'); } } public function showAction() { $this->view->authMember = $this->_authMember; $this->_helper->viewRenderer('index'); $this->indexAction(); } public function addAction() { $form = new Default_Form_Product(); $this->view->member = $this->_authMember; $this->view->form = $form; $this->view->mode = 'add'; 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(); $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); } if ($values['is_original']) { $modelTags->processTagProductOriginal($newProject->project_id, $values['is_original']); } //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 (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")); + 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()); } - 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 * * @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)); } /** * @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); } //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)); 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->isProuductOriginal($projectData->project_id); if($is_original){ $form->getElement('is_original')->checked= true; } $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 $projectData->setFromArray($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->processTagProductOriginal($this->_projectId,$values['is_original']); 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' ); $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'); } 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'); } public function loadratingsAction() { $this->_helper->layout->disableLayout(); $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); $ratings = $tableProjectRatings->fetchRating($this->_projectId); $this->_helper->json($ratings); } 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()); } 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 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' )); } } 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.'; } /** * @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)) ) { 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 $projectData->changed_at = new Zend_Db_Expr('NOW()'); $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 $projectData->changed_at = new Zend_Db_Expr('NOW()'); $projectData->ghns_excluded = 0; $projectData->save(); } $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)); } /** * 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; } 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' ) { $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 updatepackagetypeAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $typeId = null; if (isset($_POST['package_type_id'])) { $typeId = $_POST['package_type_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->savePackagetypeTagForProject($this->_projectId, $_POST['file_id'], $typeId); $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)); } /** * 20180606 Ronald: egen Umstellung auf new tag system jetzt anders public function updatepackagetypeAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $typeId = null; if (isset($_POST['package_type_id'])) { $typeId = $_POST['package_type_id']; } $packageTypeTable = new Default_Model_DbTable_ProjectPackageType(); $packageTypeTable->addPackageTypeToProject($this->_projectId, $_POST['file_id'], $typeId); $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 updatearchitectureAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $architectureId = null; if (isset($_POST['architecture_id'])) { $architectureId = $_POST['architecture_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->saveArchitectureTagForProject($this->_projectId, $_POST['file_id'], $architectureId); $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 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) . '; $fileResponse->status: ' . $fileResponse->status; } } } $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')); } /** * 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')); }*/ 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)); } 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 $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 $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) ), $this->getAllParams()); 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'); } /** * @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', 'SAMEORIGIN', 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 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; } } diff --git a/application/modules/default/controllers/UserController.php b/application/modules/default/controllers/UserController.php index d6e0fd98b..c9f74dde8 100644 --- a/application/modules/default/controllers/UserController.php +++ b/application/modules/default/controllers/UserController.php @@ -1,639 +1,715 @@ . **/ class UserController extends Local_Controller_Action_DomainSwitch { protected $_memberId; protected $_userName; /** @var Zend_Db_Table_Row */ protected $_memberSettings; public function init() { parent::init(); if ($this->hasParam('user_name')) { $this->_userName = $this->getParam('user_name'); $this->_userName = urldecode($this->_userName); $modelMember = new Default_Model_Member(); $this->_memberId = $modelMember->fetchActiveUserByUsername($this->_userName); } else { $this->_memberId = (int)$this->getParam('member_id'); } } public function indexAction() { $this->_helper->viewRenderer('aboutme'); $this->aboutmeAction(); } public function aboutmeAction() { $tableMember = new Default_Model_Member(); $tableProject = new Default_Model_Project(); - + $earnModel = new Default_Model_StatDownload(); + $helperUserRole = new Backend_View_Helper_UserRole(); $pageLimit = 500; $projectpage = (int)$this->getParam('projectpage', 1); $this->view->authMember = $this->_authMember; //$this->view->member = $tableMember->find($this->_memberId)->current(); $this->view->member = $tableMember->fetchMemberData($this->_memberId); if (null == $this->view->member) { $this->redirect("/"); } if ($this->view->member->is_deleted == 1 or $this->view->member->is_active == 0) { $this->redirect("/"); } $this->view->mainProject = $this->view->member->findDependentRowset($tableProject, 'MainProject')->current(); - // TODOs - // $this->view->supportedProjects = $tableMember->fetchSupportedProjects($this->_memberId); + $this->view->userProjectCategories = $tableProject->getUserCreatingCategorys($this->_memberId); + $this->view->aboutmeUserInfo = $this->getAboutmeUserInfo($this->_memberId,$this->view->member->username); + - //Categories - /* - $catArray = array(); - foreach ($this->view->supportedProjects as $pro) { - $catArray[$pro->catTitle] = array(); - } + $userRoleName = $helperUserRole->userRole(); + if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { - $helperProductUrl = new Default_View_Helper_BuildProductUrl(); - foreach ($this->view->supportedProjects as $pro) { - $projArr = array(); - $projArr['name'] = $pro->title; - $projArr['image'] = $pro->image_small; - $projArr['url'] = $helperProductUrl->buildProductUrl($pro->project_id); - $projArr['sumAmount'] = $pro->sumAmount; - array_push($catArray[$pro->catTitle], $projArr); + $amount = $earnModel->getMonthEarn($this->_memberId,201812); + if($amount && $amount['amount']) + { + $this->view->earnInfo = ' Last month I earned $'.$amount['amount'].'.'; + }else + { + $this->view->earnInfo=' Last month I earned 0.'; + } + }else{ + $this->view->earnInfo=''; } - $this->view->supportingTeaser = $catArray; + - $this->view->followedProducts = $tableMember->fetchFollowedProjects($this->_memberId, null); - $this->view->hits = $tableMember->fetchProjectsSupported($this->_memberId); - */ // ajax load more products if ($this->getParam('projectpage', null)) { $total_records = $tableProject->countAllProjectsForMemberCatFilter($this->_memberId, true, null); $this->view->pageLimit = $pageLimit; $this->view->projectpage = $projectpage; $this->view->total_records = $total_records; - //$this->view->userProducts = $tableProject->fetchAllProjectsForMember($this->_memberId, $pageLimit, ($projectpage - 1) * $pageLimit,true); + + // get last project category id + $lastproject = $tableProject->getUserActiveProjects($this->_memberId, 1, (($projectpage - 1) * $pageLimit-1)); + foreach ($lastproject as $value) { + $this->view->lastcatid = $value['project_category_id']; + } + $this->view->userProducts = $tableProject->getUserActiveProjects($this->_memberId, $pageLimit, ($projectpage - 1) * $pageLimit); $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer('partials/aboutmeProducts'); //$this->forward('showmoreproductsajax', 'user', null, $this->getAllParams()); return; } else { $total_records = $tableProject->countAllProjectsForMemberCatFilter($this->_memberId, true, null); $this->view->pageLimit = $pageLimit; $this->view->projectpage = $projectpage; $this->view->total_records = $total_records; //$this->view->userProducts = $tableProject->fetchAllProjectsForMember($this->_memberId, $pageLimit, ($projectpage - 1) * $pageLimit,true); $this->view->userProducts = $tableProject->getUserActiveProjects($this->_memberId, $pageLimit, ($projectpage - 1) * $pageLimit); - + $this->view->userFeaturedProducts = $tableProject->fetchAllFeaturedProjectsForMember($this->_memberId); $paginationComments = $tableMember->fetchComments($this->_memberId); if ($paginationComments) { $offset = (int)$this->getParam('page'); $paginationComments->setItemCountPerPage(50); $paginationComments->setCurrentPageNumber($offset); $this->view->comments = $paginationComments; } // favs Currently no paging... $this->view->paramLikePageId = (int)$this->getParam('likepage'); $model = new Default_Model_DbTable_ProjectFollower(); $offset = $this->view->paramLikePageId; $list = $model->fetchLikesForMember($this->_memberId); $list->setItemCountPerPage(1000); $list->setCurrentPageNumber($offset); $this->view->likes = $list; // plings Currently no paging... $plingmodel = new Default_Model_ProjectPlings(); $offset = null; $plist = $plingmodel->fetchPlingsForMember($this->_memberId); $plist->setItemCountPerPage(1000); $plist->setCurrentPageNumber($offset); $this->view->plings = $plist; // plings Currently no paging... $plingmodel = new Default_Model_ProjectPlings(); $offset = null; $pslist = $plingmodel->fetchPlingsForSupporter($this->_memberId); $pslist->setItemCountPerPage(1000); $pslist->setCurrentPageNumber($offset); $this->view->supportersplings = $pslist; // rated $ratemodel = new Default_Model_DbTable_ProjectRating(); $this->view->rated = $ratemodel->getRatedForMember($this->_memberId); $stat = array(); $stat['cntProducts'] = $total_records; if ($this->view->userFeaturedProducts) { $cnt = 0; foreach ($this->view->userFeaturedProducts as $tmp) { $cnt++; } $stat['cntFProducts'] = $cnt; } else { $stat['cntFProducts'] = 0; } $stat['cntComments'] = $paginationComments->getTotalItemCount(); $tblFollower = new Default_Model_DbTable_ProjectFollower(); $stat['cntLikesHeGave'] = $tblFollower->countLikesHeGave($this->_memberId); $stat['cntLikesHeGot'] = $tblFollower->countLikesHeGot($this->_memberId); $tblPling = new Default_Model_DbTable_ProjectPlings(); $stat['cntPlingsHeGave'] = $tblPling->countPlingsHeGave($this->_memberId); $stat['cntPlingsHeGot'] = $tblPling->countPlingsHeGot($this->_memberId); $donationinfo = $tableMember->fetchSupporterDonationInfo($this->_memberId); if ($donationinfo) { $stat['donationIssupporter'] = $donationinfo['issupporter']; $stat['donationMax'] = $donationinfo['active_time_max']; $stat['donationMin'] = $donationinfo['active_time_min']; $stat['donationCnt'] = $donationinfo['cnt']; } // $cntmb = $tableMember->fetchCntSupporters($this->_memberId); // $stat['cntSupporters'] = $cntmb; $stat['userLastActiveTime'] = $tableMember->fetchLastActiveTime($this->_memberId); - $helperUserRole = new Backend_View_Helper_UserRole(); + $userRoleName = $helperUserRole->userRole(); if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $stat['cntDuplicateSourceurl'] = $tableProject->getCountProjectsDuplicateSourceurl($this->_memberId); } $this->view->stat = $stat; } } + public function getAboutmeUserInfo($member_id,$username) + { + $tableProject = new Default_Model_Project(); + $userProjectCategories = $tableProject->getUserCreatingCategorys($member_id); + $cnt = sizeof($userProjectCategories ); + $userinfo=''; + $isAdmin = false; + $helperUserRole = new Backend_View_Helper_UserRole(); + $userRoleName = $helperUserRole->userRole(); + if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName){ + $isAdmin= true; + } + if($cnt>0) + { + $userinfo = "Hi, I am ".$username." and I'm creating "; + if($cnt==1) + { + $userinfo = $userinfo.' '.$userProjectCategories[0]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[0]['cnt'].'].'; + } + }else if($cnt==2) + { + $userinfo = $userinfo.' '.$userProjectCategories[0]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[0]['cnt'].']'; + } + $userinfo = $userinfo.' and '.$userProjectCategories[1]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[1]['cnt'].'].'; + } + }else if($cnt==3) + { + $userinfo = $userinfo.' '.$userProjectCategories[0]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[0]['cnt'].']'; + } + $userinfo = $userinfo.', '.$userProjectCategories[1]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[1]['cnt'].']'; + } + $userinfo = $userinfo.' and '.$userProjectCategories[2]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[2]['cnt'].'].'; + } + }else if($cnt>3) + { + $userinfo = $userinfo.' '.$userProjectCategories[0]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[0]['cnt'].']'; + } + $userinfo = $userinfo.', '.$userProjectCategories[1]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[1]['cnt'].']'; + } + $userinfo = $userinfo.', '.$userProjectCategories[2]['category1'].''; + if($isAdmin) + { + $userinfo = $userinfo.'['.$userProjectCategories[2]['cnt'].']'; + } + $userinfo = $userinfo.' and more.'; + } + } + return $userinfo; + } public function avatarAction() { $this->_helper->layout->disableLayout(); $size = (int)$this->getParam("size", 200); $width = (int)$this->getParam("width", ($size / 2)); $this->view->size = (int)$size / 2; $emailHash = $this->getParam("emailhash", null); if ($emailHash) { $memberTable = new Default_Model_Member(); $member = $memberTable->findMemberForMailHash($emailHash); if ($member) { $helperImage = new Default_View_Helper_Image(); $imgUrl = $helperImage->Image($member['profile_image_url'], array('width' => $width, 'height' => $width)); $this->view->avatar = $imgUrl; $this->redirect($imgUrl); return; } } $this->view->avatar = ""; $helperImage = new Default_View_Helper_Image(); $imgUrl = $helperImage->Image("default-profile.png", array('width' => $width, 'height' => $width)); $this->redirect($imgUrl); } public function aboutAction() { $modelMember = new Default_Model_Member(); $this->view->member = $modelMember->fetchMember($this->_memberId)->toArray(); $this->view->currentPageOffset = (int)$this->getParam('page'); } public function showmoreproductsajaxAction() { $this->_helper->layout->disableLayout(); $tableProject = new Default_Model_Project(); $pageLimit = 21; $page = (int)$this->getParam('page', 1); $total_records = $tableProject->countAllProjectsForMemberCatFilter($this->_memberId, true, null); $this->view->pageLimit = $pageLimit; $this->view->page = $page; $this->view->total_records = $total_records; $this->view->userProducts = $tableProject->fetchAllProjectsForMember($this->_memberId, $pageLimit, ($page - 1) * $pageLimit, true); $this->_helper->viewRenderer('/partials/aboutmeProducts'); } public function userdataajaxAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $resultArray = array(); header('Access-Control-Allow-Origin: *'); $this->getResponse()->setHeader('Access-Control-Allow-Origin', '*')->setHeader('Access-Control-Allow-Credentials', 'true') ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept') ; $userid = $this->getParam('id'); $modelMember = new Default_Model_Member(); $user = $modelMember->find($userid)->current(); if (Zend_Auth::getInstance()->hasIdentity()) { $auth = Zend_Auth::getInstance(); $user = $auth->getStorage()->read(); $resultArray['member_id'] = $user->member_id; $resultArray['username'] = $user->username; $resultArray['mail'] = $user->mail; $resultArray['avatar'] = $user->profile_image_url; } else if (null != $userid && null != $user) { $resultArray['member_id'] = $user['member_id']; $resultArray['username'] = $user['username']; $resultArray['mail'] = $user['mail']; $resultArray['avatar'] = $user['profile_image_url']; } else { $resultArray['member_id'] = null; $resultArray['username'] = null; $resultArray['mail'] = null; $resultArray['avatar'] = null; } $resultAll = array(); $resultAll['status'] = "success"; $resultAll['data'] = $resultArray; $this->_helper->json($resultAll); } public function followsAction() { $this->redirect($this->_helper->url('follows', 'member', null, $this->getAllParams())); } public function followAction() { $this->_helper->layout->disableLayout(); $this->view->authMember = $this->_authMember; $this->view->member_id = $this->_memberId; if ($this->_memberId == $this->_authMember->member_id) { return; } $memberFollowTable = new Default_Model_DbTable_MemberFollower(); $newVals = array('member_id' => $this->_memberId, 'follower_id' => (int)$this->_authMember->member_id); $where = $memberFollowTable->select()->where('member_id = ?', $this->_memberId) ->where('follower_id = ?', $this->_authMember->member_id, 'INTEGER') ; $result = $memberFollowTable->fetchRow($where); if (null === $result) { $memberFollowTable->createRow($newVals)->save(); } } public function unfollowAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer('follow'); $memberFollowTable = new Default_Model_DbTable_MemberFollower(); $memberFollowTable->delete('member_id=' . $this->_memberId . ' AND follower_id=' . $this->_authMember->member_id); $this->view->authMember = $this->_authMember; $this->view->member_id = $this->_memberId; } public function newsAction() { $this->productsAction(); $this->render('products'); } public function productsAction() { $pageLimit = 25; $page = (int)$this->getParam('page', 1); //create ppload download hash: secret + collection_id + expire-timestamp $salt = PPLOAD_DOWNLOAD_SECRET; $timestamp = time() + 3600; // one hour valid $hash = md5($salt . $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 = null; if (null != $this->_authMember && null != $this->_authMember->member_id) { $this->view->member_id = $this->_authMember->member_id; } $modelProject = new Default_Model_Project(); $userProjects = $modelProject->fetchAllProjectsForMember($this->_authMember->member_id, $pageLimit, ($page - 1) * $pageLimit); $paginator = Local_Paginator::factory($userProjects); $paginator->setItemCountPerPage($pageLimit); $paginator->setCurrentPageNumber($page); $paginator->setTotalItemCount($modelProject->countAllProjectsForMember($this->_authMember->member_id)); $this->view->products = $paginator; $modelMember = new Default_Model_Member(); $this->view->member = $modelMember->fetchMemberData($this->_authMember->member_id); } public function activitiesAction() { $modelInfo = new Default_Model_Info(); $this->view->member = $this->_authMember; $this->view->comments = $modelInfo->getLastCommentsForUsersProjects($this->_authMember->member_id); $this->view->votes = $modelInfo->getLastVotesForUsersProjects($this->_authMember->member_id); $this->view->donations = $modelInfo->getLastDonationsForUsersProjects($this->_authMember->member_id); } public function settingsAction() { $this->_helper->layout()->setLayout('settings'); } public function reportAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer('product/add'); $this->forward('report', 'product', null, $this->getAllParams()); } public function paymentsAction() { $this->view->headScript()->setFile(''); $this->view->headLink()->setStylesheet(''); $member_id = $this->_authMember->member_id; $this->view->member = $this->_authMember; $tableMember = new Default_Model_Member(); $this->view->hits = $tableMember->fetchPlingedProjects($member_id); } public function incomeAction() { $this->view->member = $this->_authMember; $tableMember = new Default_Model_Member(); $modelPlings = new Default_Model_Pling(); $this->view->donations = $modelPlings->fetchRecentDonationsForUser($this->_authMember->member_id); } public function tooltipAction() { $this->_helper->layout->disableLayout(); $info = new Default_Model_Info(); $data = $info->getTooptipForMember($this->_memberId); $this->_helper->json(array('status' => 'ok', 'data' => $data)); } public function shareAction() { $this->_helper->layout->disableLayout(); $modelProduct = new Default_Model_Member(); $memberInfo = $modelProduct->fetchMemberData($this->_memberId); $form = new Default_Form_ProjectShare(); $form->setAction('/member/' . $this->_memberId . '/share/'); // $helperBaseUrl = new Default_View_Helper_BaseUrl(); // $helperServerUrl = new Zend_View_Helper_ServerUrl(); $helpMemberUrl = new Default_View_Helper_BuildMemberUrl(); $this->view->permaLink = $helpMemberUrl->buildMemberUrl($memberInfo->username); // $this->view->permaLink = $helperServerUrl->serverUrl() . $helperBaseUrl->baseUrl() . '/member/' . $this->_memberId . '/'; if ($this->_request->isGet()) { $this->view->form = $form; $this->renderScript('product/share.phtml'); return; } if (false === $form->isValid($_POST)) { // form not valid $this->view->form = $form; $dummy = $this->view->render('product/share.phtml'); $this->_helper->json(array('status' => 'ok', 'message' => $dummy)); return; } $values = $form->getValues(); if (empty($memberInfo->firstname) and empty($memberInfo->lastname)) { $username = $memberInfo->username; } else { $username = $memberInfo->firstname . ' ' . $memberInfo->lastname; } $shareMail = new Default_Plugin_SendMail('tpl_social_mail_user'); $shareMail->setTemplateVar('sender', $values['sender_mail']); $shareMail->setTemplateVar('username', $username); $shareMail->setTemplateVar('permalink', $this->view->permaLink); $shareMail->setTemplateVar('permalinktext', 'View user\'s page'); $shareMail->setReceiverMail($values['mail']); $shareMail->send(); $this->_helper->json(array('status' => 'ok', 'redirect' => $this->view->permaLink)); } public function plingsAction() { $tableMember = new Default_Model_Member(); $this->view->view_member = $tableMember->fetchMemberData($this->_memberId); $paypalValidStatusTable = new Default_Model_DbTable_PaypalValidStatus(); $paypalValidStatus = $paypalValidStatusTable->find($this->view->view_member->paypal_valid_status)->current(); $this->view->paypal_valid_status = $paypalValidStatus; //backdoor for admins $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $this->view->member = $this->view->view_member; } else { $this->view->member = $this->_authMember; } } public function downloadhistoryAction() { $tableMember = new Default_Model_Member(); $this->view->view_member = $tableMember->fetchMemberData($this->_memberId); //backdore for admins $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $this->view->member = $this->view->view_member; } else { $this->view->member = $this->_authMember; } if ($this->view->member) { $this->view->paramPageId = (int)$this->getParam('page'); //TODO do really sql paging instead of Zend_Paginator $dhistory = new Default_Model_DbTable_MemberDownloadHistory(); $offset = $this->view->paramPageId; $list = $dhistory->getDownloadhistory($this->view->member->member_id); $list->setItemCountPerPage(250); $list->setCurrentPageNumber($offset); $this->view->downloadhistory = $list; } else { $this->view->downloadhistory = array(); } } public function likesAction() { $tableMember = new Default_Model_Member(); $this->view->view_member = $tableMember->fetchMemberData($this->_memberId); //backdore for admins $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $this->view->member = $this->view->view_member; } else { $this->view->member = $this->_authMember; } if ($this->view->member) { $this->view->paramPageId = (int)$this->getParam('page'); $model = new Default_Model_DbTable_ProjectFollower(); $offset = $this->view->paramPageId; $list = $model->fetchLikesForMember($this->view->member->member_id); $list->setItemCountPerPage(250); $list->setCurrentPageNumber($offset); $this->view->likes = $list; } else { $this->view->likes = array(); } } public function payoutAction() { $tableMember = new Default_Model_Member(); $this->view->view_member = $tableMember->fetchMemberData($this->_memberId); //backdore for admins $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) { $this->view->member = $this->view->view_member; } else { $this->view->member = $this->_authMember; } } /** * @return Default_Form_Settings * @throws Zend_Form_Exception */ private function formPassword() { $form = new Default_Form_Settings(); $form->setMethod("POST")->setAttrib("id", "settingsPasswordForm")->setAction('/member/' . $this->_memberId . '/changepass'); $passOld = $form->createElement('password', 'passwordOld')->setLabel('Enter old Password:')->setRequired(true) ->removeDecorator('HtmlTag')->addValidator(new Local_Validate_OldPasswordConfirm())->setDecorators(array( 'ViewHelper', 'Label', 'Errors', array( 'ViewScript', array( 'viewScript' => 'settings/viewscripts/flatui_input.phtml', 'placement' => false ) ) )) ; $pass1 = $form->createElement('password', 'password1')->setLabel('Enter new Password:')->setRequired(true) ->addValidator(new Zend_Validate_NotEmpty(Zend_Validate_NotEmpty::STRING))->removeDecorator('HtmlTag') ->setDecorators(array( 'ViewHelper', 'Label', 'Errors', array( 'ViewScript', array( 'viewScript' => 'settings/viewscripts/flatui_input.phtml', 'placement' => false ) ) )) ; $pass2 = $form->createElement('password', 'password2')->setLabel('Re-enter new Password:')->setRequired(true) ->addValidator(new Zend_Validate_NotEmpty(Zend_Validate_NotEmpty::STRING))->removeDecorator('HtmlTag') ->setDecorators(array( 'ViewHelper', 'Label', 'Errors', array( 'ViewScript', array( 'viewScript' => 'settings/viewscripts/flatui_input.phtml', 'placement' => false ) ) )) ; $passValid = new Local_Validate_PasswordConfirm($pass2->getValue()); $pass1->addValidator($passValid); $form->addElement($passOld)->addElement($pass1)->addElement($pass2); return $form; } } \ No newline at end of file diff --git a/application/modules/default/models/DbTable/SpamKeywords.php b/application/modules/default/models/DbTable/SpamKeywords.php new file mode 100644 index 000000000..405812df6 --- /dev/null +++ b/application/modules/default/models/DbTable/SpamKeywords.php @@ -0,0 +1,65 @@ +. + **/ +class Default_Model_DbTable_SpamKeywords extends Local_Model_Table +{ + + protected $_name = "spam_keywords"; + + protected $_keyColumnsForRow = array('spam_key_id'); + + protected $_key = 'spam_key_id'; + + public function delete($where) + { + $where = parent::_whereExpr($where); + + /** + * Build the DELETE statement + */ + $sql = "UPDATE " . parent::getAdapter()->quoteIdentifier($this->_name, true) . " SET `spam_key_is_deleted` = 1, `spam_key_is_active` = 0 " . (($where) ? " WHERE $where" : ''); + + /** + * Execute the statement and return the number of affected rows + */ + $stmt = parent::getAdapter()->query($sql); + $result = $stmt->rowCount(); + + return $result; + } + + public function listAll($startIndex, $pageSize, $sorting) + { + $select = $this->select()->order($sorting)->limit($pageSize, $startIndex); + $rows = $this->fetchAll($select)->toArray(); + $select = $this->select()->where('spam_key_is_active = 1'); + $count = $this->fetchAll($select)->count(); + + if (empty($rows)) { + return array('rows' => array(), 'totalCount' => 0); + } + + return array('rows' => $rows, 'totalCount' => $count); + } + + +} \ No newline at end of file diff --git a/application/modules/default/models/Info.php b/application/modules/default/models/Info.php index 6b0418541..ccd342c02 100644 --- a/application/modules/default/models/Info.php +++ b/application/modules/default/models/Info.php @@ -1,1275 +1,1299 @@ . **/ class Default_Model_Info { const WALLPAPERCATEGORYID = '295'; const TAG_ISORIGINAL = 'original-product'; public function getLast200ImgsProductsForAllStores($limit = 200) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . md5('getLast200ImgsProductsForAllStores' . $limit); if ($resultSet = $cache->load($cacheName)) { return $resultSet; } else { $activeCategories = $this->getActiveCategoriesForAllStores(); $sql = ' SELECT image_small ,project_id ,title FROM project WHERE project.image_small IS NOT NULL AND project.status = 100 AND project.project_category_id IN (' . implode(',', $activeCategories) . ') ORDER BY ifnull(project.changed_at, project.created_at) DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 14400); return $resultSet; } else { return array(); } } } public function getActiveStoresForCrossDomainLogin($limit = null) { $sql = ' SELECT DISTINCT config_store.host FROM config_store WHERE config_store.cross_domain_login = 1 ORDER BY config_store.order; '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $values = array_map(function ($row) { return $row['host']; }, $resultSet); return $values; } else { return array(); } } public function getActiveCategoriesForAllStores($limit = null) { $sql = ' SELECT DISTINCT config_store_category.project_category_id FROM config_store JOIN config_store_category ON config_store.store_id = config_store_category.store_id JOIN project_category ON config_store_category.project_category_id = project_category.project_category_id WHERE project_category.is_active = 1 ORDER BY config_store_category.`order`; '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $values = array_map(function ($row) { return $row['project_category_id']; }, $resultSet); return $values; } else { return array(); } } + public function countTotalActiveMembers() + { + + $cacheName = __FUNCTION__ . md5('countTotalActiveMembers'); + $cache = Zend_Registry::get('cache'); + + $result = $cache->load($cacheName); + + if ($result) { + return (int)$result['count_active_members']; + } + + $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 + GROUP BY p.member_id + ) AS `A`;"; + + $result = $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchRow($sql); + $cache->save($result, $cacheName); + return (int)$result['count_active_members']; + } + /** * if category id not set the latest comments for all categories on the current host wil be returned. * * @param int $limit * @param int|null $project_category_id * * @return array * @throws Zend_Cache_Exception * @throws Zend_Exception */ public function getLatestComments($limit = 5, $project_category_id = null,$package_type = null) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_new_' . md5(Zend_Registry::get('store_host') . (int)$limit . (int)$project_category_id.$package_type); if (($latestComments = $cache->load($cacheName))) { return $latestComments; } if (empty($project_category_id)) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); } else { $activeCategories = $this->getActiveCategoriesForCatId($project_category_id); } if (count($activeCategories) == 0) { return array(); } $sql = ' SELECT comment_id ,comment_text ,member.member_id ,member.profile_image_url ,comment_created_at ,member.username ,comment_target_id ,title ,stat_projects.project_id ,cat_title as catTitle FROM comments STRAIGHT_JOIN member ON comments.comment_member_id = member.member_id inner JOIN stat_projects ON comments.comment_target_id = stat_projects.project_id '; $sql .= ' WHERE comments.comment_active = 1 AND stat_projects.status = 100 AND stat_projects.type_id = 1 AND comments.comment_type = 0 AND stat_projects.project_category_id IN (' . implode(',', $activeCategories) . ') '; if(isset($package_type)) { $sql .= ' AND find_in_set('.$package_type.', stat_projects.package_types)'; } $sql .=' ORDER BY comments.comment_created_at DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save(array(), $cacheName, array(), 300); return array(); } } /** * @param int $omitCategoryId * * @return array * @TODO: check all occurrences of this function */ public function getActiveCategoriesForCurrentHost($omitCategoryId = null) { $currentHostMainCategories = Zend_Registry::get('store_category_list'); $modelCategory = new Default_Model_DbTable_ProjectCategory(); $activeChildren = $modelCategory->fetchChildIds($currentHostMainCategories); $activeCategories = array_unique(array_merge($currentHostMainCategories, $activeChildren)); if (empty($omitCategoryId)) { return $activeCategories; } $omitChildren = $modelCategory->fetchChildIds($omitCategoryId); return array_diff($activeCategories, $omitChildren); } /** * @param int $project_category_id * @param int|null $omitCategoryId * * @return array */ public function getActiveCategoriesForCatId($project_category_id, $omitCategoryId = null) { $modelCategory = new Default_Model_DbTable_ProjectCategory(); $activeChildren = $modelCategory->fetchChildIds($project_category_id); $activeCategories = array_unique(array_merge(array($project_category_id), $activeChildren)); if (empty($omitCategoryId)) { return $activeCategories; } $omitChildren = $modelCategory->fetchChildIds($omitCategoryId); return array_diff($activeCategories, $omitChildren); } /** * if category id not set the latest plings for all categories on the current host wil be returned. * * @param int $limit * @param null $project_category_id * * @return array|false|mixed */ /*/* public function getLatestPlings($limit = 5, $project_category_id = null) { /** @var Zend_Cache_Core $cache $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$limit . (int)$project_category_id); if (($latestPlings = $cache->load($cacheName))) { return $latestPlings; } if (empty($project_category_id)) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); } else { $activeCategories = $this->getActiveCategoriesForCatId($project_category_id); } if (count($activeCategories) == 0) { return array(); } $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; $storePackageTypeIds = null; if ($storeConfig) { $storePackageTypeIds = $storeConfig['package_type']; } $sql = ' SELECT plings.project_id, plings.id ,member.member_id ,profile_image_url ,plings.create_time ,username ,plings.amount ,comment ,project.title FROM plings JOIN project ON project.project_id = plings.project_id STRAIGHT_JOIN member ON plings.member_id = member.member_id'; if ($storePackageTypeIds) { $sql .= ' JOIN (SELECT DISTINCT project_id FROM project_package_type WHERE package_type_id in (' . $storePackageTypeIds . ')) package_type ON project.project_id = package_type.project_id'; } $sql .= ' WHERE plings.status_id = 2 AND project.status <> 30 AND project.project_category_id IN (' . implode(',', $activeCategories) . ') ORDER BY plings.create_time DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save(array(), $cacheName, array(), 300); return array(); } }*/ /** * if category id not set the most downloaded products for all categories on the current host wil be returned. * * @param int $limit * @param null $project_category_id * * @return array|false|mixed */ public function getMostDownloaded($limit = 100, $project_category_id = null, $package_type=null) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_new_' . md5(Zend_Registry::get('store_host') . (int)$limit . (int)$project_category_id.$package_type); if (($mostDownloaded = $cache->load($cacheName))) { return $mostDownloaded; } if (empty($project_category_id)) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); } else { $activeCategories = $this->getActiveCategoriesForCatId($project_category_id); } if (count($activeCategories) == 0) { return array(); } $sql = ' SELECT p.project_id ,p.title ,p.image_small ,s.amount ,s.category_title ,p.package_types FROM stat_downloads_quarter_year s INNER JOIN stat_projects p ON s.project_id = p.project_id'; $sql .= ' WHERE p.status=100 and p.project_category_id IN (' . implode(',', $activeCategories) . ') '; if(isset($package_type)) { $sql .= ' AND find_in_set('.$package_type.', p.package_types)'; } $sql .= ' ORDER BY s.amount DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save($resultSet, $cacheName, array(), 300); return array(); } } public function getLastProductsForHostStores($limit = 10, $project_category_id = null, $package_type = null,$tag_isoriginal = null) { /** @var Zend_Cache_Core $cache */ if($project_category_id) { $catids = str_replace(',', '', (string)$project_category_id); }else { $catids=""; } $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$limit .$catids.$package_type.$tag_isoriginal); if (($resultSet = $cache->load($cacheName))) { return $resultSet; } $activeCategories =array(); if (empty($project_category_id)) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); } else { $cats = explode(",", $project_category_id); if(count($cats)==1){ $activeCategories = $this->getActiveCategoriesForCatId($project_category_id); }else{ foreach ($cats as $cat) { $tmp = $this->getActiveCategoriesForCatId($cat); $activeCategories = array_merge($tmp, $activeCategories); } } } if (count($activeCategories) == 0) { return array(); } $sql = ' SELECT p.* FROM stat_projects AS p WHERE p.status = 100 AND p.project_category_id IN (' . implode(',', $activeCategories) . ') AND p.amount_reports is null'; if(isset($package_type)) { $sql .= ' AND find_in_set('.$package_type.', package_types)'; } if(isset($tag_isoriginal)) { if($tag_isoriginal) { $sql .= ' AND find_in_set("'.self::TAG_ISORIGINAL.'", tags)'; }else{ $sql .= ' AND NOT find_in_set("'.self::TAG_ISORIGINAL.'", tags)'; } } $sql .= ' ORDER BY IFNULL(p.changed_at,p.created_at) DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save($resultSet, $cacheName, array(), 300); return array(); } } public function getJsonLastProductsForHostStores($limit = 10, $project_category_id = null, $package_type = null,$tag_isoriginal = null, $offset = 0) { /** @var Zend_Cache_Core $cache */ if($project_category_id) { $catids = str_replace(',', '_', (string)$project_category_id); }else { $catids=""; } $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$limit .$catids.$package_type.$tag_isoriginal.$offset); if (($resultSet = $cache->load($cacheName))) { return $resultSet; } $activeCategories =array(); if (empty($project_category_id)) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); } else { $cats = explode(",", $project_category_id); if(count($cats)==1){ $activeCategories = $this->getActiveCategoriesForCatId($project_category_id); }else{ foreach ($cats as $cat) { $tmp = $this->getActiveCategoriesForCatId($cat); $activeCategories = array_merge($tmp, $activeCategories); } } } if (count($activeCategories) == 0) { return array(); } $sql = ' SELECT project_id, member_id, image_small, title, version, cat_title, count_comments, package_names, laplace_score, count_likes, count_dislikes, changed_at, created_at FROM stat_projects AS p WHERE p.status = 100 AND p.project_category_id IN (' . implode(',', $activeCategories) . ') AND p.amount_reports is null'; if(isset($package_type)) { $sql .= ' AND find_in_set('.$package_type.', package_types)'; } if(isset($tag_isoriginal)) { if($tag_isoriginal) { $sql .= ' AND find_in_set("'.self::TAG_ISORIGINAL.'", tags)'; }else{ $sql .= ' AND NOT find_in_set("'.self::TAG_ISORIGINAL.'", tags)'; } } $sql .= ' ORDER BY IFNULL(p.changed_at,p.created_at) DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } if (isset($offset)) { $sql .= ' offset ' . (int)$offset; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); $imagehelper = new Default_View_Helper_Image(); foreach ($resultSet as &$value) { $value['project_image_small_uri'] = $imagehelper->Image($value['image_small'], array('width' => 80, 'height' => 80)); } if (count($resultSet) > 0) { $result = Zend_Json::encode($resultSet); $cache->save($result, $cacheName, array(), 300); return $result; } else { return Zend_Json::encode(''); } } public function getTopProductsForHostStores($limit = 10, $project_category_id = null, $package_type = null) { /** @var Zend_Cache_Core $cache */ if($project_category_id) { $catids = str_replace(',', '', (string)$project_category_id); }else { $catids=""; } $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$limit .$catids.$package_type); if (($resultSet = $cache->load($cacheName))) { return $resultSet; } $activeCategories =array(); if (empty($project_category_id)) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); } else { $cats = explode(",", $project_category_id); if(count($cats)==1){ $activeCategories = $this->getActiveCategoriesForCatId($project_category_id); }else{ foreach ($cats as $cat) { $tmp = $this->getActiveCategoriesForCatId($cat); $activeCategories = array_merge($tmp, $activeCategories); } } } if (count($activeCategories) == 0) { return array(); } $sql = ' SELECT p.* FROM stat_projects AS p WHERE p.status = 100 AND p.project_category_id IN (' . implode(',', $activeCategories) . ') AND p.amount_reports is null'; if(isset($package_type)) { $sql .= ' AND find_in_set('.$package_type.', package_types)'; } $sql .= ' ORDER BY (round(((count_likes + 6) / ((count_likes + count_dislikes) + 12)),2) * 100) DESC, created_at DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save($resultSet, $cacheName, array(), 300); return array(); } } public function getRandomStoreProjectIds() { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host')); $resultSet = $cache->load($cacheName); if(false ==$resultSet) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); if (count($activeCategories) == 0) { return array(); } $sql = ' SELECT p.project_id FROM project AS p WHERE p.status = 100 AND p.type_id = 1 AND p.project_category_id IN ('. implode(',', $activeCategories).') '; $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); $cache->save($resultSet, $cacheName, array(), 3600 * 24); } $irandom = rand(0,sizeof($resultSet)); return $resultSet[$irandom]; } public function getRandProduct(){ $pid = $this->getRandomStoreProjectIds(); $project_id = $pid['project_id']; $sql = ' SELECT p.* ,laplace_score(p.count_likes, p.count_dislikes) AS laplace_score ,m.profile_image_url ,m.username FROM project AS p JOIN member AS m ON m.member_id = p.member_id WHERE p.project_id = :project_id '; $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('project_id' => $project_id)); if (count($resultSet) > 0) { return new Zend_Paginator(new Zend_Paginator_Adapter_Array($resultSet)); } else { return new Zend_Paginator(new Zend_Paginator_Adapter_Array(array())); } } // public function getRandProduct_(){ // $activeCategories = $this->getActiveCategoriesForCurrentHost(); // if (count($activeCategories) == 0) { // return array(); // } // $sql = ' // SELECT // p.* // ,laplace_score(p.count_likes, p.count_dislikes) AS laplace_score // ,m.profile_image_url // ,m.username // FROM // project AS p // JOIN // member AS m ON m.member_id = p.member_id // WHERE // p.status = 100 // AND p.type_id = 1 // AND p.project_category_id IN ('. implode(',', $activeCategories).') // ORDER BY RAND() LIMIT 1 // '; // $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); // if (count($resultSet) > 0) { // return new Zend_Paginator(new Zend_Paginator_Adapter_Array($resultSet)); // } else { // return new Zend_Paginator(new Zend_Paginator_Adapter_Array(array())); // } // } /** * @param int $limit * @param null $project_category_id * * @return array|Zend_Paginator */ public function getFeaturedProductsForHostStores($limit = 10, $project_category_id = null) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$limit . (int)$project_category_id); if (false !== ($resultSet = $cache->load($cacheName))) { return new Zend_Paginator(new Zend_Paginator_Adapter_Array($resultSet)); } if (empty($project_category_id)) { $activeCategories = $this->getActiveCategoriesForCurrentHost(); } else { $activeCategories = $this->getActiveCategoriesForCatId($project_category_id); } if (count($activeCategories) == 0) { return array(); } $sql = ' SELECT p.* ,m.profile_image_url ,m.username FROM stat_projects AS p JOIN member AS m ON m.member_id = p.member_id WHERE p.status = 100 AND p.type_id = 1 AND p.featured = 1 AND p.project_category_id IN ('. implode(',', $activeCategories).') '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql); $cache->save($resultSet, $cacheName, array(), 60); if (count($resultSet) > 0) { return new Zend_Paginator(new Zend_Paginator_Adapter_Array($resultSet)); } else { return new Zend_Paginator(new Zend_Paginator_Adapter_Array(array())); } } public function getLastCommentsForUsersProjects($member_id, $limit = 10) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$member_id . (int)$limit); if (false !== ($resultSet = $cache->load($cacheName))) { return $resultSet; } $sql = ' SELECT comment_id ,comment_text , member.member_id ,comment_created_at ,username ,title ,project_id FROM comments JOIN project ON comments.comment_target_id = project.project_id AND comments.comment_type = 0 STRAIGHT_JOIN member ON comments.comment_member_id = member.member_id WHERE comments.comment_active = 1 AND project.status = 100 AND project.member_id =:member_id ORDER BY comments.comment_created_at DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('member_id' => $member_id)); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save(array(), $cacheName, array(), 300); return array(); } } public function getLastVotesForUsersProjects($member_id, $limit = 10) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$member_id . (int)$limit); if (false !== ($resultSet = $cache->load($cacheName))) { return $resultSet; } $sql = ' SELECT rating_id , member.member_id ,username ,user_like ,user_dislike ,project_rating.project_id ,project_rating.created_at ,project.title FROM project_rating JOIN project ON project_rating.project_id = project.project_id STRAIGHT_JOIN member ON project_rating.member_id = member.member_id WHERE project.status = 100 AND project.member_id = :member_id ORDER BY rating_id DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('member_id' => $member_id)); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save(array(), $cacheName, array(), 300); return array(); } } public function getLastDonationsForUsersProjects($member_id, $limit = 10) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5(Zend_Registry::get('store_host') . (int)$member_id . (int)$limit); if (false !== ($resultSet = $cache->load($cacheName))) { return $resultSet; } $sql = ' SELECT plings.project_id, plings.id ,member.member_id ,profile_image_url ,plings.create_time ,username ,plings.amount ,comment ,project.title FROM plings JOIN project ON project.project_id = plings.project_id STRAIGHT_JOIN member ON plings.member_id = member.member_id WHERE plings.status_id = 2 AND project.status=100 AND project.member_id = :member_id ORDER BY create_time DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('member_id' => $member_id)); if (count($resultSet) > 0) { $cache->save($resultSet, $cacheName, array(), 300); return $resultSet; } else { $cache->save(array(), $cacheName, array(), 300); return array(); } } /** * @param int $limit * * @return array|false|mixed */ public function getNewActiveMembers($limit = 20) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5((int)$limit); if (false !== ($newMembers = $cache->load($cacheName))) { return $newMembers; } $sql = ' SELECT member_id, profile_image_url, username, created_at FROM member WHERE `is_active` = :activeVal AND `type` = :typeVal ORDER BY created_at DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultMembers = Zend_Db_Table::getDefaultAdapter()->query($sql, array( 'activeVal' => Default_Model_Member::MEMBER_ACTIVE, 'typeVal' => Default_Model_Member::MEMBER_TYPE_PERSON ))->fetchAll() ; $cache->save($resultMembers, $cacheName, array(), 300); return $resultMembers; } /** * @param int $limit * * @return array|false|mixed */ public function getTopScoreUsers($limit = 120) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5((int)$limit); if (false !== ($resultMembers = $cache->load($cacheName))) { return $resultMembers; } $model = new Default_Model_DbTable_MemberScore(); $resultMembers = $model->fetchTopUsers($limit); $cache->save($resultMembers, $cacheName, array(), 300); return $resultMembers; } public function getNewActiveSupporters($limit = 20) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5((int)$limit); if (false !== ($newSupporters = $cache->load($cacheName))) { return $newSupporters; } $sql = ' SELECT s.member_id as supporter_id ,s.member_id ,(select username from member m where m.member_id = s.member_id) as username ,(select profile_image_url from member m where m.member_id = s.member_id) as profile_image_url ,min(s.active_time) as created_at from support s where s.status_id = 2 and (DATE_ADD((s.active_time), INTERVAL 1 YEAR) > now()) group by member_id order by s.active_time desc '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $result = Zend_Db_Table::getDefaultAdapter()->query($sql, array())->fetchAll(); $cache->save($result, $cacheName, array(), 300); return $result; } public function getNewActivePlingProduct($limit = 20) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__ . '_' . md5((int)$limit); if (false !== ($newSupporters = $cache->load($cacheName))) { return $newSupporters; } $sql = ' select pl.member_id as pling_member_id ,pl.project_id ,p.title ,p.image_small ,p.laplace_score ,p.count_likes ,p.count_dislikes ,p.member_id ,p.profile_image_url ,p.username ,p.cat_title as catTitle ,( select min(created_at) from project_plings pt where pt.member_id = pl.member_id and pt.project_id=pl.project_id ) as created_at ,(select count(1) from project_plings pl2 where pl2.project_id = p.project_id and pl2.is_active = 1 and pl2.is_deleted = 0 ) as sum_plings from project_plings pl inner join stat_projects p on pl.project_id = p.project_id and p.status > 30 where pl.is_deleted = 0 and pl.is_active = 1 order by created_at desc '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $result = Zend_Db_Table::getDefaultAdapter()->query($sql, array())->fetchAll(); $cache->save($result, $cacheName, array(), 300); return $result; } public function getCountActiveSupporters() { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__; if (false !== ($totalcnt = $cache->load($cacheName))) { return $totalcnt; } $sql = ' SELECT count( distinct s.member_id) as total_count from support s where s.status_id = 2 and (DATE_ADD((s.active_time), INTERVAL 1 YEAR) > now()) '; $result = Zend_Db_Table::getDefaultAdapter()->query($sql, array())->fetchAll(); $totalcnt = $result[0]['total_count']; $cache->save($totalcnt, $cacheName,array() , 300); return $totalcnt; } public function getModeratorsList() { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__; if (false !== ($newMembers = $cache->load($cacheName))) { return $newMembers; } $sql = ' SELECT member_id, profile_image_url, username, created_at FROM member WHERE `is_active` = :activeVal AND `type` = :typeVal and `roleid` = :roleid ORDER BY created_at DESC '; if (isset($limit)) { $sql .= ' limit ' . (int)$limit; } $resultMembers = Zend_Db_Table::getDefaultAdapter()->query($sql, array( 'activeVal' => Default_Model_Member::MEMBER_ACTIVE, 'typeVal' => Default_Model_Member::MEMBER_TYPE_PERSON, 'roleid' => Default_Model_DbTable_Member::ROLE_ID_MODERATOR ))->fetchAll() ; $cache->save($resultMembers, $cacheName, array(), 300); return $resultMembers; } public function getCountMembers() { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__; if (false !== ($totalcnt = $cache->load($cacheName))) { return $totalcnt; } $sql = " SELECT count(1) AS total_count FROM member WHERE is_active=1 AND is_deleted=0 "; $result = Zend_Db_Table::getDefaultAdapter()->query($sql, array())->fetchAll(); $totalcnt = $result[0]['total_count']; $cache->save($totalcnt, $cacheName,array() , 300); return $totalcnt; } public function getTooptipForMember($member_id) { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__. '_' . md5($member_id); if (false !== ($tooptip = $cache->load($cacheName))) { return $tooptip; } $modelMember = new Default_Model_Member(); $tblFollower = new Default_Model_DbTable_ProjectFollower(); $modelProject = new Default_Model_Project(); $printDate = new Default_View_Helper_PrintDate(); $printDateSince = new Default_View_Helper_PrintDateSince(); $cnt = $modelMember->fetchCommentsCount($member_id); $cntLikesGave = $tblFollower->countLikesHeGave($member_id); $cntLikesGot= $tblFollower->countLikesHeGot($member_id); $donationinfo = $modelMember->fetchSupporterDonationInfo($member_id); $lastactive = $modelMember->fetchLastActiveTime($member_id); $cntprojects = $modelProject->countAllProjectsForMember($member_id,true); $member = $modelMember->find($member_id)->current(); $textCountryCity = $member->city; $textCountryCity .= $member->country ? ', ' . $member->country : ''; $data = array( 'totalComments' =>$cnt, 'created_at' =>$printDateSince->printDateSince($member->created_at), 'username' =>$member->username, 'countrycity' => $textCountryCity, 'lastactive_at' =>$printDateSince->printDateSince($lastactive), 'cntProjects' =>$cntprojects, 'issupporter' =>$donationinfo['issupporter'], 'supportMax' =>$donationinfo['active_time_max'], 'supportMin' =>$donationinfo['active_time_min'], 'supportCnt' =>$donationinfo['cnt'], 'cntLikesGave' =>$cntLikesGave, 'cntLikesGot' =>$cntLikesGot ); $cache->save($data, $cacheName,array() , 3600); return $data; } public function getProbablyPayoutPlingsCurrentmonth($project_id) { $sql = " select FORMAT(probably_payout_amount, 2) as amount from member_dl_plings where project_id = :project_id and yearmonth=(DATE_FORMAT(NOW(),'%Y%m'))"; $result = Zend_Db_Table::getDefaultAdapter()->fetchRow($sql,array('project_id'=>$project_id)); return $result['amount']; } public function getOCSInstallInstruction() { /** @var Zend_Cache_Core $cache */ $cache = Zend_Registry::get('cache'); $cacheName = __FUNCTION__; if (false !== ($instruction = $cache->load($cacheName))) { return $instruction; } $config = Zend_Registry::get('config')->settings->server->opencode; $readme = 'https://git.opendesktop.org/OCS/ocs-url/raw/master/docs/How-to-install.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(); $readmetext = $Parsedown->text($body); $cache->save($readmetext, $cacheName,array() , 3600); return $readmetext; } public function getDiscussionOpendeskop($member_id){ $sql = " select c.comment_id ,c.comment_text ,c.comment_member_id ,c.comment_created_at ,m.username ,p.project_id ,p.title ,cp.comment_member_id p_comment_member_id ,(select username from member m where m.member_id = cp.comment_member_id) p_username from comments c inner join project p on c.comment_target_id = p.project_id and p.status = 100 inner join member m ON c.comment_member_id = m.member_id left join comments cp on c.comment_parent_id = cp.comment_id where c.comment_type = 0 and c.comment_active = 1 and c.comment_member_id = :member_id ORDER BY c.comment_created_at DESC limit 10 "; $result = Zend_Db_Table::getDefaultAdapter()->query($sql, array('member_id' => $member_id))->fetchAll(); return $result; } } \ No newline at end of file diff --git a/application/modules/default/models/MemberDeactivationLog.php b/application/modules/default/models/MemberDeactivationLog.php index 692b88f40..b57be353f 100644 --- a/application/modules/default/models/MemberDeactivationLog.php +++ b/application/modules/default/models/MemberDeactivationLog.php @@ -1,248 +1,260 @@ . * * Created: 22.09.2016 **/ class Default_Model_MemberDeactivationLog extends Default_Model_DbTable_MemberDeactivationLog { const OBJ_TYPE_OPENDESKTOP_MEMBER = 1; const OBJ_TYPE_OPENDESKTOP_MEMBER_EMAIL = 2; const OBJ_TYPE_OPENDESKTOP_PROJECT = 3; const OBJ_TYPE_OPENDESKTOP_COMMENT = 4; const OBJ_TYPE_GITLAB_USER = 20; const OBJ_TYPE_GITLAB_PROJECT = 21; const OBJ_TYPE_DISCOURSE_USER = 30; - const OBJ_TYPE_DISCOURSE_TOPIC = 31; + const OBJ_TYPE_DISCOURSE_POST = 31; + const OBJ_TYPE_DISCOURSE_TOPIC = 32; /** * @param int $identifer * * @return void * @throws Zend_Exception */ public function logMemberAsDeleted($identifer) { return $this->addLog($identifer, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_MEMBER, $identifer); } /** * @param int $member_id * @param int $object_type * @param int $identifier object id * * @return void * @throws Zend_Exception */ public function addLog($member_id, $object_type, $identifier) { $identity = Zend_Auth::getInstance()->getIdentity()->member_id; $sql = "INSERT INTO `member_deactivation_log` (`deactivation_id`,`object_type_id`,`object_id`,`member_id`) VALUES (:deactivation_id,:object_type_id,:object_id,:member_id)"; try { Zend_Db_Table::getDefaultAdapter()->query($sql, array( 'deactivation_id' => $member_id, 'object_type_id' => $object_type, 'object_id' => $identifier, 'member_id' => $identity )) ; } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR write member deactivation log - ' . print_r($e, true)); } } /** * @param int $member_id * @param int $identifer * * @return void * @throws Zend_Exception */ public function logMemberEmailAsDeleted($member_id, $identifer) { return $this->addLog($member_id, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_MEMBER_EMAIL, $identifer); } /** * @param int $member_id * @param int $identifer * * @return void * @throws Zend_Exception */ public function logProjectAsDeleted($member_id, $identifer) { return $this->addLog($member_id, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_PROJECT, $identifer); } /** * @param $member_id * @param int $identifer * * @return void * @throws Zend_Exception */ public function logCommentAsDeleted($member_id, $identifer) { return $this->addLog($member_id, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_COMMENT, $identifer); } /** * @param int $member_id * @param int $object_type * @param int $identifier * @param string $data * * @throws Zend_Exception */ public function addLogData($member_id, $object_type, $identifier, $data) { $identity = Zend_Auth::getInstance()->getIdentity()->member_id; $sql = "INSERT INTO `member_deactivation_log` (`deactivation_id`,`object_type_id`,`object_id`,`member_id`, `object_data`) VALUES (:deactivation_id,:object_type_id,:object_id,:member_id,:object_data)"; try { Zend_Db_Table::getDefaultAdapter()->query($sql, array( 'deactivation_id' => $member_id, 'object_type_id' => $object_type, 'object_id' => $identifier, 'member_id' => $identity, 'object_data' => $data )) ; } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR write member deactivation log - ' . print_r($e, true)); } } /** * @param int $identifer * * @return void * @throws Zend_Exception */ public function removeLogMemberAsDeleted($identifer) { return $this->deleteLog($identifer, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_MEMBER, $identifer); } /** * @param int $member_id * @param int $object_type * @param int $identifer object id * * @return void * @throws Zend_Exception */ public function deleteLog($member_id, $object_type, $identifer) { $identity = Zend_Auth::getInstance()->getIdentity()->member_id; $sql = "UPDATE `member_deactivation_log` SET is_deleted = 1, deleted_at = NOW() WHERE deactivation_id = :deactivation_id AND object_type_id = :object_type_id AND object_id = :object_id"; try { Zend_Db_Table::getDefaultAdapter()->query($sql, array('deactivation_id' => $member_id, 'object_type_id' => $object_type, 'object_id' => $identifer)) ; } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR write member deactivation log - ' . print_r($e, true)); } } /** * @param int $member_id * @param int $identifer * * @return void * @throws Zend_Exception */ public function removeLogMemberEmailAsDeleted($member_id, $identifer) { return $this->deleteLog($member_id, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_MEMBER_EMAIL, $identifer); } /** * @param int $member_id * @param int $identifer * * @return void * @throws Zend_Exception */ public function removeLogProjectAsDeleted($member_id, $identifer) { return $this->deleteLog($member_id, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_PROJECT, $identifer); } /** * @param int $member_id * @param int $identifer * * @return void * @throws Zend_Exception */ public function removeLogCommentAsDeleted($member_id, $identifer) { return $this->deleteLog($member_id, Default_Model_MemberDeactivationLog::OBJ_TYPE_OPENDESKTOP_COMMENT, $identifer); } public function getLogEntries($member_id, $obj_type, $id) { $sql = "SELECT * FROM member_deactivation_log WHERE deactivation_id = :memberid AND object_type_id = :objecttype AND object_id = :objectid AND is_deleted = 0"; $result = array(); try { $result = Zend_Db_Table::getDefaultAdapter()->fetchRow($sql, array('memberid' => $member_id, 'objecttype' => $obj_type, 'objectid' => $id)); } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR READ member deactivation log - ' . print_r($e, true)); } return $result; } /** * @param int $member_id * * @return array * @throws Zend_Exception */ public function getLogForumPosts($member_id) { - $sql = "SELECT * FROM member_deactivation_log WHERE deactivation_id = :memberid AND object_type_id = :objecttype AND is_deleted = 0"; + $sql = "SELECT * FROM member_deactivation_log WHERE deactivation_id = :memberid AND (object_type_id = ".self::OBJ_TYPE_DISCOURSE_TOPIC." OR object_type_id = ".self::OBJ_TYPE_DISCOURSE_POST.") AND is_deleted = 0"; $result = array(); try { - $result = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('memberid' => $member_id, 'objecttype' => self::OBJ_TYPE_DISCOURSE_TOPIC)); + $result = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('memberid' => $member_id)); } catch (Exception $e) { Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR READ member deactivation log - ' . print_r($e, true)); } - return $result; + $posts = array(); + + foreach ($result as $item) { + if (self::OBJ_TYPE_DISCOURSE_TOPIC == $item['object_type_id']) { + $posts['topics'][$item['object_id']] = $item; + } + if (self::OBJ_TYPE_DISCOURSE_POST == $item['object_type_id']) { + $posts['posts'][$item['object_id']] = $item; + } + } + + return $posts; } } \ No newline at end of file diff --git a/application/modules/default/models/Ocs/Forum.php b/application/modules/default/models/Ocs/Forum.php index 897f81f88..2ad202f97 100644 --- a/application/modules/default/models/Ocs/Forum.php +++ b/application/modules/default/models/Ocs/Forum.php @@ -1,831 +1,941 @@ . * * Created: 10.09.2018 */ class Default_Model_Ocs_Forum { protected $config; protected $messages; protected $httpClient; protected $isRateLimitError; protected $rateLimitWaitSeconds; /** * @inheritDoc */ public function __construct($config = null) { if (isset($config)) { $this->config = $config; } else { $this->config = Zend_Registry::get('config')->settings->server->forum; } $uri = $this->config->host; $this->httpClient = new Zend_Http_Client($uri, array('keepalive' => true, 'strictredirects' => true)); } /** * @param array $member_data * * @param bool $force * * @return array|bool * @throws Zend_Exception * @throws Zend_Http_Client_Exception * @throws Zend_Json_Exception */ public function createUserFromArray($member_data, $force = false) { if (empty($member_data)) { return false; } $this->messages = array(); $data = $this->mapUserData($member_data); try { $user = $this->getUser($member_data['external_id'], $member_data['username']); } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } $uid = $data['username']; if (empty($user)) { try { $uri = $this->config->host . "/users"; $method = Zend_Http_Client::POST; $result = $this->httpRequest($uri, $uid, $method, $data); if (false === $result) { $this->messages[] = "Fail "; return false; } } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } $this->messages[] = "Success"; return $data; } if ($force === true) { $uid = $user['user']['username']; unset($data['password']); try { $uri = $this->config->host . "/users/{$uid}.json"; $method = Zend_Http_Client::PUT; $result = $this->httpRequest($uri, $uid, $method, $data); } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } $this->messages[] = "overwritten : " . json_encode($result); return $user; } $this->messages[] = 'user already exists.'; return false; } /** * @param array $user * * @return array */ protected function mapUserData($user) { $paramEmail = ''; if (isset($user['email_address'])) { $paramEmail = $user['email_address']; } else if (isset($user['mail'])) { $paramEmail = $user['mail']; } $data = array( 'name' => (false == empty($user['lastname'])) ? trim($user['firstname'] . ' ' . $user['lastname']) : $user['username'], 'email' => $paramEmail, 'password' => $user['password'], 'username' => strtolower($user['username']), 'active' => $user['is_active'] ? true : false, 'approved' => (false == empty($user['email_checked'])) ? true : false, 'user_fields' => array('2' => $user['external_id']) ); return $data; } /** * @param $extern_uid * @param $username * * @return array|null * @throws Zend_Http_Client_Exception * @throws Zend_Http_Exception * @throws Zend_Json_Exception */ private function getUser($extern_uid, $username) { $user_by_uid = $this->getUserByExternUid($extern_uid); if (false === empty($user_by_uid)) { return $user_by_uid; } $user_by_dn = $this->getUserByUsername($username); if (false === empty($user_by_dn)) { return $user_by_dn; } return null; } /** * @param string $extern_uid * * @return bool|array * @throws Zend_Http_Client_Exception * @throws Zend_Http_Exception * @throws Zend_Json_Exception */ public function getUserByExternUid($extern_uid) { $uri = $this->config->host . "/u/by-external/{$extern_uid}.json"; $method = Zend_Http_Client::GET; $uid = 'external_id'; $user = $this->httpRequest($uri, $uid, $method); if (false === $user) { return false; } return $user; } /** * @param string $uri * @param string $uid * @param string $method * @param array|null $post_param * * @return bool|array * @throws Zend_Exception * @throws Zend_Http_Client_Exception * @throws Zend_Http_Exception * @throws Zend_Json_Exception */ protected function httpRequest($uri, $uid, $method = Zend_Http_Client::GET, $post_param = null) { $this->isRateLimitError = false; $this->rateLimitWaitSeconds = 0; $this->httpClient->resetParameters(); $this->httpClient->setUri($uri); $this->httpClient->setParameterGet('api_key', $this->config->private_token); $this->httpClient->setParameterGet('api_username', $this->config->user_sudo); $this->httpClient->setHeaders('User-Agent', $this->config->user_agent); $this->httpClient->setMethod($method); if (isset($post_param)) { $this->httpClient->setParameterPost($post_param); } $response = $this->httpClient->request(); if ($response->getStatus() < 200 OR $response->getStatus() >= 500) { $this->messages[] = 'Request failed.(' . $uri . ') OCS Forum server send message: ' . $response->getBody(); return false; } $body = $response->getRawBody(); $content_encoding = $response->getHeader('Content-encoding'); $transfer_encoding = $response->getHeader('Transfer-encoding'); if ($transfer_encoding == 'chunked') { $body = Zend_Http_Response::decodeChunkedBody($body); } if ($content_encoding == 'gzip') { $body = Zend_Http_Response::decodeGzip($body); } if (substr($body, 0, strlen('')) === '') { $this->messages[] = $body; return false; } $body = Zend_Json::decode($body); if (empty($body)) { return array('message' => 'empty body received'); } if (array_key_exists("error_type", $body) OR array_key_exists("errors", $body)) { $this->messages[] = "id: {$uid} ($uri) - " . $response->getBody(); if (isset($body['error_type']) AND ($body['error_type'] == "rate_limit")) { $this->isRateLimitError = true; $this->rateLimitWaitSeconds = $body['extras']['wait_seconds']; throw new Zend_Exception($body['errors'][0]); } return false; } if (array_key_exists('success', $body) AND $body['success'] == false) { $this->messages[] = "id: {$uid} ($uri) - " . $body['message']; return false; } return $body; } /** * @param string $username * * @return bool|array * @throws Zend_Http_Client_Exception * @throws Zend_Http_Exception * @throws Zend_Json_Exception */ public function getUserByUsername($username) { $encoded_username = urlencode($username); $uri = $this->config->host . "/users/{$encoded_username}.json"; $method = Zend_Http_Client::GET; $uid = $username; $user = $this->httpRequest($uri, $uid, $method); if (false === $user) { return false; } return $user; } /** * @param string $email * * @return bool|array * @throws Zend_Http_Client_Exception * @throws Zend_Http_Exception * @throws Zend_Json_Exception */ public function getUserByEmail($email) { $uri = $this->config->host . "/admin/users/list/all.json?email={$email}"; $method = Zend_Http_Client::GET; $user = $this->httpRequest($uri, $email, $method); if (false === $user) { return false; } return $user[0]; } /** * @return array|null */ public function getMessages() { return $this->messages; } /** * @param $member_id * * @return bool * @throws Default_Model_Ocs_Exception * @throws Zend_Exception * @throws Zend_Http_Client_Exception * @throws Zend_Json_Exception */ public function deleteUser($member_id) { if (empty($member_id)) { return false; } $member_data = $this->getMemberData($member_id, false); if (empty($member_data)) { return false; } $forum_member = $this->getUser($member_data['external_id'], $member_data['username']); if (empty($forum_member)) { return false; } $uri = $this->config->host . '/admin/users/' . $forum_member['user']['id'] . '.json'; $method = Zend_Http_Client::DELETE; $uid = $member_id; $user = $this->httpRequest($uri, $uid, $method); if (false === $user) { return false; } return $user; } /** * @param $member_id * @param bool $onlyActive * * @return mixed * @throws Default_Model_Ocs_Exception */ private function getMemberData($member_id, $onlyActive = true) { $onlyActiveFilter = ''; if ($onlyActive) { $onlyActiveFilter = " AND `m`.`is_active` = 1 AND `m`.`is_deleted` = 0 AND `me`.`email_checked` IS NOT NULL AND `me`.`email_deleted` = 0"; } $sql = " SELECT `mei`.`external_id`,`m`.`member_id`, `m`.`username`, `me`.`email_address`, `m`.`password`, `m`.`roleId`, `m`.`firstname`, `m`.`lastname`, `m`.`profile_image_url`, `m`.`biography`, `m`.`created_at`, `m`.`changed_at`, `m`.`source_id` FROM `member` AS `m` LEFT JOIN `member_email` AS `me` ON `me`.`email_member_id` = `m`.`member_id` AND `me`.`email_primary` = 1 LEFT JOIN `member_external_id` AS `mei` ON `mei`.`member_id` = `m`.`member_id` WHERE `m`.`member_id` = :memberId {$onlyActiveFilter} ORDER BY `m`.`member_id` DESC "; $result = Zend_Db_Table::getDefaultAdapter()->fetchRow($sql, array('memberId' => $member_id)); if (count($result) == 0) { throw new Default_Model_Ocs_Exception('member with id ' . $member_id . ' could not found.'); } return $result; } /** * @return bool|array */ public function getGroups() { $uri = $this->config->host . '/groups.json'; $uid = 'get groups'; $method = Zend_Http_Client::GET; try { $result = $this->httpRequest($uri, $uid, $method); } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } if (false === $result) { $this->messages[] = "Fail "; return false; } $this->messages[] = "Success"; return $result; } /** * @param string $name * * @return bool|array */ public function createGroup($name) { $uri = $this->config->host . '/admin/groups'; $method = Zend_Http_Client::POST; $data = array( "group[name]" => $name ); try { $result = $this->httpRequest($uri, $name, $method, $data); } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } if (false === $result) { $this->messages[] = "Fail "; return false; } $this->messages[] = "Success"; return $result['basic_group']; } public function deleteGroup($group_id) { $uri = $this->config->host . '/admin/groups/' . $group_id . '.json'; $method = Zend_Http_Client::DELETE; try { $result = $this->httpRequest($uri, $group_id, $method); } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } if (false === $result) { $this->messages[] = "Fail "; return false; } $this->messages[] = "Success"; return $result; } public function addGroupMember($groupname, $members) { } /** * @param $member_data * @param $oldUsername * * @return array|bool|null * @throws Default_Model_Ocs_Exception * @throws Zend_Exception * @throws Zend_Http_Client_Exception * @throws Zend_Json_Exception */ public function updateUserFromArray($member_data, $oldUsername) { if (empty($member_data)) { return false; } $this->messages = array(); $data = $this->mapUserData($member_data); $user = $this->getUser($member_data['external_id'], $oldUsername); if (empty($user)) { $this->messages[] = "Fail "; return false; } $uid = $user['user']['username']; unset($data['password']); try { $uri = $this->config->host . "/users/{$uid}.json"; $method = Zend_Http_Client::PUT; $this->httpRequest($uri, $uid, $method, $data); } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } $this->messages[] = "overwritten : " . json_encode($user); return $user; } /** * @param array $member_data * * @return array|bool * @throws Zend_Http_Client_Exception * @throws Zend_Http_Exception * @throws Zend_Json_Exception */ public function deleteUserWithArray($member_data) { if (empty($member_data)) { return false; } $forum_member = $this->getUserByExternUid($member_data['external_id']); if (empty($forum_member)) { return false; } $uri = $this->config->host . '/admin/users/' . $forum_member['id'] . '.json'; $method = Zend_Http_Client::DELETE; $uid = $member_data['member_id']; $user = $this->httpRequest($uri, $uid, $method); if (false === $user) { return false; } return $user; } /** * @param int|array $member_data * * @return array|bool * @throws Default_Model_Ocs_Exception * @throws Zend_Exception * @throws Zend_Http_Client_Exception * @throws Zend_Json_Exception */ public function blockUser($member_data) { if (is_int($member_data)) { $member_data = $this->getMemberData($member_data, false); } if (empty($member_data)) { return false; } $forum_member = $this->getUser($member_data['external_id'], $member_data['username']); if (empty($forum_member)) { return false; } $uri = $this->config->host . '/admin/users/' . $forum_member['user']['id'] . '/suspend'; $method = Zend_Http_Client::PUT; $uid = $member_data['member_id']; $suspend_until = new DateTime(); $suspend_until->add(new DateInterval('P1Y')); $data = array('suspend_until' => $suspend_until->format("Y-m-d"), "reason" => ""); try { $user = $this->httpRequest($uri, $uid, $method, $data); if (false === $user) { $this->messages[] = "Fail " . json_encode($this->messages); return false; } } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } $this->messages[] = 'Forum user suspended: ' . json_encode($user); $memberLog = new Default_Model_MemberDeactivationLog(); $memberLog->addLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_USER, $forum_member['user']['id']); return $user; } public function blockUserPosts($member_data) { if (is_int($member_data)) { $member_data = $this->getMemberData($member_data, false); } if (empty($member_data)) { return false; } - $result = $this->getPostsFromUser($member_data); - if (false == $result) { + $posts = $this->getPostsFromUser($member_data); + + if (false == $posts) { $this->messages[] = "Fail. No posts for user {$member_data['username']} received"; } $memberLog = new Default_Model_MemberDeactivationLog(); - foreach ($result['posts'] as $item) { - $result = $this->deletePostFromUser($item['id']); + foreach ($posts['posts'] as $id=>$item) { + $result = $this->deletePostFromUser($id); + if (false === $result) { + continue; + } + $this->messages[] = 'Forum user post deleted: ' . json_encode($id); + $memberLog->addLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_POST, $id); + } + + //handle topics + foreach ($posts['topics'] as $id=>$topic) { + $result = $this->deleteTopicFromUser($id); if (false === $result) { continue; } - $this->messages[] = 'Forum user post deleted: ' . json_encode($item['id']); - $memberLog->addLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_TOPIC, $item['id']); + $this->messages[] = 'Forum user topic deleted: ' . json_encode($id); + $memberLog->addLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_TOPIC, $id); } return true; } public function silenceUser($member_data) { if (is_int($member_data)) { $member_data = $this->getMemberData($member_data, false); } if (empty($member_data)) { return false; } $forum_member = $this->getUser($member_data['external_id'], $member_data['username']); if (empty($forum_member)) { return false; } $uri = $this->config->host . '/admin/users/' . $forum_member['user']['id'] . '/silence'; $method = Zend_Http_Client::PUT; $uid = $member_data['member_id']; $suspend_until = new DateTime(); $suspend_until->add(new DateInterval('PT5M')); $data = array( 'silenced_till' => $suspend_until->format(DateTime::ATOM), "reason" => "probably a spam user", "post_action" => "delete" ); $user = $this->httpRequest($uri, $uid, $method, $data); $this->messages[] = 'Forum user silenced: ' . json_encode($user); return $user; } public function getPostsFromUser($member_data) { if (empty($member_data)) { return false; } if (is_int($member_data)) { $member_data = $this->getMemberData($member_data, false); } //$forum_member = $this->getUser($member_data['external_id'], $member_data['username']); //if (empty($forum_member)) { // return false; //} - $uri = $this->config->host . '/search/query.json?term=@' . $member_data['username']; + $username = substr($member_data['username'], 0, 20); + $uri = $this->config->host . "/user_actions.json?offset=0&username={$username}&filter=4,5&no_results_help_key=user_activity.no_default"; $method = Zend_Http_Client::GET; $uid = $member_data['member_id']; $result = $this->httpRequest($uri, $uid, $method); - return $result; + if (false === is_array($result)) { + return false; + } + + $posts = array(); + + foreach ($result['user_actions'] as $user_action) { + if ($user_action['action_type'] == 4) { + $posts['topics'][$user_action['topic_id']] = $user_action; + } + if ($user_action['action_type'] == 5) { + $posts['posts'][$user_action['post_id']] = $user_action; + } + } + + return $posts; } /** * @param int $post_id * * @return array|bool */ public function deletePostFromUser($post_id) { if (empty($post_id)) { return false; } $uri = $this->config->host . '/posts/' . $post_id; $method = Zend_Http_Client::DELETE; $uid = $post_id; try { $result = $this->httpRequest($uri, $uid, $method); } catch (Zend_Exception $e) { $this->httpClient->getAdapter()->close(); $this->messages[] = "Fail " . $e->getMessage(); return false; } return $result; } public function undeletePostFromUser($post_id) { if (empty($post_id)) { return false; } $uri = $this->config->host . '/posts/' . $post_id . '/recover'; $method = Zend_Http_Client::PUT; $uid = $post_id; try { $result = $this->httpRequest($uri, $uid, $method); } catch (Zend_Exception $e) { $this->httpClient->getAdapter()->close(); $this->messages[] = "Fail " . $e->getMessage(); return false; } return $result; } + /** + * @param int $topic_id + * + * @return array|bool + */ + public function deleteTopicFromUser($topic_id) + { + if (empty($topic_id)) { + return false; + } + + $uri = $this->config->host . '/t/' . $topic_id; + $method = Zend_Http_Client::DELETE; + $uid = $topic_id; + + try { + $result = $this->httpRequest($uri, $uid, $method); + } catch (Zend_Exception $e) { + $this->httpClient->getAdapter()->close(); + $this->messages[] = "Fail " . $e->getMessage(); + + return false; + } + + return $result; + } + + /** + * @param int $topic_id + * + * @return array|bool + */ + public function undeleteTopicFromUser($topic_id) + { + if (empty($topic_id)) { + return false; + } + + $uri = $this->config->host . '/t/' . $topic_id . '/recover'; + $method = Zend_Http_Client::PUT; + $uid = $topic_id; + + try { + $result = $this->httpRequest($uri, $uid, $method); + } catch (Zend_Exception $e) { + $this->httpClient->getAdapter()->close(); + $this->messages[] = "Fail " . $e->getMessage(); + + return false; + } + + return $result; + } + public function unblockUser($member_data) { if (empty($member_data)) { return false; } if (is_int($member_data)) { $member_data = $this->getMemberData($member_data, false); } $forum_member = $this->getUser($member_data['external_id'], $member_data['username']); if (empty($forum_member)) { return false; } $uri = $this->config->host . '/admin/users/' . $forum_member['user']['id'] . '/unsuspend'; $method = Zend_Http_Client::PUT; $uid = $member_data['member_id']; try { $user = $this->httpRequest($uri, $uid, $method); if (false === $user) { $this->messages[] = "Fail " . json_encode($this->messages); return false; } } catch (Zend_Exception $e) { $this->messages[] = "Fail " . $e->getMessage(); return false; } $this->messages[] = 'Forum user unsuspend: ' . json_encode($user); $memberLog = new Default_Model_MemberDeactivationLog(); $memberLog->deleteLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_USER, $forum_member['user']['id']); return $user; } public function unblockUserPosts($member_data) { if (empty($member_data)) { return false; } if (is_int($member_data)) { $member_data = $this->getMemberData($member_data, false); } $forum_member = $this->getUser($member_data['external_id'], $member_data['username']); if (empty($forum_member)) { return false; } $memberLog = new Default_Model_MemberDeactivationLog(); $deletedPosts = $memberLog->getLogForumPosts($member_data['member_id']); - foreach ($deletedPosts as $deleted_post) { + foreach ($deletedPosts['topics'] as $deleted_post) { + $result = $this->undeleteTopicFromUser($deleted_post['object_id']); + if (false === $result) { + continue; + } + $this->messages[] = 'Forum user topic undeleted: ' . json_encode($deleted_post['object_id']); + $memberLog->deleteLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_TOPIC, $deleted_post['object_id']); + } + foreach ($deletedPosts['posts'] as $deleted_post) { $result = $this->undeletePostFromUser($deleted_post['object_id']); if (false === $result) { continue; } $this->messages[] = 'Forum user post undeleted: ' . json_encode($deleted_post['object_id']); - $memberLog->deleteLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_TOPIC, $deleted_post['object_id']); + $memberLog->deleteLog($member_data['member_id'], Default_Model_MemberDeactivationLog::OBJ_TYPE_DISCOURSE_POST, $deleted_post['object_id']); } - return true; } /** * @return mixed */ public function hasRateLimitError() { return $this->isRateLimitError; } /** * @return mixed */ public function getRateLimitWaitSeconds() { return $this->rateLimitWaitSeconds; } + public function getTopic($id) + { + if (empty($id)) { + return false; + } + + $uri = $this->config->host . '/t/' . $id . '.json'; + $method = Zend_Http_Client::GET; + $uid = $id; + + try { + $result = $this->httpRequest($uri, $uid, $method); + } catch (Zend_Exception $e) { + $this->httpClient->getAdapter()->close(); + $this->messages[] = "Fail " . $e->getMessage(); + + return false; + } + + return $result; + } + } \ No newline at end of file diff --git a/application/modules/default/models/Project.php b/application/modules/default/models/Project.php index ff17af7e0..a7890b574 100644 --- a/application/modules/default/models/Project.php +++ b/application/modules/default/models/Project.php @@ -1,1665 +1,1744 @@ . **/ 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_PACKAGETYPE = 'package_type'; const FILTER_NAME_ORIGINAL = 'original'; 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; /** * @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) { $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`.`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`, laplace_score(`p`.`count_likes`,`p`.`count_dislikes`) 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 `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` = :typeId '; $result = $this->_db->fetchRow($sql, array( 'projectId' => $project_id, 'projectStatus' => self::PROJECT_INACTIVE, 'typeId' => self::PROJECT_TYPE_STANDARD, 'tag_licence_gid' => self::TAG_LICENCE_GID, 'tag_type_id' => self::TAG_TYPE_ID )); 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`.`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`, laplace_score(`p`.`count_likes`,`p`.`count_dislikes`) AS `laplace_score`, `view_reported_projects`.`amount_reports` AS `amount_reports`, `project_license`.`title` 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 `view_reported_projects` ON ((`view_reported_projects`.`project_id` = `p`.`project_id`)) LEFT JOIN `project_license` ON ((`project_license`.`project_license_id` = `p`.`project_license_id`)) WHERE `p`.`project_id` = :projectId AND `p`.`status` >= :projectStatus AND `p`.`type_id` = :typeId '; $result = $this->_db->fetchRow($sql, array( 'projectId' => $project_id, 'projectStatus' => self::PROJECT_INACTIVE, 'typeId' => self::PROJECT_TYPE_STANDARD )); 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('stat_projects', array( 'project_id', 'image_small', 'title', 'catTitle' => 'cat_title' ))->setIntegrityCheck(false) ->where('status = ?', self::PROJECT_ACTIVE) ->where('member_id = ?', $project->member_id, 'INTEGER') ->where('project_id != ?', $project->project_id, 'INTEGER') ->where('type_id = ?', self::PROJECT_TYPE_STANDARD) ->where('amount_reports is null') ->where('project_category_id = ?', $project->project_category_id, 'INTEGER') ->limit($count) ->order('project_created_at DESC') ; $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; $storePackageTypeIds = null; if ($storeConfig) { $storePackageTypeIds = $storeConfig->package_type; } if ($storePackageTypeIds) { $q = $this->generatePackageTypeFilter($q, array(self::FILTER_NAME_PACKAGETYPE => $storePackageTypeIds)); } $result = $this->fetchAll($q); return $result; } /** * @param Zend_Db_Select $statement * @param array $filterArrayValue * * @return Zend_Db_Select */ protected function generatePackageTypeFilter(Zend_Db_Select $statement, $filterArrayValue) { if (false == isset($filterArrayValue[self::FILTER_NAME_PACKAGETYPE])) { return $statement; } $filter = $filterArrayValue[self::FILTER_NAME_PACKAGETYPE]; if (is_array($filter)) { $statement->join(array( 'package_type' => new Zend_Db_Expr('(SELECT DISTINCT project_id FROM project_package_type WHERE package_type_id in (' . $filter . '))') ), 'project.project_id = package_type.project_id', array()); } else { $statement->where('find_in_set(?, package_types)', $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('stat_projects', array( 'project_id', 'image_small', 'title', 'catTitle' => 'cat_title' ))->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') ; $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; $storePackageTypeIds = null; if ($storeConfig) { $storePackageTypeIds = $storeConfig->package_type; } if ($storePackageTypeIds) { $q = $this->generatePackageTypeFilter($q, array(self::FILTER_NAME_PACKAGETYPE => $storePackageTypeIds)); } Zend_Registry::get('logger')->debug(__METHOD__ . ' - ' . $q->__toString()); $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; } $storePackageTypeIds = (false === empty($store_config->package_type)) ? $store_config->package_type : null; $cacheName = __FUNCTION__ . '_' . md5(serialize($idCategory) . $withSubCat . serialize($storePackageTypeIds)); /** @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->generatePackageTypeFilter($select, array(self::FILTER_NAME_PACKAGETYPE => $storePackageTypeIds)); 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; } } /** * @return mixed */ public function fetchTotalProjectsCount() { $sql = "SELECT count(1) AS `total_project_count` FROM `project` WHERE `project`.`status` = :status AND `project`.`type_id` = :ptype"; $result = $this->_db->fetchRow($sql, array('status' => self::PROJECT_ACTIVE, 'ptype' => self::PROJECT_TYPE_STANDARD)); return $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); /** @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->generatePackageTypeFilter($statement, $inputFilterParams); $statement = $this->generateOriginalFilter($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=?', self::PROJECT_TYPE_STANDARD); 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.changed_at DESC'); break; case 'top': //$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' )); 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('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->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 * * @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']; 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'); } $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`, `p`.`count_likes`, `p`.`count_dislikes`, - `p`.`laplace_score`, + laplace_score(`p`.`count_likes`, `p`.`count_dislikes`) AS `laplace_score`, `p`.`member_id`, - `p`.`cat_title` AS `catTitle`, + `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 `stat_projects` `p` + (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`, + (select count(1) from project pp where pp.member_id = p.member_id and pp.status = 100 and pp.type_id = 1 and pp.project_category_id = p.project_category_id) cntCategory + FROM `project` `p` + join project_category cat on p.project_category_id = cat.project_category_id + WHERE `p`.`status` =100 - AND `p`.`member_id` = :member_id - ORDER BY `p`.`changed_at` DESC + 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 getUserActiveProjects($member_id, $limit = null, $offset = null) + // { + // // for member me page + // $sql = " + // SELECT + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_path, '|', 2),'|',-1) as cat1, + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_path, '|', 3),'|',-1) as cat2, + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_path, '|', 4),'|',-1) as cat3, + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_path, '|', 5),'|',-1) as cat4, + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_id_path, ',', 2),',',-1) as catid1, + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_id_path, ',', 3),',',-1) as catid2, + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_id_path, ',', 4),',',-1) as catid3, + // SUBSTRING_INDEX(SUBSTRING_INDEX(ancestor_id_path, ',', 5),',',-1) as catid4, + // `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`, + // laplace_score(`p`.`count_likes`, `p`.`count_dislikes`) 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`, + // (select count(1) from project pp where pp.member_id = p.member_id and pp.status = 100 and pp.project_category_id = p.project_category_id) cntCategory + // FROM `project` `p` + // join project_category cat on p.project_category_id = cat.project_category_id + // join stat_cat_tree c on p.project_category_id = c.project_category_id + // WHERE `p`.`status` =100 + // AND `p`.`member_id` = :member_id + // ORDER BY cntCategory desc, `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 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 `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 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']; } /** * @param int $member_id * * @return mixed */ public function getCountProjectsDuplicateSourceurl($member_id) { $sql = " SELECT count(1) AS `cnt` FROM ( SELECT DISTINCT `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 . ")"; $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; } } \ No newline at end of file diff --git a/application/modules/default/models/ProjectClone.php b/application/modules/default/models/ProjectClone.php index 237631a88..bda8ba176 100755 --- a/application/modules/default/models/ProjectClone.php +++ b/application/modules/default/models/ProjectClone.php @@ -1,175 +1,175 @@ . **/ class Default_Model_ProjectClone extends Default_Model_DbTable_ProjectClone { public function fetchOrigins($project_id) { $sql = " SELECT c.project_id as project_id_clone ,c.project_id_parent as project_id ,c.external_link ,c.member_id ,c.text ,' ' as catTitle - ,(select project_category_id from project p where p.project_id = c.project_id_parent) project_category_id - ,(select title from project p where p.project_id = c.project_id_parent) title - ,(select image_small from project p where p.project_id = c.project_id_parent) image_small - ,(select changed_at from project p where p.project_id = c.project_id_parent) changed_at + ,p.project_category_id + ,p.title + ,p.image_small + ,p.changed_at FROM project_clone c JOIN project p ON p.project_id = c.project_id_parent WHERE c.is_deleted = 0 and c.is_valid = 1 and c.project_id = :project_id AND p.`status` = 100 order by c.created_at desc "; $resultSet = $this->_db->fetchAll($sql, array('project_id' => $project_id)); return $this->generateRowSet($resultSet); // return $resultSet; } public function fetchClones($project_id) { $sql = " SELECT c.project_id as project_id ,c.project_id_parent as project_id_origin ,c.external_link ,c.member_id ,c.text ,' ' as catTitle ,(select project_category_id from project p where p.project_id = c.project_id_parent) project_category_id - ,(select title from project p where p.project_id = c.project_id) title - ,(select image_small from project p where p.project_id = c.project_id) image_small - ,(select changed_at from project p where p.project_id = c.project_id) changed_at + ,p.title + ,p.image_small + ,p.changed_at FROM project_clone c JOIN project p ON p.project_id = c.project_id WHERE c.is_deleted = 0 and c.is_valid = 1 and c.project_id_parent = :project_id AND p.`status` = 100 order by c.created_at desc "; $resultSet = $this->_db->fetchAll($sql, array('project_id' => $project_id)); return $this->generateRowSet($resultSet); // return $resultSet; } public function fetchParent($project_id) { $sql = " SELECT * FROM project_clone c WHERE c.is_deleted = 0 and c.is_valid = 1 and c.project_id = :project_id "; $resultSet = $this->_db->fetchRow($sql, array('project_id' => $project_id)); return $this->generateRowSet($resultSet); } public function fetchRelatedProducts($project_id) { $sql = " select distinct * from ( SELECT c.project_id as project_id ,c.external_link ,c.member_id ,c.text ,' ' as catTitle ,(select project_category_id from project p where p.project_id = c.project_id_parent) project_category_id - ,(select title from project p where p.project_id = c.project_id) title - ,(select image_small from project p where p.project_id = c.project_id) image_small - ,(select changed_at from project p where p.project_id = c.project_id) changed_at + ,p.title + ,p.image_small + ,p.changed_at FROM project_clone c JOIN project p on p.project_id = c.project_id WHERE c.is_deleted = 0 and c.is_valid = 1 and c.project_id_parent = :project_id AND p.`status` = 100 union SELECT c.project_id as project_id ,c.external_link ,c.member_id ,c.text ,' ' as catTitle ,(select project_category_id from project p where p.project_id = c.project_id_parent) project_category_id - ,(select title from project p where p.project_id = c.project_id) title - ,(select image_small from project p where p.project_id = c.project_id) image_small - ,(select changed_at from project p where p.project_id = c.project_id) changed_at + ,p.title + ,p.image_small + ,p.changed_at FROM project_clone c JOIN project p on p.project_id = c.project_id WHERE c.project_id<> :project_id and c.is_deleted = 0 and c.is_valid = 1 AND p.`status` = 100 and c.project_id_parent in ( select project_id_parent from project_clone c where c.project_id = :project_id and c.is_valid = 1 and c.is_deleted = 0 ) ) a where a.catTitle is not null order by changed_at desc "; $resultSet = $this->_db->fetchAll($sql, array('project_id' => $project_id)); return $this->generateRowSet($resultSet); } public function fetchCredits() { $sql = " SELECT c.project_clone_id ,c.project_id ,c.project_id_parent ,c.external_link ,c.text ,c.member_id as reported_by - ,(select username from member m where m.member_id = c.member_id) as reporter_username - ,(select profile_image_url from member m where m.member_id = c.member_id) as reporter_profile_image_url - - ,(select cat_title from stat_projects p where p.project_id = c.project_id) catTitle - ,(select title from stat_projects p where p.project_id = c.project_id) title - ,(select image_small from stat_projects p where p.project_id = c.project_id) image_small - ,(select changed_at from stat_projects p where p.project_id = c.project_id) changed_at - ,(select laplace_score from stat_projects p where p.project_id = c.project_id) laplace_score - ,(select member_id from stat_projects p where p.project_id = c.project_id) member_id - ,(select username from stat_projects p where p.project_id = c.project_id) username - - - ,(select cat_title from stat_projects p where p.project_id = c.project_id_parent) parent_catTitle - ,(select title from stat_projects p where p.project_id = c.project_id_parent) parent_title - ,(select image_small from stat_projects p where p.project_id = c.project_id_parent) parent_image_small - ,(select changed_at from stat_projects p where p.project_id = c.project_id_parent) parent_changed_at - ,(select laplace_score from stat_projects p where p.project_id = c.project_id_parent) parent_laplace_score - ,(select member_id from stat_projects p where p.project_id = c.project_id_parent) parent_member_id - ,(select username from stat_projects p where p.project_id = c.project_id_parent) parent_username + ,m.username as reporter_username + ,m.profile_image_url as reporter_profile_image_url + ,p.cat_title catTitle + ,p.title + ,p.image_small + ,p.changed_at + ,p.laplace_score + ,p.member_id + ,p.username + ,pp.cat_title parent_catTitle + ,pp.title parent_title + ,pp.image_small parent_image_small + ,pp.changed_at parent_changed_at + ,pp.laplace_score parent_laplace_score + ,pp.member_id parent_member_id + ,pp.username parent_username FROM project_clone c - WHERE c.is_deleted = 0 and c.is_valid = 0 + JOIN stat_projects p on p.project_id = c.project_id + join member m on m.member_id = c.member_id + left join stat_projects pp on pp.project_id =c.project_id_parent + WHERE c.is_deleted = 0 and c.is_valid = 0 AND p.status = 100 order by c.created_at desc "; $resultSet = $this->_db->fetchAll($sql); return $this->generateRowSet($resultSet); } } \ No newline at end of file diff --git a/application/modules/default/models/Spam.php b/application/modules/default/models/Spam.php index 7aec76235..8e69c6b60 100644 --- a/application/modules/default/models/Spam.php +++ b/application/modules/default/models/Spam.php @@ -1,126 +1,71 @@ . * * Created: 31.05.2017 */ class Default_Model_Spam { const SPAM_THRESHOLD = 1; /** * naive approach for spam detection * @todo: define a list of stop words * * @param array $project_data * * @return bool */ public static function hasSpamMarkers($project_data) { + $sql = "SELECT spam_key_word FROM spam_keywords WHERE spam_key_is_active = 1 AND spam_key_is_deleted = 0"; + $keywords = Zend_Db_Table::getDefaultAdapter()->fetchCol($sql); + + $needles = implode('|', $keywords); + $haystack = implode(" ", array($project_data['title'], $project_data['description'])); - if (stripos($haystack, 'keto')) { - return true; - } - if (stripos($haystack, 'spartan')) { - return true; - } - if (stripos($haystack, 'ingredient')) { - return true; - } - if (stripos($haystack, 'rdx surge')) { - return true; - } - if (stripos($haystack, 'vashikaran')) { - return true; - } - if (stripos($haystack, 'muscles')) { - return true; - } - if (stripos($haystack, 'viagra')) { - return true; - } - if (stripos($haystack, 's3xual')) { - return true; - } - if (stripos($haystack, 'erection')) { - return true; - } - if (stripos($haystack, 'praltrix')) { - return true; - } - if (stripos($haystack, 's3x')) { - return true; - } - if (stripos($haystack, 'herpes')) { - return true; - } - if (stripos($haystack, 'male enhancement')) { - return true; - } - if (stripos($haystack, 'astrology')) { - return true; - } - if (stripos($haystack, 'megashare')) { - return true; - } - if (stripos($haystack, 'body weight')) { - return true; - } - if (stripos($haystack, 'diet')) { - return true; - } - if (stripos($haystack, 'foreskin')) { - return true; - } - if (stripos($haystack, 'fat loss')) { - return true; - } - if (stripos($haystack, 'cream')) { - return true; - } - if (stripos($haystack, 'healthy')) { + if(preg_match("/\b({$needles})\b/", $haystack)){ return true; } return false; } public function fetchSpamCandidate() { $sql = " SELECT * FROM `stat_projects` WHERE `stat_projects`.`amount_reports` >= :threshold AND `stat_projects`.`status` = 100 ORDER BY `stat_projects`.`changed_at` DESC, `stat_projects`.`created_at` DESC, `stat_projects`.`amount_reports` DESC "; $result = Zend_Db_Table::getDefaultAdapter()->query($sql, array('threshold' => self::SPAM_THRESHOLD)); if ($result->rowCount() > 0) { return $result->fetchAll(); } else { return array(); } } } \ No newline at end of file diff --git a/application/modules/default/models/StatDownload.php b/application/modules/default/models/StatDownload.php index 1654e7a6c..e10de3d12 100644 --- a/application/modules/default/models/StatDownload.php +++ b/application/modules/default/models/StatDownload.php @@ -1,70 +1,86 @@ . * * Created: 16.12.2016 **/ class Default_Model_StatDownload { public function getUserDownloads($member_id) { $sql = " SELECT `member_dl_plings`.*, CASE WHEN (SELECT count(1) AS `sum_plings` FROM `project_plings` `pp` WHERE `pp`.`project_id` = `member_dl_plings`.`project_id` AND `pp`.`is_deleted` = 0 AND `is_active` = 1 GROUP BY `pp`.`project_id`) > 0 THEN (SELECT count(1) AS `sum_plings` FROM `project_plings` `pp` WHERE `pp`.`project_id` = `member_dl_plings`.`project_id` AND `pp`.`is_deleted` = 0 AND `is_active` = 1 GROUP BY `pp`.`project_id`) + 1 ELSE 1 END AS `num_plings_now`, `project`.`title`, `project`.`image_small`, `project_category`.`title` AS `cat_title`, laplace_score(`project`.`count_likes`, `project`.`count_dislikes`)/100 AS `laplace_score`, `member_payout`.`amount`, `member_payout`.`status`, `member_payout`.`payment_transaction_id`, CASE WHEN `tag_object`.`tag_item_id` IS NULL THEN 1 ELSE 0 END AS `is_license_missing_now`, CASE WHEN ((`project_category`.`source_required` = 1 AND `project`.`source_url` IS NOT NULL AND LENGTH(`project`.`source_url`) > 0) OR (`project_category`.`source_required` = 0)) THEN 0 ELSE 1 END AS `is_source_missing_now`, `project`.`pling_excluded` AS `is_pling_excluded_now` FROM `member_dl_plings` STRAIGHT_JOIN `project` ON `project`.`project_id` = `member_dl_plings`.`project_id` STRAIGHT_JOIN `project_category` ON `project_category`.`project_category_id` = `member_dl_plings`.`project_category_id` LEFT JOIN `member_payout` ON `member_payout`.`member_id` = `member_dl_plings`.`member_id` AND `member_payout`.`yearmonth` = `member_dl_plings`.`yearmonth` LEFT JOIN `tag_object` ON `tag_object`.`tag_type_id` = 1 AND `tag_object`.`tag_group_id` = 7 AND `tag_object`.`is_deleted` = 0 AND `tag_object`.`tag_object_id` = `project`.`project_id` WHERE `member_dl_plings`.`member_id` = :member_id ORDER BY `member_dl_plings`.`yearmonth` DESC, `project_category`.`title`, `project`.`title` "; $result = Zend_Db_Table::getDefaultAdapter()->query($sql, array('member_id' => $member_id)); if ($result->rowCount() > 0) { return $result->fetchAll(); } else { return array(); } } + public function getMonthEarn($member_id,$yyyymm) + { + $sql = " select sum(probably_payout_amount) amount + from member_dl_plings + where member_id=:member_id + and yearmonth=:yyyymm + and is_pling_excluded = 0 + and is_license_missing = 0"; + + $resultSet = Zend_Db_Table::getDefaultAdapter()->fetchAll($sql, array('member_id' => $member_id,'yyyymm' =>$yyyymm)); + return array_pop($resultSet); + + + + } + } \ No newline at end of file diff --git a/application/modules/default/plugins/AclRules.php b/application/modules/default/plugins/AclRules.php index 3d73d00e9..f1cc4ae54 100644 --- a/application/modules/default/plugins/AclRules.php +++ b/application/modules/default/plugins/AclRules.php @@ -1,342 +1,343 @@ . **/ class Default_Plugin_AclRules extends Zend_Acl { const ROLENAME_GUEST = 'guest'; const ROLENAME_COOKIEUSER = 'cookieuser'; const ROLENAME_FEUSER = 'feuser'; const ROLENAME_MODERATOR = 'moderator'; const ROLENAME_STAFF = 'staff'; const ROLENAME_ADMIN = 'admin'; const ROLENAME_SYSUSER = 'sysuser'; function __construct() { $this->addRole(new Zend_Acl_Role (self::ROLENAME_GUEST)); $this->addRole(new Zend_Acl_Role (self::ROLENAME_COOKIEUSER), self::ROLENAME_GUEST); $this->addRole(new Zend_Acl_Role (self::ROLENAME_FEUSER), self::ROLENAME_COOKIEUSER); $this->addRole(new Zend_Acl_Role (self::ROLENAME_MODERATOR), self::ROLENAME_FEUSER); $this->addRole(new Zend_Acl_Role (self::ROLENAME_STAFF), self::ROLENAME_FEUSER); $this->addRole(new Zend_Acl_Role (self::ROLENAME_ADMIN)); $this->addRole(new Zend_Acl_Role (self::ROLENAME_SYSUSER)); $this->addResource(new Zend_Acl_Resource ('default_logout')); $this->addResource(new Zend_Acl_Resource ('default_oauth')); $this->addResource(new Zend_Acl_Resource ('default_authorization')); $this->addResource(new Zend_Acl_Resource ('default_button')); $this->addResource(new Zend_Acl_Resource ('default_categories')); $this->addResource(new Zend_Acl_Resource ('default_community')); $this->addResource(new Zend_Acl_Resource ('default_content')); $this->addResource(new Zend_Acl_Resource ('default_discovery')); $this->addResource(new Zend_Acl_Resource ('default_donationlist')); $this->addResource(new Zend_Acl_Resource ('default_support')); $this->addResource(new Zend_Acl_Resource ('default_error')); $this->addResource(new Zend_Acl_Resource ('default_explore')); $this->addResource(new Zend_Acl_Resource ('default_gateway')); $this->addResource(new Zend_Acl_Resource ('default_hive')); $this->addResource(new Zend_Acl_Resource ('default_home')); $this->addResource(new Zend_Acl_Resource ('default_ocsv1')); // OCS API $this->addResource(new Zend_Acl_Resource ('default_embedv1')); // embed API $this->addResource(new Zend_Acl_Resource ('default_productcategory')); $this->addResource(new Zend_Acl_Resource ('default_productcomment')); $this->addResource(new Zend_Acl_Resource ('default_product')); $this->addResource(new Zend_Acl_Resource ('default_report')); $this->addResource(new Zend_Acl_Resource ('default_rectification')); $this->addResource(new Zend_Acl_Resource ('default_rss')); $this->addResource(new Zend_Acl_Resource ('default_settings')); $this->addResource(new Zend_Acl_Resource ('default_supporterbox')); $this->addResource(new Zend_Acl_Resource ('default_plingbox')); $this->addResource(new Zend_Acl_Resource ('default_user')); $this->addResource(new Zend_Acl_Resource ('default_widget')); $this->addResource(new Zend_Acl_Resource ('default_file')); $this->addResource(new Zend_Acl_Resource ('default_plings')); $this->addResource(new Zend_Acl_Resource ('default_gitfaq')); $this->addResource(new Zend_Acl_Resource ('default_spam')); $this->addResource(new Zend_Acl_Resource ('default_moderation')); $this->addResource(new Zend_Acl_Resource ('default_duplicates')); $this->addResource(new Zend_Acl_Resource ('default_misuse')); $this->addResource(new Zend_Acl_Resource ('default_credits')); $this->addResource(new Zend_Acl_Resource ('default_ads')); $this->addResource(new Zend_Acl_Resource ('default_dl')); $this->addResource(new Zend_Acl_Resource ('default_password')); $this->addResource(new Zend_Acl_Resource ('default_verify')); $this->addResource(new Zend_Acl_Resource ('default_login')); $this->addResource(new Zend_Acl_Resource ('default_stati')); $this->addResource(new Zend_Acl_Resource ('default_tag')); $this->addResource(new Zend_Acl_Resource ('backend_categories')); $this->addResource(new Zend_Acl_Resource ('backend_vcategories')); $this->addResource(new Zend_Acl_Resource ('backend_categorytag')); $this->addResource(new Zend_Acl_Resource ('backend_categorytaggroup')); $this->addResource(new Zend_Acl_Resource ('backend_claim')); $this->addResource(new Zend_Acl_Resource ('backend_comments')); $this->addResource(new Zend_Acl_Resource ('backend_content')); $this->addResource(new Zend_Acl_Resource ('backend_faq')); $this->addResource(new Zend_Acl_Resource ('backend_hive')); $this->addResource(new Zend_Acl_Resource ('backend_hiveuser')); $this->addResource(new Zend_Acl_Resource ('backend_index')); $this->addResource(new Zend_Acl_Resource ('backend_mail')); $this->addResource(new Zend_Acl_Resource ('backend_member')); $this->addResource(new Zend_Acl_Resource ('backend_memberpayout')); $this->addResource(new Zend_Acl_Resource ('backend_memberpaypaladdress')); $this->addResource(new Zend_Acl_Resource ('backend_paypalvalidstatus')); $this->addResource(new Zend_Acl_Resource ('backend_payoutstatus')); $this->addResource(new Zend_Acl_Resource ('backend_operatingsystem')); $this->addResource(new Zend_Acl_Resource ('backend_project')); $this->addResource(new Zend_Acl_Resource ('backend_ranking')); $this->addResource(new Zend_Acl_Resource ('backend_reportcomments')); $this->addResource(new Zend_Acl_Resource ('backend_reportproducts')); $this->addResource(new Zend_Acl_Resource ('backend_search')); $this->addResource(new Zend_Acl_Resource ('backend_storecategories')); $this->addResource(new Zend_Acl_Resource ('backend_vstorecategories')); $this->addResource(new Zend_Acl_Resource ('backend_store')); $this->addResource(new Zend_Acl_Resource ('backend_tag')); $this->addResource(new Zend_Acl_Resource ('backend_user')); $this->addResource(new Zend_Acl_Resource ('backend_tags')); $this->addResource(new Zend_Acl_Resource ('backend_ghnsexcluded')); $this->addResource(new Zend_Acl_Resource ('backend_letteravatar')); $this->addResource(new Zend_Acl_Resource ('backend_group')); + $this->addResource(new Zend_Acl_Resource ('backend_spamkeywords')); $this->addResource(new Zend_Acl_Resource ('backend_cdiscourse')); $this->addResource(new Zend_Acl_Resource ('backend_cgitlab')); $this->addResource(new Zend_Acl_Resource ('backend_cldap')); $this->addResource(new Zend_Acl_Resource ('backend_coauth')); $this->addResource(new Zend_Acl_Resource ('backend_cexport')); $this->addResource(new Zend_Acl_Resource ('statistics_data')); $this->allow(self::ROLENAME_GUEST, array( 'statistics_data' )); $this->allow(self::ROLENAME_GUEST, array( 'default_logout', 'default_authorization', 'default_button', 'default_categories', 'default_content', 'default_community', 'default_donationlist', 'default_error', 'default_explore', 'default_gateway', 'default_hive', 'default_home', 'default_ocsv1', // OCS API 'default_embedv1', // embed API 'default_productcategory', 'default_rss', 'default_supporterbox', 'default_plingbox', 'default_oauth', 'default_plings', 'default_gitfaq', 'default_ads', 'default_dl', 'default_stati', 'default_password', 'default_verify', 'default_login' )); $this->allow(self::ROLENAME_SYSUSER, array( 'default_authorization', 'default_button', 'default_categories', 'default_content', 'default_community', 'default_donationlist', 'default_error', 'default_explore', 'default_gateway', 'default_hive', 'default_home', 'default_ocsv1', // OCS API 'default_embedv1', // embed API 'default_productcategory', 'default_report', 'default_rss', 'default_supporterbox', 'default_plingbox', 'default_oauth', 'default_plings', 'default_ads', 'default_dl', 'default_stati', 'default_password' )); $this->allow(self::ROLENAME_COOKIEUSER, array( 'default_logout', 'default_productcomment', 'default_settings', 'default_support', 'default_tag', 'default_rectification' )); $this->allow(self::ROLENAME_STAFF, array( 'backend_index', 'backend_categories', 'backend_categorytag', 'backend_claim', 'backend_comments', 'backend_content', 'backend_store', 'backend_storecategories', 'backend_operatingsystem', 'backend_reportcomments', 'backend_reportproducts', 'backend_search', 'backend_group' )); $this->allow(self::ROLENAME_ADMIN); // resource access rights in detail $this->allow(self::ROLENAME_GUEST, 'backend_group', array('newgroup')); // resource default_product $this->allow(self::ROLENAME_GUEST, 'default_product', array( 'index', 'show', 'getupdatesajax', 'updates', 'follows', 'fetch', 'search', 'startdownload', 'ppload', 'loadratings', 'loadinstallinstruction' )); // resource default_product $this->allow(self::ROLENAME_SYSUSER, 'default_product', array( 'index', 'show', 'getupdatesajax', 'updates', 'follows', 'fetch', 'search', 'startdownload', 'ppload', 'loadratings' )); $this->allow(self::ROLENAME_COOKIEUSER, 'default_product', array( 'add', 'rating', 'follow', 'unfollow', 'plingproject', 'followproject', 'unplingproject', 'add', 'pling', 'pay', 'dwolla', 'paymentok', 'paymentcancel', 'saveproduct', 'claim' )); $this->allow(self::ROLENAME_MODERATOR, 'backend_project', array( 'doghnsexclude' )); $this->allow(self::ROLENAME_MODERATOR, 'default_moderation', array( 'index','list' )); $this->allow(self::ROLENAME_MODERATOR, 'default_duplicates', array( 'index' )); $this->allow(self::ROLENAME_COOKIEUSER, 'default_product', array( 'edit', 'saveupdateajax', 'deleteupdateajax', 'update', 'preview', 'delete', 'unpublish', 'publish', 'verifycode', 'makerconfig', 'addpploadfile', 'updatepploadfile', 'deletepploadfile', 'deletepploadfiles', 'updatepackagetype', 'updatearchitecture', ), new Default_Plugin_Acl_IsProjectOwnerAssertion()); // resource default_support $this->allow(self::ROLENAME_COOKIEUSER, 'default_support', array('index', 'pay', 'paymentok', 'paymentcancel')); // resource default_support $this->allow(self::ROLENAME_COOKIEUSER, 'default_report', array('comment', 'product', 'productfraud', 'productclone')); // resource default_widget $this->allow(self::ROLENAME_GUEST, 'default_widget', array('index', 'render')); $this->allow(self::ROLENAME_COOKIEUSER, 'default_widget', array('save', 'savedefault', 'config'), new Default_Plugin_Acl_IsProjectOwnerAssertion()); $this->allow(self::ROLENAME_COOKIEUSER, 'default_file', array( 'gitlink', 'link', ), new Default_Plugin_Acl_IsProjectOwnerAssertion()); // resource default_user $this->allow(self::ROLENAME_GUEST, 'default_home', array('baseurlajax','forumurlajax','blogurlajax','storenameajax','domainsajax', 'userdataajax', 'loginurlajax', 'metamenujs','metamenubundlejs','fetchforgit')); // resource default_user $this->allow(self::ROLENAME_GUEST, 'default_user', array('index', 'aboutme', 'share', 'report', 'about', 'tooltip', 'avatar', 'userdataajax')); $this->allow(self::ROLENAME_COOKIEUSER, 'default_user', array( 'follow', 'unfollow', 'settings', 'products', 'news', 'activities', 'payments', 'income', 'payout', 'plings', 'downloadhistory', 'likes' )); $this->allow(self::ROLENAME_COOKIEUSER, 'default_tag', array('filter', 'add', 'del', 'assign', 'remove')); } } diff --git a/application/modules/default/views/scripts/community/index.phtml b/application/modules/default/views/scripts/community/index.phtml index 440bec81a..836f624a5 100644 --- a/application/modules/default/views/scripts/community/index.phtml +++ b/application/modules/default/views/scripts/community/index.phtml @@ -1,247 +1,250 @@ . **/ $helperImage = new Default_View_Helper_Image(); $modelInfo = new Default_Model_Info(); $users = $modelInfo->getNewActiveMembers(100); $topusers = $modelInfo->getTopScoreUsers(100); $supporters = $modelInfo->getNewActiveSupporters(100); $plingproducts = $modelInfo->getNewActivePlingProduct(100); - +$countSupporters = $modelInfo->getCountActiveSupporters(); +$countActiveMembers = $modelInfo->countTotalActiveMembers(); $buildMemberUrl = new Default_View_Helper_BuildMemberUrl(); $buildProductUrl = new Default_View_Helper_BuildProductUrl(); $membersCount = new Default_View_Helper_FetchTotalMembersCount(); //$totalAMountSupported = new Default_View_Helper_FetchTotalAmountSupported(); ?>