diff --git a/application/modules/default/controllers/ProductController.php b/application/modules/default/controllers/ProductController.php index acc710318..2df5350fc 100644 --- a/application/modules/default/controllers/ProductController.php +++ b/application/modules/default/controllers/ProductController.php @@ -1,2996 +1,3007 @@ . **/ 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 gettaggroupsforcatajaxAction() { $this->_helper->layout()->disableLayout(); $catId = null; $fileId = null; if($this->hasParam('file_id')) { $fileId = $this->getParam('file_id'); } if($this->hasParam('project_cat_id')) { $catId = $this->getParam('project_cat_id'); $catTagModel = new Default_Model_Tags(); $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId); $tableTags = new Default_Model_DbTable_Tags(); $result = array(); $resultGroup = array(); foreach ($tagGroups as $group) { $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); $selectedTags = null; if(!empty($fileId)) { $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE,$group['tag_group_id']); } $group['tag_list'] = $tags; $group['selected_tags'] = $selectedTags; $result[] = $group; } $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($tagGroups), 'tag_groups' => $result)); return; } $this->_helper->json(array('status' => 'error')); } private function getTagGroupsForCat($fileId) { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $catId = $productInfo->project_category_id; if(!empty($catId)) { $catTagModel = new Default_Model_Tags(); $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId); $tableTags = new Default_Model_DbTable_Tags(); $result = array(); foreach ($tagGroups as $group) { $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']); $selectedTags = null; if(!empty($fileId)) { $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE,$group['tag_group_id']); } $group['tag_list'] = $tags; $group['selected_tags'] = $selectedTags; $result[] = $group; } return $result; } return null; } private function getFileDownloadCount($collection_id, $fileId) { $modelFiles = new Default_Model_DbTable_PploadFiles(); $countAll = $modelFiles->fetchCountDownloadsForFileAllTime($collection_id, $fileId); $countToday = $modelFiles->fetchCountDownloadsForFileToday($collection_id, $fileId); $count = (int)$countAll+ (int)$countToday; return $count; } public function listsamesourceurlAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $result = $modelProduct->getSourceUrlProjects($productInfo->source_url); $r = '
'; foreach ($result as $value) { $r=$r.'
' .'
'.$value['title'].'
' .'' .'
'.$value['created_at'].'
' .'
'.$value['changed_at'].'
' .'
'; } $r = $r.'
'; /*$response='';*/ echo $r; } public function getfilesajaxAction() { $this->_helper->layout()->disableLayout(); $collection_id = null; $file_status = null; $ignore_status_code = null; if($this->hasParam('status')) { $file_status = $this->getParam('status'); } if($this->hasParam('ignore_status_code')) { $ignore_status_code = $this->getParam('ignore_status_code'); } $filesTable = new Default_Model_DbTable_PploadFiles(); if($this->hasParam('collection_id')) { $collection_id = $this->getParam('collection_id'); $result = array(); //Load files from DB if($ignore_status_code == 0 && $file_status == 'active') { $files = $filesTable->fetchAllActiveFilesForProject($collection_id); } else { $files = $filesTable->fetchAllFilesForProject($collection_id); } //Check, if the project category has tag-grous $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); $catTagGropuModel = new Default_Model_TagGroup(); $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($productInfo->project_category_id); foreach ($files as $file) { //add tag grous, if needed if(!empty($tagGroups)) { $groups = $this->getTagGroupsForCat($file['id']); $file['tag_groups'] = $groups; } //$file['downloaded_count_live'] = $this->getFileDownloadCount($collection_id, $file['id']); $counterToday = $file['count_dl_today']; $counterAll = $file['count_dl_all']; $counter = 0; if(!empty($counterToday)) { $counter = $counterToday; } if(!empty($counterAll)) { $counter = $counter + $counterAll; } $file['downloaded_count_live'] = $counter; $result[] = $file; } $this->_helper->json(array('status' => 'success', 'ResultSize' => count($result), 'files' => $result)); return; } $this->_helper->json(array('status' => 'error')); } public function getfiletagsajaxAction() { $this->_helper->layout()->disableLayout(); $fileId = null; if($this->hasParam('file_id')) { $fileId = $this->getParam('file_id'); $tagModel = new Default_Model_Tags(); $fileTags = $tagModel->getFileTags($fileId); $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($fileTags), 'file_tags' => $fileTags)); return; } $this->_helper->json(array('status' => 'error')); } public function 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); $salt = PPLOAD_DOWNLOAD_SECRET; $filesList = array(); foreach ($files as $file) { $timestamp = time() + 3600; // one hour valid $hash = hash('sha512',$salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; if(null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; $file['url'] = urlencode($url); $filesList[] = $file; } $this->view->filesJson = Zend_Json::encode($filesList); $this->view->filesCntJson = Zend_Json::encode($fmodel->fetchFilesCntForProject($this->view->product->ppload_collection_id)); $tableProjectUpdates = new Default_Model_ProjectUpdates(); $this->view->updatesJson = Zend_Json::encode($tableProjectUpdates->fetchProjectUpdates($this->_projectId)); $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); $ratings = $tableProjectRatings->fetchRating($this->_projectId); $cntRatingsActive = 0; foreach ($ratings as $p) { if($p['rating_active']==1) $cntRatingsActive =$cntRatingsActive+1; } $this->view->ratingsJson = Zend_Json::encode($ratings); $this->view->cntRatingsActiveJson = Zend_Json::encode($cntRatingsActive); $identity = Zend_Auth::getInstance()->getStorage()->read(); if (Zend_Auth::getInstance()->hasIdentity()){ $ratingOfUserJson = $tableProjectRatings->getProjectRateForUser($this->_projectId,$identity->member_id); $this->view->ratingOfUserJson = Zend_Json::encode($ratingOfUserJson); }else{ $this->view->ratingOfUserJson = Zend_Json::encode(null); } $tableProjectFollower = new Default_Model_DbTable_ProjectFollower(); $likes = $tableProjectFollower->fetchLikesForProject($this->_projectId); $this->view->likeJson = Zend_Json::encode($likes); $projectplings = new Default_Model_ProjectPlings(); $plings = $projectplings->fetchPlingsForProject($this->_projectId); $this->view->projectplingsJson = Zend_Json::encode($plings); $tableProject = new Default_Model_Project(); $galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId); $this->view->galleryPicturesJson = Zend_Json::encode($galleryPictures); $tagmodel = new Default_Model_Tags(); $tagsuser = $tagmodel->getTagsUser($this->_projectId, Default_Model_Tags::TAG_TYPE_PROJECT); $tagssystem = $tagmodel->getTagsSystemList($this->_projectId); $this->view->tagsuserJson = Zend_Json::encode($tagsuser); $this->view->tagssystemJson = Zend_Json::encode($tagssystem); $modelComments = new Default_Model_ProjectComments(); $offset = 0; $testComments = $modelComments->getCommentTreeForProjectList($this->_projectId); $this->view->commentsJson = Zend_Json::encode($testComments); $modelClone = new Default_Model_ProjectClone(); $origins = $modelClone->fetchOrigins($this->_projectId); $this->view->originsJson = Zend_Json::encode($origins); $related = $modelClone->fetchRelatedProducts($this->_projectId); $this->view->relatedJson = Zend_Json::encode($related); $moreProducts = $tableProject->fetchMoreProjects($this->view->product, 8); $this->view->moreProductsJson = Zend_Json::encode($moreProducts); $moreProducts = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8); $this->view->moreProductsOfOtherUsrJson = Zend_Json::encode($moreProducts); } public function indexAction() { if (!empty($this->_collectionId)) { $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductForCollectionId($this->_collectionId); $this->_projectId = $productInfo->project_id; } if (empty($this->_projectId)) { $this->redirect('/explore'); } $this->view->paramPageId = (int)$this->getParam('page'); $this->view->member_id = null; if(null != $this->_authMember && null != $this->_authMember->member_id) { $this->view->member_id = $this->_authMember->member_id; } // $this->fetchDataForIndexView(); $modelProduct = new Default_Model_Project(); $productInfo = $modelProduct->fetchProductInfo($this->_projectId); if (empty($productInfo)) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } //Check if this is a collection if($productInfo->type_id == $modelProduct::PROJECT_TYPE_COLLECTION) { $this->redirect('/c/'.$this->_projectId); } $this->view->product = $productInfo; $this->view->headTitle($productInfo->title . ' - ' . $this->getHeadTitle(), 'SET'); $this->view->cat_id = $this->view->product->project_category_id; //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(); $filesList = array(); if(isset($this->view->product->ppload_collection_id)) { $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id); if(!empty($files)) { foreach ($files as $file) { $timestamp = time() + 3600; // one hour valid $hash = hash('sha512',$salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp; if(null != $this->_authMember) { $url .= '/u/' . $this->_authMember->member_id; } $url .= '/lt/filepreview/' . $file['name']; $file['url'] = urlencode($url); //If this file is a video, we have to convert it for preview if(!empty($file['type']) && in_array($file['type'], Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES) && empty($file['ppload_file_preview_id'])) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_ConvertVideo($file['collection_id'], $file['id'], $file['type']); $queue->send(serialize($command)); } if(!empty($file['url_preview'])) { $file['url_preview'] = urlencode($file['url_preview']); } if(!empty($file['url_thumb'])) { $file['url_thumb'] = urlencode($file['url_thumb']); } $filesList[] = $file; } } } $this->view->filesJson = Zend_Json::encode($filesList); //gitlab if($this->view->product->is_gitlab_project) { $gitProject = $this->fetchGitlabProject($this->view->product->gitlab_project_id); if(null == $gitProject) { $this->view->product->is_gitlab_project = 0; $this->view->product->show_gitlab_project_issues = 0; $this->view->product->use_gitlab_project_readme = 0; $this->view->product->gitlab_project_id = null; } else { $this->view->gitlab_project = $gitProject; //show issues? if($this->view->product->show_gitlab_project_issues) { $issues = $this->fetchGitlabProjectIssues($this->view->product->gitlab_project_id); $this->view->gitlab_project_issues = $issues; $this->view->gitlab_project_issues_url = $this->view->gitlab_project['web_url'] . '/issues/'; } //show readme.md? if($this->view->product->use_gitlab_project_readme && null != $this->view->gitlab_project['readme_url']) { $config = Zend_Registry::get('config')->settings->server->opencode; $readme = $this->view->gitlab_project['web_url'].'/raw/master/README.md?inline=false'; $httpClient = new Zend_Http_Client($readme, array('keepalive' => true, 'strictredirects' => true)); $httpClient->resetParameters(); $httpClient->setUri($readme); $httpClient->setHeaders('Private-Token', $config->private_token); $httpClient->setHeaders('Sudo', $config->user_sudo); $httpClient->setHeaders('User-Agent', $config->user_agent); $httpClient->setMethod(Zend_Http_Client::GET); $response = $httpClient->request(); $body = $response->getRawBody(); if (count($body) == 0) { return array(); } include_once('Parsedown.php'); $Parsedown = new Parsedown(); $this->view->readme = $Parsedown->text($body); } else { $this->view->readme = null; } } } $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() { $this->view->member = $this->_authMember; $this->view->mode = 'add'; $form = new Default_Form_Product(array('member_id' => $this->view->member->member_id)); $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(); $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 (100 < $this->_authMember->roleId) { if (Default_Model_Spam::hasSpamMarkers($newProject->toArray())) { $tableReportComments = new Default_Model_DbTable_ReportProducts(); $tableReportComments->save(array('project_id' => $newProject->project_id, 'reported_by' => 24, 'text' => "System: automatic spam detection")); } Default_Model_DbTable_SuspicionLog::logProject($newProject, $this->_authMember, $this->getRequest()); } } catch (Zend_Exception $e) { Zend_Registry::get('logger')->err($e->getMessage()); } $this->redirect('/member/' . $newProject->member_id . '/products/'); } private function saveGalleryPics($form_element) { $imageModel = new Default_Model_DbTable_Image(); return $imageModel->saveImages($form_element); } /** * @param $projectData * * @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, 'member_id' => $this->view->member_id)); if (false === empty($projectData->image_small)) { $form->getElement('image_small_upload')->setRequired(false); } $form->getElement('preview')->setLabel('Save'); $form->removeElement('project_id'); // we don't need this field in edit mode if ($this->_request->isGet()) { $form->populate($projectData->toArray()); // $form->populate(array('tags' => $modelTags->getTags($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT))); $form->populate(array('tagsuser' => $modelTags->getTagsUser($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT))); $form->getElement('image_small')->setValue($projectData->image_small); //Bilder voreinstellen $form->getElement(self::IMAGE_SMALL_UPLOAD)->setValue($projectData->image_small); $licenseTags = $tagTable->fetchLicenseTagsForProject($this->_projectId); $licenseTag = null; if($licenseTags) { $licenseTag = $licenseTags[0]['tag_id']; } $form->getElement('license_tag_id')->setValue($licenseTag); $is_original = $modelTags->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', '\\1', '\1\2', 'Quote:
\1
', '\\1' ); $newtxt = preg_replace($patterns, $replaces, $newtxt); return ($newtxt); } protected function readExploreUrlFromReferrer() { $helperBuildExploreUrl = new Default_View_Helper_BuildExploreUrl(); $referrerExplore = $helperBuildExploreUrl->buildExploreUrl(null, null, null, null, true); /** @var Zend_Controller_Request_Http $request */ $request = $this->getRequest(); if (strpos($request->getHeader('referer'), $referrerExplore) !== false) { return $request->getHeader('referer'); } } public function plingAction() { if (empty($this->_projectId)) { $this->redirect('/explore'); } $this->view->authMember = $this->_authMember; $this->fetchDataForIndexView(); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $this->view->urlPay = $helperBuildProductUrl->buildProductUrl($this->_projectId, 'pay'); $this->view->amount = (float)$this->getParam('amount', 1); $this->view->comment = html_entity_decode(strip_tags($this->getParam('comment'), null), ENT_QUOTES, 'utf-8'); $this->view->provider = mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'), 'utf-8'); $this->view->headTitle($this->_browserTitlePrepend . $this->view->product->title, 'SET'); $helperUserIsOwner = new Default_View_Helper_UserIsOwner(); $helperIsProjectActive = new Default_View_Helper_IsProjectActive(); if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id)) ) { throw new Zend_Controller_Action_Exception('This page does not exist', 404); } $tableProject = new Default_Model_Project(); $this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId); } public function payAction() { $this->_helper->layout()->disableLayout(); $tableProject = new Default_Model_Project(); $project = $tableProject->fetchProductInfo($this->_projectId); //get parameter $amount = (float)$this->getParam('amount', 1); $comment = Default_Model_HtmlPurify::purify($this->getParam('comment')); $paymentProvider = mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'), 'utf-8'); $hideIdentity = (int)$this->getParam('hideId', 0); $paymentGateway = $this->createPaymentGateway($paymentProvider); $paymentGateway->getUserDataStore()->generateFromArray($project->toArray()); $requestMessage = 'Thank you for supporting: ' . $paymentGateway->getUserDataStore()->getProductTitle(); $response = null; try { $response = $paymentGateway->requestPayment($amount, $requestMessage); $this->view->checkoutEndpoint = $paymentGateway->getCheckoutEndpoint(); $this->view->paymentKey = $response->getPaymentId(); $this->_helper->viewRenderer->setRender('pay_' . $paymentProvider); } catch (Exception $e) { throw new Zend_Controller_Action_Exception('payment error', 500, $e); } if (false === $response->isSuccessful()) { throw new Zend_Controller_Action_Exception('payment failure', 500); } if (empty($this->_authMember->member_id) or ($hideIdentity == 1)) { $memberId = 1; } else { $memberId = $this->_authMember->member_id; } //Add pling $modelPlings = new Default_Model_DbTable_Plings(); $plingId = $modelPlings->createNewPlingFromResponse($response, $memberId, $project->project_id, $amount); if (false == empty($comment)) { $modelComments = new Default_Model_ProjectComments(); $dataComment = array( 'comment_type' => Default_Model_DbTable_Comments::COMMENT_TYPE_PLING, 'comment_target_id' => $project->project_id, 'comment_member_id' => $memberId, 'comment_pling_id' => $plingId, 'comment_text' => $comment ); $modelComments->save($dataComment); } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $memberId, Default_Model_ActivityLog::PROJECT_PLINGED, $project->toArray()); } /** * @param string $paymentProvider * * @return Local_Payment_GatewayInterface * @throws Exception * @throws Local_Payment_Exception * @throws Zend_Controller_Exception * @throws Zend_Exception */ protected function createPaymentGateway($paymentProvider) { $httpHost = $this->getRequest()->getHttpHost(); /** @var Zend_Config $config */ $config = Zend_Registry::get('config'); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); switch ($paymentProvider) { case 'paypal': $paymentGateway = new Default_Model_PayPal_Gateway($config->third_party->paypal); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal'); // $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal?XDEBUG_SESSION_START=1'); $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentcancel', null, true)); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok', null, true)); break; case 'dwolla': $paymentGateway = new Default_Model_Dwolla_Gateway($config->third_party->dwolla); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/dwolla'); // $paymentGateway->setIpnNotificationUrl('http://' . $_SERVER ['HTTP_HOST'] . '/gateway/dwolla?XDEBUG_SESSION_START=1'); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'dwolla', null, true)); break; case 'amazon': $paymentGateway = new Default_Model_Amazon_Gateway($config->third_party->amazon); $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon'); // $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon?XDEBUG_SESSION_START=1'); $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentcancel', null, true)); $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok', null, true)); break; default: throw new Zend_Controller_Exception('No known payment provider found in parameters.'); break; } return $paymentGateway; } public function dwollaAction() { $modelPling = new Default_Model_DbTable_Plings(); $plingData = $modelPling->fetchRow(array('payment_reference_key = ?' => $this->getParam('checkoutId'))); $plingData->payment_transaction_id = (int)$this->getParam('transaction'); $plingData->save(); if ($this->_getParam('status') == 'Completed') { $this->_helper->viewRenderer('paymentok'); $this->paymentokAction(); } else { $this->_helper->viewRenderer('paymentcancel'); $this->paymentcancelAction(); } } public function paymentokAction() { $this->_helper->layout()->disableLayout(); $this->view->paymentStatus = 'success'; $this->view->paymentMessage = 'Payment successful.'; $this->fetchDataForIndexView(); } public function paymentcancelAction() { $this->_helper->layout()->disableLayout(); $this->view->paymentStatus = 'danger'; $this->view->paymentMessage = 'Payment cancelled.'; $this->fetchDataForIndexView(); } public function deleteAction() { $this->_helper->layout()->setLayout('flat_ui'); $memberId = (int)$this->getParam('m'); if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id != $memberId) ) { $this->forward('products', 'user', 'default'); return; } $tableProduct = new Default_Model_Project(); $tableProduct->setDeleted($this->_authMember->member_id,$this->_projectId); $product = $tableProduct->find($this->_projectId)->current(); // delete product from search index $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->deleteDocument($product->toArray()); // $command = new Backend_Commands_DeleteProductExtended($product); // $command->doCommand(); // $queue = Local_Queue_Factory::getQueue('search'); // $command = new Backend_Commands_DeleteProductFromIndex($product->project_id, $product->project_category_id); // $msg = $queue->send(serialize($command)); // ppload // Delete collection if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $collectionResponse = $pploadApi->deleteCollection($product->ppload_collection_id); } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_DELETED, $product->toArray()); $this->forward('products', 'user', 'default'); } public function unpublishAction() { $this->_helper->layout()->setLayout('flat_ui'); $memberId = (int)$this->getParam('m'); if ( (empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id != $memberId) ) { return; } $tableProduct = new Default_Model_Project(); $tableProduct->setInActive($this->_projectId, $memberId); $product = $tableProduct->find($this->_projectId)->current(); if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) { $parentProduct = $tableProduct->find($product->pid)->current(); $product->image_small = $parentProduct->image_small; } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_UNPUBLISHED, $product->toArray()); // remove unpublished project from search index $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->deleteDocument($product); // ppload if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionRequest = array( 'category' => $product->project_category_id ); $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest); } $this->forward('products', 'user', 'default', array('member_id' => $memberId)); //$this->redirect('/member/'.$memberId.'/products'); } public function publishAction() { $memberId = (int)$this->getParam('m'); if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id != $memberId) ) { return; } $tableProduct = new Default_Model_Project(); $tableProduct->setActive($this->_authMember->member_id,$this->_projectId); $product = $tableProduct->find($this->_projectId)->current(); if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) { $parentProduct = $tableProduct->find($product->pid)->current(); $product->image_small = $parentProduct->image_small; } $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id, Default_Model_ActivityLog::PROJECT_PUBLISHED, $product->toArray()); // add published project to search index $productInfo = $tableProduct->fetchProductInfo($this->_projectId); $modelSearch = new Default_Model_Search_Lucene(); $modelSearch->addDocument($productInfo); // ppload if ($product->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); // Update collection information $collectionRequest = array( 'category' => $product->project_category_id . '-published' ); $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest); } $this->forward('products', 'user', 'default', array('member_id' => $memberId)); //$this->redirect('/member/'.$memberId.'/products'); } public function loadratingsAction() { $this->_helper->layout->disableLayout(); $tableProjectRatings = new Default_Model_DbTable_ProjectRating(); $ratings = $tableProjectRatings->fetchRating($this->_projectId); $this->_helper->json($ratings); } public function 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 if((int)$this->_authMember->member_id==(int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$this->_authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); } $projectData->ghns_excluded = 0; $projectData->save(); $activityLog = new Default_Model_ActivityLog(); $activityLog->writeActivityLog($this->_projectId, $projectData->member_id, Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray()); // Update profile information $memberTable = new Default_Model_DbTable_Member(); $memberSettings = $memberTable->find($this->_authMember->member_id)->current(); $mainproject = $projectTable->find($memberSettings->main_project_id)->current(); $profileName = ''; if ($memberSettings->firstname || $memberSettings->lastname ) { $profileName = trim($memberSettings->firstname . ' ' . $memberSettings->lastname); } else { if ($memberSettings->username) { $profileName = $memberSettings->username; } } $profileRequest = array( 'owner_id' => $this->_authMember->member_id, 'name' => $profileName, 'email' => $memberSettings->mail, 'homepage' => $memberSettings->link_website, 'description' => $mainproject->description ); $profileResponse = $pploadApi->postProfile($profileRequest); // Update collection information $collectionCategory = $projectData->project_category_id; if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) { $collectionCategory .= '-published'; } $collectionRequest = array( 'title' => $projectData->title, 'description' => $projectData->description, 'category' => $collectionCategory, 'content_id' => $projectData->project_id ); $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest); // Store product image as collection thumbnail $this->_updatePploadMediaCollectionthumbnail($projectData); } else { //20180219 ronald: we set the changed_at only by new files or new updates if((int)$this->_authMember->member_id==(int)$projectData->member_id) { $projectData->changed_at = new Zend_Db_Expr('NOW()'); } else { $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$this->_authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); } $projectData->ghns_excluded = 0; $projectData->save(); } //If this file is a video, we have to convert it for preview if(!empty($fileResponse->file->type) && in_array($fileResponse->file->type, Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES)) { $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_ConvertVideo($projectData->ppload_collection_id, $fileResponse->file->id, $fileResponse->file->type); $queue->send(serialize($command)); } $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; + + //20180219 ronald: we set the changed_at only by new files or new updates + if((int)$this->_authMember->member_id==(int)$projectData->member_id) + { + $projectData->changed_at = new Zend_Db_Expr('NOW()'); + } else { + $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member ('.$this->_authMember->member_id.') != Project-Owner ('.$projectData->member_id.'): **********' . "\n"); + } + $projectData->ghns_excluded = 0; + $projectData->save(); + } if (isset($_POST['file_description'])) { $fileRequest['description'] = mb_substr($_POST['file_description'], 0, 140); } if (isset($_POST['file_category'])) { $fileRequest['category'] = $_POST['file_category']; } if (isset($_POST['file_tags'])) { $fileRequest['tags'] = $_POST['file_tags']; } if (isset($_POST['ocs_compatible'])) { $fileRequest['ocs_compatible'] = $_POST['ocs_compatible']; } if (isset($_POST['file_version'])) { $fileRequest['version'] = $_POST['file_version']; } $fileResponse = $pploadApi->putFile($_POST['file_id'], $fileRequest); $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($fileResponse, true) . "\n"); if ($tmpFilename) { unlink($tmpFilename); } if (isset($fileResponse->status) && $fileResponse->status == 'success' ) { $this->_helper->json(array( 'status' => 'ok', 'file' => $fileResponse->file )); return; } else { $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse) . '; $fileResponse->status: ' . $fileResponse->status; } } else { $error_text .= 'PPload Response: ' . json_encode($fileResponse) . '; fileResponse->file->collection_id: ' . $fileResponse->file->collection_id . ' != $projectData->ppload_collection_id: ' . $projectData->ppload_collection_id; } } else { $error_text .= 'No CollectionId or no FileId. CollectionId: ' . $projectData->ppload_collection_id . ', FileId: ' . $_POST['file_id']; } $log->debug('********** END ' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n"); $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function updatefiletagAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $tagId = null; if (isset($_POST['tag_id'])) { $tagId = $_POST['tag_id']; } $tagGroupId = null; if (isset($_POST['tag_group_id'])) { $tagGroupId = $_POST['tag_group_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->saveFileTagForProjectAndTagGroup($this->_projectId, $_POST['file_id'], $tagId, $tagGroupId); $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function deletefiletagAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $tagId = null; if (isset($_POST['tag_id'])) { $tagId = $_POST['tag_id']; } //set architecture $modelTags = new Default_Model_Tags(); $modelTags->deleteFileTagForProject($this->_projectId, $_POST['file_id'], $tagId); $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function updatecompatibleAction() { $this->_helper->layout()->disableLayout(); $error_text = ''; // Update a file information in ppload collection if (!empty($_POST['file_id'])) { $typeId = null; if (isset($_POST['is_compatible'])) { $is_compatible = $_POST['is_compatible']; } return; } else { $error_text .= 'No FileId. , FileId: ' . $_POST['file_id']; } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } public function startdownloadAction() { $this->_helper->layout()->disableLayout(); /** * Save Download-Data in Member_Download_History */ $file_id = $this->getParam('file_id'); $file_type = $this->getParam('file_type'); $file_name = $this->getParam('file_name'); $file_size = $this->getParam('file_size'); $projectId = $this->_projectId; $this->redirect('/dl?file_id='.$file_id.'&file_type='.$file_type.'&file_name='.$file_name.'&file_size='.$file_size.'&project_id='.$projectId); // if ($_SERVER['REQUEST_METHOD'] == 'POST') { /* if(isset($file_id) && isset($projectId) && isset($memberId)) { $memberDlHistory = new Default_Model_DbTable_MemberDownloadHistory(); $data = array('project_id' => $projectId, 'member_id' => $memberId, 'file_id' => $file_id, 'file_type' => $file_type, 'file_name' => $file_name, 'file_size' => $file_size); $memberDlHistory->createRow($data)->save(); } $url = urldecode($urltring); $this->redirect($url); * */ // } else { // $this->redirect('/ads?file_id='.$file_id); // } } /** * ppload */ public function deletepploadfileAction() { $this->_helper->layout()->disableLayout(); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); $error_text = ''; // Delete file from ppload collection if (!empty($_POST['file_id'])) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $fileResponse = $pploadApi->getFile($_POST['file_id']); if (isset($fileResponse->file->collection_id) && $fileResponse->file->collection_id == $projectData->ppload_collection_id ) { $fileResponse = $pploadApi->deleteFile($_POST['file_id']); if (isset($fileResponse->status) && $fileResponse->status == 'success' ) { $this->_helper->json(array('status' => 'ok')); return; } else { $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse); } } } $this->_helper->json(array('status' => 'error', 'error_text' => $error_text)); } /** * ppload */ public function deletepploadfilesAction() { $this->_helper->layout()->disableLayout(); $projectTable = new Default_Model_DbTable_Project(); $projectData = $projectTable->find($this->_projectId)->current(); // Delete all files in ppload collection if ($projectData->ppload_collection_id) { $pploadApi = new Ppload_Api(array( 'apiUri' => PPLOAD_API_URI, 'clientId' => PPLOAD_CLIENT_ID, 'secret' => PPLOAD_SECRET )); $filesRequest = array( 'collection_id' => $projectData->ppload_collection_id, 'perpage' => 1000 ); $filesResponse = $pploadApi->getFiles($filesRequest); if (isset($filesResponse->status) && $filesResponse->status == 'success' ) { foreach ($filesResponse->files as $file) { $fileResponse = $pploadApi->deleteFile($file->id); if (!isset($fileResponse->status) || $fileResponse->status != 'success' ) { $this->_helper->json(array('status' => 'error')); return; } } } $this->_helper->json(array('status' => 'ok')); return; } $this->_helper->json(array('status' => 'error')); } /** * 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'); $this->view->store = $this->getParam('domain_store_id'); } /** * @param $memberId * * @throws Zend_Db_Table_Exception */ protected function setViewDataForMyProducts($memberId) { $tableMember = new Default_Model_Member(); $this->view->member = $tableMember->find($memberId)->current(); $tableProduct = new Default_Model_Project(); $this->view->products = $tableProduct->fetchAllProjectsForMember($memberId); } protected function _initResponseHeader() { $duration = 1800; // in seconds $expires = gmdate("D, d M Y H:i:s", time() + $duration) . " GMT"; $this->getResponse()->setHeader('X-FRAME-OPTIONS', 'ALLOWALL', true)// ->setHeader('Last-Modified', $modifiedTime, true) ->setHeader('Expires', $expires, true)->setHeader('Pragma', 'no-cache', true) ->setHeader('Cache-Control', 'private, no-cache, must-revalidate', true) ; } /** * @param $hits * * @return array */ protected function generateProjectsArrayForView($hits) { $viewArray = array(); $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); /** @var $hit Zend_Search_Lucene_Search_QueryHit */ foreach ($hits as $hit) { $project = $hit->getDocument(); if (null != $project->username) { $isUpdate = ($project->type_id == 2); if ($isUpdate) { $showUrl = $helperBuildProductUrl->buildProductUrl($project->pid) . '#anker_' . $project->project_id; $plingUrl = $helperBuildProductUrl->buildProductUrl($project->pid, 'pling'); } else { $showUrl = $helperBuildProductUrl->buildProductUrl($project->project_id); $plingUrl = $helperBuildProductUrl->buildProductUrl($project->project_id, 'pling'); } $projectArr = array( 'score' => $hit->score, 'id' => $project->project_id, 'type_id' => $project->type_id, 'title' => $project->title, 'description' => $project->description, 'image' => $project->image_small, 'plings' => 0, 'urlGoal' => $showUrl, 'urlPling' => $plingUrl, 'showUrlPling' => ($project->paypal_mail != null), 'member' => array( 'name' => $project->username, 'url' => 'member/' . $project->member_id, 'image' => $project->profile_image_url, 'id' => $project->member_id ) ); $viewArray[] = $projectArr; } } return $viewArray; } protected function setLayout() { $layoutName = 'flat_ui_template'; $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null; if($storeConfig && $storeConfig->layout_pagedetail) { $this->_helper->layout()->setLayout($storeConfig->layout_pagedetail); }else{ $this->_helper->layout()->setLayout($layoutName); } } private function fetchGitlabProject($gitProjectId) { $gitlab = new Default_Model_Ocs_Gitlab(); try { $gitProject = $gitlab->getProject($gitProjectId); } catch (Exception $exc) { //Project is gone $modelProject = new Default_Model_Project(); $modelProject->updateProject($this->_projectId, array('is_gitlab_project' => 0, 'gitlab_project_id' => null, 'show_gitlab_project_issues' => 0, 'use_gitlab_project_readme' => 0)); $gitProject = null; } return $gitProject; } private function fetchGitlabProjectIssues($gitProjectId) { $gitlab = new Default_Model_Ocs_Gitlab(); try { $gitProjectIssues = $gitlab->getProjectIssues($gitProjectId); } catch (Exception $exc) { //Project is gone $modelProject = new Default_Model_Project(); $modelProject->updateProject($this->_projectId, array('is_gitlab_project' => 0, 'gitlab_project_id' => null, 'show_gitlab_project_issues' => 0, 'use_gitlab_project_readme' => 0)); $gitProjectIssues = null; } return $gitProjectIssues; } public function startvideoajaxAction() { $this->_helper->layout()->disableLayout(); $collection_id = null; $file_id = null; $memberId = $this->_authMember->member_id; if($this->hasParam('collection_id') && $this->hasParam('file_id')) { $collection_id = $this->getParam('collection_id'); $file_id = $this->getParam('file_id'); $id = null; //Log media view try { $mediaviewsTable = new Default_Model_DbTable_MediaViews(); $id = $mediaviewsTable->getNewId(); $data = array('media_view_id' => $id, 'media_view_type_id' => $mediaviewsTable::MEDIA_TYPE_VIDEO, 'project_id' => $this->_projectId, 'collection_id' => $collection_id, 'file_id' => $file_id, 'start_timestamp' => new Zend_Db_Expr ('Now()'), 'ip' => $this->getRealIpAddr(), 'referer' => $this->getReferer()); if(!empty($memberId)) { $data['member_id'] = $memberId; } $data['source'] = 'OCS-Webserver'; $mediaviewsTable->createRow($data)->save(); } catch (Exception $exc) { //echo $exc->getTraceAsString(); $errorLog = Zend_Registry::get('logger'); $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); } $this->_helper->json(array('status' => 'success', 'MediaViewId' => $id)); return; } $this->_helper->json(array('status' => 'error')); } public function stopvideoajaxAction() { $this->_helper->layout()->disableLayout(); $view_id = null; if($this->hasParam('media_view_id')) { $view_id = $this->getParam('media_view_id'); //Log media view stop try { $mediaviewsTable = new Default_Model_DbTable_MediaViews(); $data = array('stop_timestamp' => new Zend_Db_Expr ('Now()')); $mediaviewsTable->update($data, 'media_view_id = '. $view_id); } catch (Exception $exc) { //echo $exc->getTraceAsString(); $errorLog = Zend_Registry::get('logger'); $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL); } $this->_helper->json(array('status' => 'success', 'MediaViewId' => $view_id)); return; } $this->_helper->json(array('status' => 'error')); } function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } function getReferer() { $referer = null; if (!empty($_SERVER['HTTP_REFERER'])) { $referer = $_SERVER['HTTP_REFERER']; } return $referer; } } diff --git a/application/modules/default/controllers/ProductcommentController.php b/application/modules/default/controllers/ProductcommentController.php index 72b72f3d7..68b994f98 100644 --- a/application/modules/default/controllers/ProductcommentController.php +++ b/application/modules/default/controllers/ProductcommentController.php @@ -1,279 +1,280 @@ . **/ class ProductcommentController extends Local_Controller_Action_DomainSwitch { /** @var Zend_Auth */ protected $_auth; public function init() { parent::init(); $this->auth = Zend_Auth::getInstance(); } public function indexAction() { $this->_helper->layout->disableLayout(); $project_id = (int)$this->getParam('p'); $cmodel = new Default_Model_ProjectComments(); $list = $cmodel->getCommentTreeForProjectList($project_id); $this->_helper->json($list); } public function addreplyAction() { $this->_helper->layout->disableLayout(); //$this->_helper->viewRenderer->setNoRender(true); 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') ; $data = array(); $data['comment_target_id'] = (int)$this->getParam('p'); $data['comment_parent_id'] = (int)$this->getParam('i'); $data['comment_member_id'] = (int)$this->_authMember->member_id; $data['comment_text'] = Default_Model_HtmlPurify::purify($this->getParam('msg')); $tableReplies = new Default_Model_ProjectComments(); $result = $tableReplies->save($data); $status = count($result->toArray()) > 0 ? 'ok' : 'error'; $message = ''; $this->view->comments = $this->loadComments((int)$this->getParam('page'), (int)$this->getParam('p')); $this->view->product = $this->loadProductInfo((int)$this->getParam('p')); $this->view->member_id = (int)$this->_authMember->member_id; $this->updateActivityLog($result, $this->view->product->image_small); //Send a notification to the owner $this->sendNotificationToOwner($this->view->product, $data['comment_text']); //Send a notification to the parent comment writer $this->sendNotificationToParent($this->view->product, $data['comment_text'], $data['comment_parent_id']); if ($this->_request->isXmlHttpRequest()) { $requestResult = $this->view->render('product/partials/productCommentsUX1.phtml'); $this->_helper->json(array('status' => $status, 'message' => $message, 'data' => $requestResult)); } else { $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl(); $url = $helperBuildProductUrl->buildProductUrl($data['comment_target_id']); $this->redirect($url); } } private function loadComments($page_offset, $project_id) { $modelComments = new Default_Model_ProjectComments(); $paginationComments = $modelComments->getCommentTreeForProject($project_id); $paginationComments->setItemCountPerPage(25); $paginationComments->setCurrentPageNumber($page_offset); return $paginationComments; } private function loadProductInfo($param) { $tableProject = new Default_Model_Project(); return $tableProject->fetchProductInfo($param); } private function updateActivityLog($data, $image_small) { if ($data['comment_parent_id']) { $activity_type = Default_Model_ActivityLog::PROJECT_COMMENT_REPLY; } else { $activity_type = Default_Model_ActivityLog::PROJECT_COMMENT_CREATED; } Default_Model_ActivityLog::logActivity($data['comment_id'], $data['comment_target_id'], $data['comment_member_id'], $activity_type, array('title' => '', 'description' => $data['comment_text'], 'image_small' => $image_small)); } /** * @param Zend_Db_Table_Row_Abstract $product * @param string $comment */ private function sendNotificationToOwner($product, $comment) { //Don't send email notification for comments from product owner if ($this->_authMember->member_id == $product->member_id) { return; } $productData = new stdClass(); $productData->mail = $product->mail; $productData->username = $product->username; $productData->username_sender = $this->_authMember->username; $productData->title = $product->title; $productData->project_id = $product->project_id; $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_SendCommentNotification('tpl_user_comment_note', $productData, $comment); $queue->send(serialize($command)); } private function sendNotificationToParent($product, $comment, $parent_id) { if (0 == $parent_id) { return; } $tableReplies = new Default_Model_ProjectComments(); $parentComment = $tableReplies->getCommentWithMember($parent_id); if (0 == count($parentComment)) { return; } if ($this->_authMember->member_id == $parentComment['member_id']) { return; } // email sent by sendNotificationToOwner already if ($product->member_id == $parentComment['member_id']) { return; } $productData = new stdClass(); $productData->mail = $parentComment['mail']; $productData->username = $parentComment['username']; $productData->username_sender = $this->_authMember->username; $productData->title = $product->title; $productData->project_id = $product->project_id; $queue = Local_Queue_Factory::getQueue(); $command = new Backend_Commands_SendCommentNotification('tpl_user_comment_reply_note', $productData, $comment); $queue->send(serialize($command)); } public function addreplyreviewAction() { $this->_helper->layout->disableLayout(); $msg = trim($this->getParam('msg')); $project_id = (int)$this->getParam('p'); $comment_id = null; $status = 'ok'; $message = ''; //Only Supporter can make a review if(Zend_Auth::getInstance()->hasIdentity() ) { if ($msg != '' && strlen($msg)>0) { // $data = array(); // $data['comment_target_id'] = (int)$this->getParam('p'); // $data['comment_parent_id'] = (int)$this->getParam('i'); // $data['comment_member_id'] = (int)$this->_authMember->member_id; // $data['comment_text'] = Default_Model_HtmlPurify::purify($this->getParam('msg')); $voteup = (int)$this->getParam('v'); // negative voting msg length > 5 if($voteup ==2 && strlen($msg) < 5) { $this->_helper->json(array('status' => 'error', 'message' => ' At least 5 chars. ', 'data' => '')); return; } $modelRating = new Default_Model_DbTable_ProjectRating(); $modelRating->rateForProject($project_id, $this->_authMember->member_id, $voteup, $msg); $this->view->product = $this->loadProductInfo((int)$this->getParam('p')); $this->view->member_id = (int)$this->_authMember->member_id; if($this->view->product){ //Send a notification to the owner $this->sendNotificationToOwner($this->view->product, Default_Model_HtmlPurify::purify($this->getParam('msg'))); } } $this->_helper->json(array('status' => $status, 'message' => $message, 'data' => '','laplace_score' =>$this->view->product->laplace_score)); } else { $this->_helper->json(array('status' => 'error', 'message' => 'Only registered members with an active supporting can vote!', 'data' => '')); } } public function addreplyreviewnewAction() { $this->_helper->layout->disableLayout(); $msg = trim($this->getParam('msg')); $project_id = (int)$this->getParam('p'); $comment_id = null; $status = 'ok'; $message = ''; - - - - //Only Supporter can make a review + + if(Zend_Auth::getInstance()->hasIdentity() ) { - if ($msg != '' && strlen($msg)>0) { - - + if ($msg != '' && strlen($msg)>0) { $score = (int)$this->getParam('s'); - // negative voting msg length > 5 if($score < 6 && strlen($msg) < 5) { $this->_helper->json(array('status' => 'error', 'message' => ' At least 5 chars. ', 'data' => '')); return; } - $modelRating = new Default_Model_DbTable_ProjectRating(); - $modelRating->scoreForProject($project_id, $this->_authMember->member_id, $score, $msg); - $this->view->product = $this->loadProductInfo((int)$this->getParam('p')); $this->view->member_id = (int)$this->_authMember->member_id; + if($this->view->product->member_id==$this->view->member_id) + { + $this->_helper->json(array('status' => 'error', 'message' => ' Not allowed. ', 'data' => '')); + return; + } + $modelRating = new Default_Model_DbTable_ProjectRating(); + $modelRating->scoreForProject($project_id, $this->_authMember->member_id, $score, $msg); + + + if($this->view->product){ //Send a notification to the owner - $this->sendNotificationToOwner($this->view->product, Default_Model_HtmlPurify::purify($this->getParam('msg'))); - + $this->sendNotificationToOwner($this->view->product, Default_Model_HtmlPurify::purify($this->getParam('msg'))); } } $this->_helper->json(array('status' => $status, 'message' => $message, 'data' => '','laplace_score' =>$this->view->product->laplace_score)); } else { $this->_helper->json(array('status' => 'error', 'message' => 'Only registered members with an active supporting can vote!', 'data' => '')); } } } \ No newline at end of file diff --git a/application/modules/default/views/scripts/product/partials/details.phtml b/application/modules/default/views/scripts/product/partials/details.phtml index 2f9f72b90..747346447 100644 --- a/application/modules/default/views/scripts/product/partials/details.phtml +++ b/application/modules/default/views/scripts/product/partials/details.phtml @@ -1,354 +1,357 @@ . **/ $tableProject = new Default_Model_Project(); $this->product_views = $tableProject->fetchProjectViews($this->product->project_id); $helperUserRole = new Backend_View_Helper_UserRole(); $userRoleName = $helperUserRole->userRole(); $tableTags = new Default_Model_Tags(); $tagsArray = $tableTags->getTagsArray($this->product->project_id, $tableTags::TAG_TYPE_PROJECT, $tableTags::TAG_GHNS_EXCLUDED_GROUPID); $isGhnsExcluded = false; if(isset($tagsArray) && (count($tagsArray) == 1)) { $isGhnsExcluded = true; } $filesTable = new Default_Model_DbTable_PploadFiles(); $countDownloadsToday = $filesTable->fetchCountDownloadsTodayForProject($this->product->ppload_collection_id); $mediaViewsTable = new Default_Model_DbTable_MediaViews(); $countMediaViewsToday = $mediaViewsTable->fetchCountViewsTodayForProject($this->product->project_id); $countMediaViewsAlltime = $mediaViewsTable->fetchCountViewsForProjectAllTime($this->product->project_id); $countPageviews = $this->projectDetailCounts($this->product->project_id); $countPageviewsTotal = 0; $countPageviewsToday = $countPageviews[0]['count_views']; if(sizeof($countPageviews)==2) $countPageviewsTotal = $countPageviews[1]['count_views']; // $heute = date("Y-m-d H:i:s"); $today = (new DateTime())->modify('-1 day'); $filterDownloadToday = $today->format("Y-m-d H:i:s"); ?>
Details
license
product->project_license_title; ?>
version
product->project_version); ?>
product->project_changed_at) { ?>
updated printDate($this->product->project_changed_at) ?>
major updated printDate($this->product->project_major_updated_at) ?>
added printDate($this->product->project_created_at) ?>
downloads today
+ + +
+ video views today + +
+ +
+ video views total + +
+ +
page views today
page views total
-
- video views today - -
- -
- video views total - -
-
spam reports fetchReportsSpamCnt($this->product->project_id) ?>
misuse reports fetchReportsMisuseCnt($this->product->project_id)?>
link to hive delete product
(remember the cache) after you change some value below and refresh the page you may encounter some differences to your changes
product->spam_checked == 1 ? ' checked=\'checked\' ' : ''; ?> /> spam checked product->featured == 1 ? ' checked=\'checked\' ' : ''; ?> /> featured /> ghns-excluded product->pling_excluded == 1 ? ' checked=\'checked\' ' : ''; ?> /> pling-excluded /> ghns-excluded
inlineScript()->appendScript( ' $(document).ready(function(){ GhnsExcludedClick.setup('.$this->product->project_id.'); }); '); } diff --git a/application/modules/statistics/Bootstrap.php b/application/modules/statistics/Bootstrap.php new file mode 100644 index 000000000..8dcba440a --- /dev/null +++ b/application/modules/statistics/Bootstrap.php @@ -0,0 +1,99 @@ +. + **/ +class Statistics_Bootstrap extends Zend_Application_Module_Bootstrap +{ + + protected function _initAutoloader() + { + $autoloader = new Zend_Application_Module_Autoloader(array( + 'namespace' => 'Statistics', + 'basePath' => realpath(dirname(__FILE__)), + )); + $autoloader->addResourceType('Ranking', 'library/statistics/ranking', 'Ranking'); + return $autoloader; + } + + protected function _initRouter() + { + $frontController = Zend_Controller_Front::getInstance(); + /** @var $router Zend_Controller_Router_Rewrite */ + $router = $frontController->getRouter(); + +// $dir = $router->getFrontController()->getControllerDirectory(); + + $router->addRoute( + 'statistics_daily_ajax', + new Zend_Controller_Router_Route( + '/statistics/daily/ajax/:project_id/:year/:month/:day/', + array( + 'module' => 'statistics', + 'controller' => 'daily', + 'action' => 'ajax', + 'project_id' => null, + 'year' => null, + 'month' => null, + 'day' => null + ) + ) + ); + + $router->addRoute( + 'statistics_monthly_ajax', + new Zend_Controller_Router_Route( + '/statistics/monthly/ajax/:project_id/:year/:month/', + array( + 'module' => 'statistics', + 'controller' => 'monthly', + 'action' => 'ajax', + 'project_id' => null, + 'year' => null, + 'month' => null + ) + ) + ); + + $router->addRoute( + 'statistics_weekly_ajax', + new Zend_Controller_Router_Route( + '/statistics/weekly/ajax/:project_id/:yearweek/', + array( + 'module' => 'statistics', + 'controller' => 'weekly', + 'action' => 'ajax', + 'project_id' => null, + 'yearweek' => null + ) + ) + ); + + return $router; + } + + protected function _initIncludePath () { + set_include_path(implode(PATH_SEPARATOR, array( + dirname(__FILE__) . '/library', + get_include_path(), + ))); + } + +} + diff --git a/application/modules/statistics/controllers/CronController.php b/application/modules/statistics/controllers/CronController.php new file mode 100644 index 000000000..bda8c2922 --- /dev/null +++ b/application/modules/statistics/controllers/CronController.php @@ -0,0 +1,64 @@ +. + **/ +class Statistics_CronController extends Local_Controller_Action_CliAbstract +{ + + const DATE_FORMAT = "Y-m-d"; + + public function runAction() + { + $today = new DateTime(); + // $yesterday = $today->sub(new DateInterval("P1D")); + + $validator = new Zend_Validate_Date(array('format' => self::DATE_FORMAT)); + + $date = $this->getRequest()->getParam('date', $today->format(self::DATE_FORMAT)); + if ($validator->isValid($date)) { + $statistics = new Statistics_Model_GoalStatistics(); + $result = $statistics->generateDailyStatistics($date); + + foreach (get_object_vars($result) as $name => $value) { + echo "$name: $value\n"; + } + } + } + + + public function dailypageviewsAction() + { + $statistics = new Statistics_Model_GoalStatistics(); + $statistics->dailyPageviews(); + } + + + public function migrateAction() + { + $statistics = new Statistics_Model_GoalStatistics(); + $result = $statistics->migrateStatistics(); + + foreach (get_object_vars($result) as $name => $value) { + echo "$name: $value\n"; + } + } + +} diff --git a/application/modules/statistics/controllers/CronDailyController.php b/application/modules/statistics/controllers/CronDailyController.php new file mode 100644 index 000000000..b4b5346ea --- /dev/null +++ b/application/modules/statistics/controllers/CronDailyController.php @@ -0,0 +1,33 @@ +. + **/ +class Statistics_CronDailyController extends Local_Controller_Action_CliAbstract +{ + + public function runAction() + { + //20170505 Ronald: remove this for now, we do not use this table + //$stat = new Statistics_Model_Stat(); + //$stat->dailyPageviews(); + } + +} diff --git a/application/modules/statistics/controllers/DailyController.php b/application/modules/statistics/controllers/DailyController.php new file mode 100644 index 000000000..8fd2d3c82 --- /dev/null +++ b/application/modules/statistics/controllers/DailyController.php @@ -0,0 +1,93 @@ +. + **/ +class Statistics_DailyController extends Zend_Controller_Action +{ + + const PROJECT_ID = 'project_id'; + const YEAR = 'year'; + const MONTH = 'month'; + const DAY = 'day'; + + /** @var Statistics_Model_GoalStatistics */ + protected $tableStatistics; + /** @var Zend_Auth */ + protected $authorization; + /** @var Zend_Controller_Request_Abstract */ + protected $request; + /** @var mixed */ + protected $loginMemberId; + + public function init() + { + parent::init(); + + $this->tableStatistics = new Statistics_Model_GoalStatistics(); + $this->authorization = Zend_Auth::getInstance(); + $this->loginMemberId = + $this->authorization->hasIdentity() ? $this->authorization->getStorage()->read()->member_id : 0; + $this->request = $this->getRequest(); + } + + public function showAction() + { + $this->_helper->layout->disableLayout(); + } + + public function ajaxAction() + { + $this->_helper->layout->disableLayout(); + $this->_helper->viewRenderer->setNoRender(true); + + $identifier = $this->request->getParam(self::PROJECT_ID); + $year = $this->request->getParam(self::YEAR); + $month = $this->request->getParam(self::MONTH); + $day = $this->request->getParam(self::DAY); + + $resultSet = $this->tableStatistics->getDailyStatistics($identifier, $year, $month, $day); + + if (empty($resultSet)) { + $this->_helper->json(null); + } else { + $this->_helper->json($this->generateGoogleChartDataSet($resultSet)); + } + } + + /** + * @param array $dataSet + * + * @return array + */ + protected function generateGoogleChartDataSet($dataSet) + { + $rows = array(); + $rows[] = array('Key', 'Quantity'); + foreach ($dataSet as $value) { + foreach ($value as $key => $rowElement) { + $rows[] = array($key, (int)$rowElement); + } + } + + return $rows; + } + +} diff --git a/application/modules/statistics/controllers/DataController.php b/application/modules/statistics/controllers/DataController.php new file mode 100644 index 000000000..7d5100357 --- /dev/null +++ b/application/modules/statistics/controllers/DataController.php @@ -0,0 +1,214 @@ +. + * + * Created: 31.07.2017 + */ + +class Statistics_DataController extends Zend_Controller_Action +{ + + /** @var Zend_Config */ + protected $db_config; + + public function init() + { + $contextSwitch = $this->_helper->getHelper('contextSwitch'); + $contextSwitch->setDefaultContext('json'); + $this->db_config = Zend_Registry::get('config')->settings->dwh; + } + + public function projectAction() + { + $modelData = new Statistics_Model_Data($this->db_config->toArray()); + $id = (int) $this->getParam('p'); + try { + $result = $modelData->getProject($id); + } catch (Exception $e) { + Zend_Registry::get('logger')->error($e->getMessage()); + return $this->_helper->json->sendJson(array( + 'status' => 'error', + 'msg' => 'error while processing request', + 'data' => '' + )); + } + if ($result) { + $msg = array( + 'status' => 'ok', + 'msg' => '', + 'data' => $result + ); + return $this->_helper->json->sendJson($msg); + } + return $this->_helper->json->sendJson(array( + 'status' => 'not found', + 'msg' => 'data with given id could not be found.', + 'data' => '' + )); + } + + public function projectsAction() + { + /* + $modelData = new Statistics_Model_Data($this->db_config->toArray()); + $limit = (int) $this->getParam('l'); + try { + $result = $modelData->getProjects($limit); + } catch (Exception $e) { + Zend_Registry::get('logger')->error($e->getMessage()); + return $this->_helper->json->sendJson(array( + 'status' => 'error', + 'msg' => 'error while processing request', + 'data' => '' + )); + } + if ($result) { + $msg = array( + 'status' => 'ok', + 'msg' => '', + 'data' => $result + ); + return $this->_helper->json->sendJson($msg); + } + return $this->_helper->json->sendJson(array( + 'status' => 'not found', + 'msg' => 'data with given id could not be found.', + 'data' => '' + )); + */ + $result = array(); + $result[] = array('memberdate'=>'07-26', 'daycount'=>'88'); + $result[] = array('memberdate'=>'07-27', 'daycount'=>'84'); + $result[] = array('memberdate'=>'07-28', 'daycount'=>'101'); + $result[] = array('memberdate'=>'07-29', 'daycount'=>'96'); + $result[] = array('memberdate'=>'07-30', 'daycount'=>'66'); + $result[] = array('memberdate'=>'07-31', 'daycount'=>'110'); + $result[] = array('memberdate'=>'08-01', 'daycount'=>'90'); + $result[] = array('memberdate'=>'08-02', 'daycount'=>'81'); + $result[] = array('memberdate'=>'08-03', 'daycount'=>'81'); + $result[] = array('memberdate'=>'08-04', 'daycount'=>'85'); + $result[] = array('memberdate'=>'08-05', 'daycount'=>'72'); + $result[] = array('memberdate'=>'08-06', 'daycount'=>'61'); + $result[] = array('memberdate'=>'08-07', 'daycount'=>'64'); + $result[] = array('memberdate'=>'08-08', 'daycount'=>'84'); + $result[] = array('memberdate'=>'08-09', 'daycount'=>'81'); + $result[] = array('memberdate'=>'08-10', 'daycount'=>'86'); + $result[] = array('memberdate'=>'08-11', 'daycount'=>'86'); + $result[] = array('memberdate'=>'08-12', 'daycount'=>'82'); + $result[] = array('memberdate'=>'08-13', 'daycount'=>'64'); + + return $this->_helper->json->sendJson($result); + } + + public function memberAction() + { + $result = array(); + $result[] = array("projectdate"=>"July 26th","daycount"=>"29"); + $result[] = array("projectdate"=>"July 27th","daycount"=>"34"); + $result[] = array("projectdate"=>"July 28th","daycount"=>"32"); + $result[] = array("projectdate"=>"July 29th","daycount"=>"26"); + $result[] = array("projectdate"=>"July 30th","daycount"=>"13"); + $result[] = array("projectdate"=>"July 31st","daycount"=>"33"); + $result[] = array("projectdate"=>"August 1st","daycount"=>"25"); + $result[] = array("projectdate"=>"August 2nd","daycount"=>"30"); + $result[] = array("projectdate"=>"August 3rd","daycount"=>"31"); + $result[] = array("projectdate"=>"August 4th","daycount"=>"31"); + $result[] = array("projectdate"=>"August 5th","daycount"=>"22"); + $result[] = array("projectdate"=>"August 6th","daycount"=>"12"); + $result[] = array("projectdate"=>"August 7th","daycount"=>"13"); + $result[] = array("projectdate"=>"August 8th","daycount"=>"35"); + $result[] = array("projectdate"=>"August 9th","daycount"=>"31"); + $result[] = array("projectdate"=>"August 10th","daycount"=>"25"); + $result[] = array("projectdate"=>"August 11th","daycount"=>"43"); + $result[] = array("projectdate"=>"August 12th","daycount"=>"26"); + $result[] = array("projectdate"=>"August 13th","daycount"=>"15"); + + return $this->_helper->json->sendJson($result); + + /* + $modelData = new Statistics_Model_Data($this->db_config->toArray()); + $id = (int) $this->getParam('m'); + try { + $result = $modelData->getMember($id); + } catch (Exception $e) { + Zend_Registry::get('logger')->error($e->getMessage()); + return $this->_helper->json->sendJson(array( + 'status' => 'error', + 'msg' => 'error while processing request', + 'data' => '' + )); + } + if ($result) { + $msg = array( + 'status' => 'ok', + 'msg' => '', + 'data' => $result + ); + return $this->_helper->json->sendJson($msg); + } + return $this->_helper->json->sendJson(array( + 'status' => 'not found', + 'msg' => 'data with given id could not be found.', + 'data' => '' + )); + */ + } + + public function membersAction() + { + $modelData = new Statistics_Model_Data($this->db_config->toArray()); + $limit = (int) $this->getParam('l'); + try { + $result = $modelData->getMembers($limit); + } catch (Exception $e) { + Zend_Registry::get('logger')->error($e->getMessage()); + return $this->_helper->json->sendJson(array( + 'status' => 'error', + 'msg' => 'error while processing request', + 'data' => '' + )); + } + if ($result) { + $msg = array( + 'status' => 'ok', + 'msg' => '', + 'data' => $result + ); + return $this->_helper->json->sendJson($msg); + } + return $this->_helper->json->sendJson(array( + 'status' => 'not found', + 'msg' => 'data with given id could not be found.', + 'data' => '' + )); + } + + public function newprojectsstatAction() + { + // last two year for example + $result=array(100,200,50,60,80,70,100,200,50,60,80,70); + $msg = array( + 'status' => 'ok', + 'msg' => '', + 'data' => $result + ); + return $this->_helper->json->sendJson($msg); + } +} \ No newline at end of file diff --git a/application/modules/statistics/controllers/MonthlyController.php b/application/modules/statistics/controllers/MonthlyController.php new file mode 100644 index 000000000..0828da3ed --- /dev/null +++ b/application/modules/statistics/controllers/MonthlyController.php @@ -0,0 +1,94 @@ +. + **/ +class Statistics_MonthlyController extends Zend_Controller_Action +{ + + const PROJECT_ID = 'project_id'; + const YEAR = 'year'; + const MONTH = 'month'; + const DAY = 'day'; + + /** @var Statistics_Model_GoalStatistics */ + protected $tableStatistics; + /** @var Zend_Auth */ + protected $authorization; + /** @var Zend_Controller_Request_Abstract */ + protected $request; + /** @var mixed */ + protected $loginMemberId; + + public function init() + { + parent::init(); + + $this->tableStatistics = new Statistics_Model_GoalStatistics(); + $this->authorization = Zend_Auth::getInstance(); + $this->loginMemberId = + $this->authorization->hasIdentity() ? $this->authorization->getStorage()->read()->member_id : 0; + $this->request = $this->getRequest(); + } + + public function showAction() + { + $this->_helper->layout->disableLayout(); + } + + public function ajaxAction() + { + $this->_helper->layout->disableLayout(); + $this->_helper->viewRenderer->setNoRender(true); + + $identifier = $this->request->getParam(self::PROJECT_ID); + $year = $this->request->getParam(self::YEAR); + $month = $this->request->getParam(self::MONTH); + + $resultSet = $this->tableStatistics->getMonthlyStatistics($identifier, $year, $month); + + if (empty($resultSet)) { + $this->_helper->json(null); + } else { + $this->_helper->json($this->generateGoogleChartDataSet($resultSet)); + } + } + + /** + * @param array $dataSet + * + * @return array + */ + protected function generateGoogleChartDataSet($dataSet) + { + $rows = array(); + $rows[] = array_keys($dataSet[0]); + foreach ($dataSet as $value) { + $row = array(); + foreach ($value as $key => $rowElement) { + $row[] = (int)$rowElement; + } + $rows[] = $row; + } + + return $rows; + } + +} diff --git a/application/modules/statistics/controllers/WeeklyController.php b/application/modules/statistics/controllers/WeeklyController.php new file mode 100644 index 000000000..7eafd9637 --- /dev/null +++ b/application/modules/statistics/controllers/WeeklyController.php @@ -0,0 +1,94 @@ +. + **/ +class Statistics_WeeklyController extends Zend_Controller_Action +{ + + const PROJECT_ID = 'project_id'; + const YEAR = 'year'; + const MONTH = 'month'; + const DAY = 'day'; + const YEARWEEK = 'yearweek'; + + /** @var Statistics_Model_GoalStatistics */ + protected $tableStatistics; + /** @var Zend_Auth */ + protected $authorization; + /** @var Zend_Controller_Request_Abstract */ + protected $request; + /** @var mixed */ + protected $loginMemberId; + + public function init() + { + parent::init(); + + $this->tableStatistics = new Statistics_Model_GoalStatistics(); + $this->authorization = Zend_Auth::getInstance(); + $this->loginMemberId = + $this->authorization->hasIdentity() ? $this->authorization->getStorage()->read()->member_id : 0; + $this->request = $this->getRequest(); + } + + public function showAction() + { + $this->_helper->layout->disableLayout(); + } + + public function ajaxAction() + { + $this->_helper->layout->disableLayout(); + $this->_helper->viewRenderer->setNoRender(true); + + $identifier = $this->request->getParam(self::PROJECT_ID); + $yearWeek = $this->request->getParam(self::YEARWEEK); + + $resultSet = $this->tableStatistics->getWeeklyStatistics($identifier, $yearWeek); + + if (empty($resultSet)) { + $this->_helper->json(null); + } else { + $this->_helper->json($this->generateGoogleChartDataSet($resultSet)); + } + } + + /** + * @param array $dataSet + * + * @return array + */ + protected function generateGoogleChartDataSet($dataSet) + { + $rows = array(); + $rows[] = array_keys($dataSet[0]); + foreach ($dataSet as $value) { + $row = array(); + foreach ($value as $key => $rowElement) { + $row[] = (int)$rowElement; + } + $rows[] = $row; + } + + return $rows; + } + +} diff --git a/application/modules/statistics/library/statistics/ranking/RankingInterface.php b/application/modules/statistics/library/statistics/ranking/RankingInterface.php new file mode 100644 index 000000000..1d6a3634a --- /dev/null +++ b/application/modules/statistics/library/statistics/ranking/RankingInterface.php @@ -0,0 +1,31 @@ +. + **/ +interface Statistics_Ranking_RankingInterface +{ + + /** + * @param $data + * @return mixed + */ + public function calculateRankingValue($data); + +} diff --git a/application/modules/statistics/library/statistics/ranking/WeightedAverageRanking.php b/application/modules/statistics/library/statistics/ranking/WeightedAverageRanking.php new file mode 100644 index 000000000..d717ed775 --- /dev/null +++ b/application/modules/statistics/library/statistics/ranking/WeightedAverageRanking.php @@ -0,0 +1,57 @@ +. + **/ +class Statistics_Ranking_WeightedAverageRanking implements Statistics_Ranking_RankingInterface +{ + + protected $weightForKeys; + + + function __construct() + { + $this->weightForKeys = array( + 'count_views' => 0.1, + 'count_plings' => 5, + 'count_updates' => 1, + 'count_comments' => 1, + 'count_followers' => 0, + 'count_supporters' => 0, + 'count_money' => 0 + ); + } + + /** + * @param $data + * @return float + */ + public function calculateRankingValue($data) + { + $weightedSum = 0.0; + $dividerSum = 0.0; + + foreach ($this->weightForKeys as $key => $weight) { + $weightedSum += $weight * (float)$data[$key]; + $dividerSum += $weight; + } + return $weightedSum / $dividerSum; + } + +} diff --git a/application/modules/statistics/models/Data.php b/application/modules/statistics/models/Data.php new file mode 100644 index 000000000..1a8419ecb --- /dev/null +++ b/application/modules/statistics/models/Data.php @@ -0,0 +1,620 @@ +. + * + * Created: 31.07.2017 + */ + +class Statistics_Model_Data +{ + + const DEFAULT_STORE_ID = 22; //opendesktop + + /** @var Zend_Db_Adapter_Pdo_Abstract */ + protected $_db; + + public function __construct($options) { + if (isset($options['db'])) { + $this->initDbAdapter($options['db']); + } else { + throw new Exception('configuration parameter for database connection needed'); + } + } + + private function initDbAdapter($db) + { + $adapter = $db['adapter']; + $params = $db['params']; + //$default = (int)(isset($params['isDefaultTableAdapter']) && $params['isDefaultTableAdapter'] + // || isset($params['default']) && $params['default']); + unset($params['adapter'], $params['default'], $params['isDefaultTableAdapter']); + $adapter = Zend_Db::factory($adapter, $params); + $this->_db = $adapter; + } + + public function getNewmemberstats(){ + $sql = "SELECT DATE(`created_at`) as memberdate , count(*) as daycount FROM dwh.ods_member_v group by memberdate order by memberdate desc limit 30"; + $result = $this->_db->fetchAll($sql); + return $result; + } + + public function getNewprojectstats(){ + $sql = "SELECT DATE(`created_at`) as projectdate , count(*) as daycount FROM dwh.ods_project_v where status>=40 group by projectdate order by projectdate desc limit 30"; + $result = $this->_db->fetchAll($sql); + return $result; + } + + public function getNewprojectWeeklystats(){ + $sql = "SELECT YEARWEEK(`created_at`) as yyyykw , count(*) as amount + FROM project p + join stat_cat_tree t on p.project_category_id = t.project_category_id + where status=100 and type_id = 1 + group by yyyykw + order by yyyykw + desc limit 60"; + $result = $this->_db->fetchAll($sql); + return $result; + } + public function getNewprojectWeeklystatsWithoutWallpapers(){ + $sql = "SELECT YEARWEEK(`created_at`) as yyyykw , count(*) as amount + FROM project p + join stat_cat_tree t on p.project_category_id = t.project_category_id + where status=100 and type_id = 1 + and (t.lft<899 or t.rgt>988) + group by yyyykw + order by yyyykw + desc limit 60"; + $result = $this->_db->fetchAll($sql); + return $result; + } + + public function getNewprojectWeeklystatsWallpapers(){ + $sql = "SELECT YEARWEEK(`created_at`) as yyyykw , count(*) as amount + FROM project p + join stat_cat_tree t on p.project_category_id = t.project_category_id + where status=100 and type_id = 1 + and (t.lft>899 and t.rgt<988) + group by yyyykw + order by yyyykw + desc limit 60"; + $result = $this->_db->fetchAll($sql); + return $result; + } + + public function getPayout($yyyymm){ + + $sql = "SELECT * , + (select username from member m where m.member_id = p.member_id) username + FROM dwh.member_payout p where yearmonth = :yyyymm order by amount desc"; + $result = $this->_db->fetchAll($sql, array("yyyymm"=>$yyyymm)); + return $result; + } + + public function getPayoutMemberPerCategory($yyyymm,$catid){ + + $modelProjectCategories = new Default_Model_DbTable_ProjectCategory(); + $ids = $modelProjectCategories->fetchChildIds($catid); + array_push($ids, $catid); + $idstring = implode(',', $ids); + + $sql = " + select * from + ( + select + member_id + ,(select username from member m where m.member_id = v.member_id) username + ,round(sum(probably_payout_amount)) as amount + from member_dl_plings_v as v + where project_category_id IN (".$idstring.") and v.yearmonth= :yyyymm + group by v.member_id + order by amount desc + ) tmp where amount>0 + "; + $result = $this->_db->fetchAll($sql, array("yyyymm"=>$yyyymm)); + return $result; + } + + public function getNewcomer($yyyymm){ + $yyyymm_vor = $this->getLastYearMonth($yyyymm); + $sql = "SELECT member_id + , (select username from member m where m.member_id = member_payout.member_id) as username + , paypal_mail,round(amount,2) as amount FROM member_payout WHERE yearmonth =:yyyymm + and member_id not in (select member_id from member_payout where yearmonth =:yyyymm_vor) + order by amount desc + "; + $result = $this->_db->fetchAll($sql, array("yyyymm"=>$yyyymm, "yyyymm_vor"=>$yyyymm_vor)); + return $result; + } + + public function getNewloser($yyyymm){ + $yyyymm_vor = $this->getLastYearMonth($yyyymm); + $sql = "SELECT member_id + , (select username from member m where m.member_id = member_payout.member_id) as username + , paypal_mail,round(amount,2) as amount FROM member_payout WHERE yearmonth =:yyyymm_vor + and member_id not in (select member_id from member_payout where yearmonth =:yyyymm) + order by amount desc + "; + $result = $this->_db->fetchAll($sql, array("yyyymm"=>$yyyymm, "yyyymm_vor"=>$yyyymm_vor)); + return $result; + } + + public function getMonthDiff($yyyymm){ + $yyyymm_vor = $this->getLastYearMonth($yyyymm); + $sql = " + select akt.member_id + , (select username from member m where m.member_id = akt.member_id) as username + , akt.amount as am_akt + , let.amount as am_let + , round(akt.amount-let.amount) as am_diff + , akt.yearmonth ym_akt + , let.yearmonth ym_let + from + (select member_id, amount,yearmonth from member_payout where yearmonth = :yyyymm) akt, + (select member_id, amount,yearmonth from member_payout where yearmonth = :yyyymm_vor) let + where akt.member_id = let.member_id + order by am_diff desc + "; + $result = $this->_db->fetchAll($sql, array("yyyymm"=>$yyyymm, "yyyymm_vor"=>$yyyymm_vor)); + + return $result; + } + +/* + public function getDownloadsDaily($numofmonthback){ + $sql = " + select + SUBSTR(d.date_yyyymmdd,1,6) as symbol + ,SUBSTR(d.date_yyyymmdd,7,8)*1 as date + ,d.count as price + from dwh.files_downloads_daily as d + where STR_TO_DATE(date_yyyymmdd,'%Y%m%d' ) >= (DATE_FORMAT(CURDATE(), '%Y-%m-01')- INTERVAL :numofmonthback MONTH) + and STR_TO_DATE(date_yyyymmdd,'%Y%m%d' )< CURDATE() + order by date_yyyymmdd asc + "; + $result = $this->_db->fetchAll($sql,array("numofmonthback"=>$numofmonthback)); + return $result; + } +*/ + + public function getDownloadsDaily($numofmonthback){ + $sql = " + select + SUBSTR(d.date_yyyymmdd,1,6) as symbol + ,SUBSTR(d.date_yyyymmdd,7,8)*1 as date + ,d.count as price + from dwh.files_downloads_daily as d + where STR_TO_DATE(date_yyyymmdd,'%Y%m%d' ) >= (DATE_FORMAT(CURDATE(), '%Y-%m-01')- INTERVAL :numofmonthback MONTH) + and STR_TO_DATE(date_yyyymmdd,'%Y%m%d' )< CURDATE() + union + + select + concat(SUBSTR(d.date_yyyymmdd,1,6),' payout') as symbol + ,SUBSTR(d.date_yyyymmdd,7,8)*1 as date + ,d.count as price + from dwh.payout_daily as d + where STR_TO_DATE(date_yyyymmdd,'%Y%m%d' ) >= (DATE_FORMAT(CURDATE(), '%Y-%m-01')- INTERVAL :numofmonthback MONTH) + and STR_TO_DATE(date_yyyymmdd,'%Y%m%d' )< CURDATE() + + "; + $result = $this->_db->fetchAll($sql,array("numofmonthback"=>$numofmonthback)); + return $result; + } + + public function getDownloadsUndPayoutsDaily($yyyymm){ + $sql = " + select + concat(SUBSTR(d.date_yyyymmdd,1,6),' downloads') as symbol + ,SUBSTR(d.date_yyyymmdd,7,8)*1 as date + ,d.count as price + from dwh.files_downloads_daily as d + where SUBSTR(d.date_yyyymmdd,1,6)=:yyyymm + union + select + concat(SUBSTR(d.date_yyyymmdd,1,6),' payouts') as symbol + ,SUBSTR(d.date_yyyymmdd,7,8)*1 as date + ,d.count as price + from dwh.payout_daily as d + where SUBSTR(d.date_yyyymmdd,1,6)=:yyyymm + + "; + $result = $this->_db->fetchAll($sql,array("yyyymm"=>$yyyymm)); + return $result; + } + + +/** + ,(select count(1) from dwh.files_downloads dd where dd.project_id = d.project_id + and dd.downloaded_timestamp between :date_start and :date_end + and dd.referer like 'https://www.google%') as cntGoogle +*/ + + public function getTopDownloadsPerDate($date){ + $date_start =$date.' 00:00:00'; + $date_end =$date.' 23:59:59'; + $sql = " + select d.project_id + , count(1) as cnt + ,(select p.title from project p where p.project_id = d.project_id) as ptitle + ,(select p.created_at from project p where p.project_id = d.project_id) as pcreated_at + ,(select c.title from category c, project p where p.project_id = d.project_id and p.project_category_id=c.project_category_id) as ctitle + ,(select username from member m , project p where m.member_id = p.member_id and p.project_id = d.project_id) as username + from dwh.files_downloads d + where d.downloaded_timestamp between :date_start and :date_end + group by d.project_id + order by cnt desc + limit 50 + "; + + $result = $this->_db->fetchAll($sql,array("date_start"=>$date_start,"date_end"=>$date_end)); + return $result; + } + + public function getTopDownloadsPerMonth($month,$catid){ + + $sd = $month.'-01'; + $date_start =date('Y-m-01', strtotime($sd)).' 00:00:00'; + $date_end =date('Y-m-t', strtotime($sd)).' 23:59:59'; + + if($catid==0) + { + + // $sql = " + // select d.project_id + // , count(1) as cnt + // ,(select p.title from project p where p.project_id = d.project_id) as ptitle + // ,(select p.created_at from project p where p.project_id = d.project_id) as pcreated_at + // ,(select c.title from category c where d.project_category_id=c.project_category_id) as ctitle + // ,(select username from member m where m.member_id = d.member_id) as username + // from dwh.files_downloads d + // where d.yyyymm = :month + // group by d.project_id,project_category_id,member_id + // order by cnt desc + // limit 50 + // "; + $sql = "select d.project_id + , sum(d.count) as cnt + ,p.title as ptitle + ,p.created_at as pcreated_at + ,(select c.title from category c where d.project_category_id=c.project_category_id) as ctitle + ,(select username from member m where m.member_id = p.member_id) as username + from dwh.files_downloads_project_daily d + join project p on d.project_id = p.project_id + where d.yyyymm = :month + group by d.project_id,d.project_category_id,p.member_id + order by cnt desc + limit 50"; + + }else + { + $modelProjectCategories = new Default_Model_DbTable_ProjectCategory(); + $ids = $modelProjectCategories->fetchChildIds($catid); + array_push($ids, $catid); + $idstring = implode(',', $ids); + // $sql = ' + // select d.project_id + // , count(1) as cnt + // ,(select p.title from project p where p.project_id = d.project_id) as ptitle + // ,(select p.created_at from project p where p.project_id = d.project_id) as pcreated_at + // ,(select c.title from category c where d.project_category_id=c.project_category_id) as ctitle + // ,(select username from member m where m.member_id = d.member_id) as username + // from dwh.files_downloads d + // where d.yyyymm = :month + // and d.project_category_id in ('.$idstring.') + // group by d.project_id,project_category_id,member_id + // order by cnt desc + // limit 50 + // '; + $sql = 'select d.project_id + , sum(d.count) as cnt + ,p.title as ptitle + ,p.created_at as pcreated_at + ,(select c.title from category c where d.project_category_id=c.project_category_id) as ctitle + ,(select username from member m where m.member_id = p.member_id) as username + from dwh.files_downloads_project_daily d + join project p on d.project_id = p.project_id + where d.yyyymm = :month + and d.project_category_id in ('.$idstring.') + group by d.project_id,d.project_category_id,p.member_id + order by cnt desc + limit 50'; + } + + $result = $this->_db->fetchAll($sql,array("month"=>$month)); + return $result; + } + + public function getProductMonthly($project_id) + { + $sql = " + select + yyyymm as yearmonth + ,sum(count) as amount + from dwh.files_downloads_project_daily + where project_id = :project_id + group by yyyymm + limit 100 + "; + $result = $this->_db->fetchAll($sql,array("project_id"=>$project_id)); + return $result; + } + + public function getProductDayly($project_id) + { + $sql = " + select yyyymmdd as yearmonth,count as amount + from dwh.files_downloads_project_daily + where project_id = :project_id + order by yyyymmdd desc + limit 1000 + "; + $result = $this->_db->fetchAll($sql,array("project_id"=>$project_id)); + return array_reverse($result); + } + + + public function getDownloadsDomainStati($begin, $end){ + $date_start =$begin.' 00:00:00'; + $date_end =$end.' 23:59:59'; + $sql = " + select count(1) as cnt + ,d.referer_domain + ,is_from_own_domain + from dwh.files_downloads d + where d.downloaded_timestamp between :date_start and :date_end + group by d.referer_domain,is_from_own_domain + order by is_from_own_domain desc, cnt desc + "; + $result = $this->_db->fetchAll($sql,array("date_start"=>$date_start,"date_end"=>$date_end)); + return $result; + } + + + public function getPayoutCategoryMonthly($yyyymm){ + $sql = " + select * from + ( + select project_category_id + ,(select title from category as c where c.project_category_id = v.project_category_id) as title + ,round(sum(probably_payout_amount)) as amount + ,sum(v.num_downloads) as num_downloads + from member_dl_plings_v as v + where yearmonth =:yyyymm + group by v.project_category_id + order by amount desc + ) tmp where amount>0 + "; + $result = $this->_db->fetchAll($sql, array("yyyymm"=>$yyyymm)); + return $result; + } + + + + private function getPayoutCategorySingle($catid) + { + + $modelProjectCategories = new Default_Model_DbTable_ProjectCategory(); + $ids = $modelProjectCategories->fetchChildIds($catid); + array_push($ids, $catid); + $idstring = implode(',', $ids); + // Zend_Registry::get('logger')->info(__METHOD__ . ' - ===================================' ); + // Zend_Registry::get('logger')->info(__METHOD__ . ' - ' . $idstring); + $sql = " + select * from + ( + select + yearmonth + ,(select title from category as c where c.project_category_id = ".$catid.") as symbol + ,round(sum(probably_payout_amount)) as amount + from member_dl_plings_v as v + where project_category_id IN (".$idstring.") + group by v.yearmonth + order by yearmonth asc + ) tmp where amount>0 + "; + $result = $this->_db->fetchAll($sql); + return $result; + } + + public function getPayoutCategory_($catid){ + + if($catid==0) + { + $pids = array(152, 233,158, 148,491,445,295); + $sql = " + select * from + ( + select + 'All' as symbol + ,yearmonth + ,round(sum(probably_payout_amount)) as amount + from member_dl_plings_v as v + group by v.yearmonth + order by yearmonth asc + ) tmp where amount>0 + "; + $result = $this->_db->fetchAll($sql); + foreach ($pids as $catid) { + $t = self::getPayoutCategorySingle($catid); + $result = array_merge($result, $t); + } + } + else + { + $result = self::getPayoutCategorySingle($catid); + } + + return $result; + + } + + public function getPayoutCategory($catid){ + + if($catid==0) + { + // $pids = array(152, 233,158,404, 148,491,445,295); + $modelCategoryStore = new Default_Model_DbTable_ConfigStoreCategory(); + $pids = $modelCategoryStore->fetchCatIdsForStore(self::DEFAULT_STORE_ID); + $sql = " + select * from + ( + select + 'All' as symbol + ,yearmonth + ,round(sum(probably_payout_amount)) as amount + from member_dl_plings_v as v + group by v.yearmonth + order by yearmonth asc + ) tmp where amount>0 + "; + $result = $this->_db->fetchAll($sql); + foreach ($pids as $c) { + $tmp = self::getPayoutCategorySingle($c); + foreach ($result as &$row) { + $row['amount'.$c] = 0; + foreach ($tmp as $t) { + if($t['yearmonth']==$row['yearmonth']) + { + $row['amount'.$c] = $t['amount']; + break; + } + } + } + } + } + else + { + $result = self::getPayoutCategorySingle($catid); + $modelCategoriesTable = new Default_Model_DbTable_ProjectCategory(); + $pids = $modelCategoriesTable->fetchImmediateChildrenIds($catid); + foreach ($pids as $c) { + $tmp = self::getPayoutCategorySingle($c); + foreach ($result as &$row) { + $row['amount'.$c] = 0; + foreach ($tmp as $t) { + if($t['yearmonth']==$row['yearmonth']) + { + $row['amount'.$c] = $t['amount']; + break; + } + } + } + } + } + + return $result; + + } + + public function _getPayoutCategory($catid){ + + if($catid==0) + { + $pids = array(152, 233,158,404, 148,491,445,295); + $sql = " + select * from + ( + select + 'All' as symbol + ,yearmonth + ,round(sum(probably_payout_amount)) as amount + from member_dl_plings_v as v + group by v.yearmonth + order by yearmonth asc + ) tmp where amount>0 + "; + $result = $this->_db->fetchAll($sql); + foreach ($pids as $c) { + $tmp = self::getPayoutCategorySingle($c); + foreach ($result as &$row) { + $row['amount'.$c] = 0; + foreach ($tmp as $t) { + if($t['yearmonth']==$row['yearmonth']) + { + $row['amount'.$c] = $t['amount']; + break; + } + } + } + } + } + else + { + $result = self::getPayoutCategorySingle($catid); + } + + return $result; + + } + + + public function getLastYearMonth($yyyymm){ + $aktdate = strval($yyyymm).'01'; + $fmt = 'Ymd'; + $d = DateTime::createFromFormat($fmt, $aktdate); + $d->modify( 'last day of previous month' ); + return $d->format( 'Ym' ); + } + + public function getPayoutyear(){ + $sql = "select round(sum(amount)) amount,yearmonth from dwh.member_payout group by yearmonth order by yearmonth"; + $result = $this->_db->fetchAll($sql); + return $result; + } + + + public function getPayoutOfMember($member_id){ + //$sql = "select yearmonth, amount from dwh.member_payout where member_id = :member_id order by yearmonth asc"; + $sql = "select yearmonth, amount from dwh.member_payout where member_id = :member_id order by yearmonth asc"; + $result = $this->_db->fetchAll($sql, array("member_id"=>$member_id)); + return $result; + } + + public function getProject($project_id) + { + $sql = "SELECT * FROM ods_project_v WHERE project_id = :projectId"; + $result = $this->_db->fetchAll($sql, array('projectId' => $project_id)); + return $result; + } + + public function getProjects($limit = 50) + { + $limit = (int)$limit; + $sql = "SELECT * FROM ods_project_v LIMIT {$limit}"; + $result = $this->_db->fetchAll($sql); + return $result; + } + + public function getMember($member_id) + { + $sql = "SELECT * FROM ods_member_v WHERE member_id = :memberId"; + $result = $this->_db->fetchAll($sql, array('memberId' => (int)$member_id)); + return $result; + } + + + public function getMembers($limit = 50) + { + $sql = "SELECT * FROM ods_member_v"; + $sql = $this->_db->limit($sql, (int)$limit); + $result = $this->_db->fetchAll($sql); + return $result; + } + +} \ No newline at end of file diff --git a/application/modules/statistics/models/DbTable/StatDaily.php b/application/modules/statistics/models/DbTable/StatDaily.php new file mode 100644 index 000000000..f0b07680b --- /dev/null +++ b/application/modules/statistics/models/DbTable/StatDaily.php @@ -0,0 +1,77 @@ +. + **/ +class Statistics_Model_DbTable_StatDaily extends Zend_Db_Table_Abstract +{ + + /** + * The primary key column or columns. + * A compound key should be declared as an array. + * You may declare a single-column primary key + * as a string. + * + * @var mixed + */ + protected $_primary = 'daily_id'; + + /** + * The table name. + * + * @var string + */ + protected $_name = 'stat_daily'; + + protected $_keyColumnsForRow = array('project_id', 'project_category_id', 'project_type_id', 'year', 'month', 'day'); + + + /** + * @param $data + */ + public function save($data) + { + $rowSet = $this->findForColumns($data, $this->_keyColumnsForRow); + + if (null === $rowSet) { + $rowSet = $this->createRow($data); + } else { + $rowSet->setFromArray($data); + } + + $rowSet->save(); + } + + /** + * @param $data + * @param $columns + * @return null|Zend_Db_Table_Row_Abstract + */ + public function findForColumns($data, $columns) + { + + $statement = $this->select()->setIntegrityCheck(false)->from($this->_name); + foreach ($columns as $identifier) { + $statement->where($this->_db->quoteIdentifier($identifier) . ' = ?', $data[$identifier]); + } + + return $this->fetchRow($statement); + } + +} diff --git a/application/modules/statistics/models/GoalStatistics.php b/application/modules/statistics/models/GoalStatistics.php new file mode 100644 index 000000000..b8c55b334 --- /dev/null +++ b/application/modules/statistics/models/GoalStatistics.php @@ -0,0 +1,323 @@ +. + **/ +class Statistics_Model_GoalStatistics +{ + + const MYSQL_DATE_FORMAT = "Y-m-d H:i:s"; + const DEFAULT_RANKING_PLUGIN = 'Statistics_Ranking_WeightedAverageRanking'; + + /** @var Statistics_Ranking_RankingInterface */ + protected $_rankingPlugin; + + + /** + * @param Statistics_Ranking_RankingInterface $rankingPlugin + */ + function __construct(Statistics_Ranking_RankingInterface $rankingPlugin = null) + { + if (is_null($rankingPlugin)) { + $default = self::DEFAULT_RANKING_PLUGIN; + $this->_rankingPlugin = new $default; + return $this; + } + $this->_rankingPlugin = $rankingPlugin; + } + + public function setupDatabase() + { + exit(0); + + $sql = " + CREATE TABLE `stat_daily` ( + `daily_id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', + `project_id` INT(11) NOT NULL COMMENT 'ID of the project', + `project_category_id` INT(11) DEFAULT '0' COMMENT 'Category', + `project_type` INT(11) NOT NULL COMMENT 'type of the project', + `count_views` INT(11) DEFAULT '0', + `count_plings` INT(11) DEFAULT '0', + `count_updates` INT(11) DEFAULT NULL, + `count_comments` INT(11) DEFAULT NULL, + `count_followers` INT(11) DEFAULT NULL, + `count_supporters` INT(11) DEFAULT NULL, + `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `year` INT(11) DEFAULT NULL COMMENT 'z.B.: 1988', + `month` INT(11) DEFAULT NULL COMMENT 'z.b: 1-12', + `day` INT(11) DEFAULT NULL COMMENT 'z.B. 1-31', + `year_week` INT(11) DEFAULT NULL COMMENT 'z.b.: 201232', + PRIMARY KEY (`daily_id`) + ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='Store daily statistic'; + + CREATE TABLE `app_config` ( + `config_id` INT(11) NOT NULL AUTO_INCREMENT, + `group` VARCHAR(20) NOT NULL, + `name` VARCHAR(20) NOT NULL, + `value` VARCHAR(20) NOT NULL, + PRIMARY KEY (`config_id`), + KEY `index_group` (`group`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Store config for statistic'; + "; + + $sql_alter = " + ALTER TABLE pling.stat_daily + ADD ranking_value INT AFTER year_week; + ALTER TABLE pling.stat_daily + ADD count_money FLOAT AFTER count_supporters; + ALTER TABLE pling.stat_daily + CHANGE ranking_value ranking_value FLOAT; + ALTER TABLE pling.stat_daily + CHANGE project_type project_type_id INT(11) NOT NULL COMMENT 'type of the project'; + "; + + $database = Zend_Db_Table::getDefaultAdapter(); + $database->query($sql)->execute(); + $database->query($sql_alter)->execute(); + } + + public function dailyPageviews() + { + $sql = ' + insert into stat_daily_pageviews + select project_id + ,count(project_id) cnt + ,(select p.project_category_id from project p where v.project_id = p.project_id) project_category_id + ,CURDATE() created_at + from stat_page_views v where v.created_at > date_sub(CURDATE(), interval 6 month) + group by project_id + '; + $database = Zend_Db_Table::getDefaultAdapter(); + $database->query($sql)->execute(); + } + + public function migrateStatistics() + { + $database = Zend_Db_Table::getDefaultAdapter(); + + $sqlTruncate = "TRUNCATE stat_daily"; + $result = $database->query($sqlTruncate); + + + $sql = " + SELECT DATE_FORMAT(stat_page_views.created_at,\"%d.%m.%Y\") AS stat_date + FROM pling.stat_page_views stat_page_views + GROUP BY stat_date + ORDER BY created_at ASC; + "; + + $queryObject = $database->query($sql); + $resultSet = $queryObject->fetchAll(); + + $addedRows = 0; + $resultMessage = new stdClass(); + + if (count($resultSet) > 0) { + foreach ($resultSet as $element) { + $resultMessage = $this->generateDailyStatistics($element['stat_date']); + if ($resultMessage->result === false) { + break; + } + $addedRows += $resultMessage->AffectedRows; + } + + } + + $resultMessage->AffectedRows = $addedRows; + $resultMessage->Environment = APPLICATION_ENV; + + return $resultMessage; + } + + /** + * @param string|null $forDate + * @return stdClass + */ + public function generateDailyStatistics($forDate = null) + { + $database = Zend_Db_Table::getDefaultAdapter(); + + $dateCreatedAt = new DateTime(); + $mysqlCreatedAt = $dateCreatedAt->format(self::MYSQL_DATE_FORMAT); + + if (is_null($forDate)) { + $generateForDateObject = new DateTime(); + } else { + $generateForDateObject = new DateTime($forDate); + } + + $generateForDateObject->setTime(0, 0, 0); + $mysqlStartDate = $generateForDateObject->format(self::MYSQL_DATE_FORMAT); + + $generateForDateObject->setTime(23, 59, 59); + $mysqlEndDate = $generateForDateObject->format(self::MYSQL_DATE_FORMAT); + + $sql = " + select + prj.project_id, + prj.type_id as project_type_id, + prj.project_category_id, + (select count(1) from stat_page_views pv where pv.project_id = prj.project_id and pv.created_at between '{$mysqlStartDate}' and '{$mysqlEndDate}' group by pv.project_id) AS count_views, + (select count(1) from plings p where p.project_id = prj.project_id and p.pling_time between '{$mysqlStartDate}' and '{$mysqlEndDate}' AND p.status_id in (2,3,4) group by p.project_id) AS count_plings, + (select count(1) from project pu where pu.pid = prj.project_id and (pu.created_at between '{$mysqlStartDate}' and '{$mysqlEndDate}') and pu.type_id = 2 group by pu.pid) AS count_updates, + (select count(1) from project_follower pf where pf.project_id = prj.project_id) AS count_followers, + (SELECT count(1) FROM plings WHERE status_id >= 2 AND create_time BETWEEN '{$mysqlStartDate}' AND '{$mysqlEndDate}' AND project_id = prj.project_id AND comment is not null GROUP BY project_id) AS count_comments, + (SELECT count(member_id) FROM (SELECT member_id, project_id FROM plings WHERE status_id >= 2 AND create_time BETWEEN '{$mysqlStartDate}' AND '{$mysqlEndDate}' GROUP BY member_id, project_id) AS tempCountProjectSupporter WHERE project_id = prj.project_id) AS count_supporters, + (SELECT sum(amount) FROM plings WHERE status_id >= 2 AND create_time BETWEEN '{$mysqlStartDate}' AND '{$mysqlEndDate}' AND project_id = prj.project_id GROUP BY project_id) AS count_money, + '" . $mysqlCreatedAt . "' AS created_at, + DATE_FORMAT('{$mysqlStartDate}', '%Y') AS year, + DATE_FORMAT('{$mysqlStartDate}', '%m') AS month, + DATE_FORMAT('{$mysqlStartDate}', '%d') AS day, + YEARWEEK('{$mysqlStartDate}',1) AS year_week + from + project as prj + where + prj.status = " . Default_Model_DbTable_Project::PROJECT_ACTIVE . " + and prj.type_id = " . Default_Model_DbTable_Project::PROJECT_TYPE_STANDARD . " + group by prj.project_id; + "; + + $statement = $database->query($sql); + + $statTable = new Statistics_Model_DbTable_StatDaily(); + + while ($row = $statement->fetch(Zend_Db::FETCH_ASSOC, Zend_Db::FETCH_ORI_NEXT)) { + $row['ranking_value'] = $this->_rankingPlugin->calculateRankingValue($row); + $statTable->save($row); + } + + $resultMessage = new stdClass(); + $resultMessage->result = $statement->errorCode() == '00000' ? true : false; + $resultMessage->errorMessage = implode(' ', $statement->errorInfo()); + $resultMessage->errorCode = $statement->errorCode(); + $resultMessage->AffectedRows = $statement->rowCount(); + + return $resultMessage; + + } + + /** + * @param string $identifier + * @param int $year + * @param int $month + * @param int $day + * @return array + */ + public function getDailyStatistics($identifier, $year, $month, $day) + { + $sql = " + SELECT sd.count_views AS views, sd.count_plings AS plings, sd.count_updates AS updates, sd.count_comments AS comments, sd.count_followers AS followers, sd.count_supporters AS supporters + FROM stat_daily AS sd + WHERE + sd.project_id = ? + AND sd.year = ? + AND sd.month = ? + AND sd.day = ?; + "; + $database = Zend_Db_Table::getDefaultAdapter(); + $sql = $database->quoteInto($sql, $identifier, 'INTEGER', 1); + $sql = $database->quoteInto($sql, $year, 'INTEGER', 1); + $sql = $database->quoteInto($sql, $month, 'INTEGER', 1); + $sql = $database->quoteInto($sql, $day, 'INTEGER', 1); + + $resultSet = $database->query($sql)->fetchAll(); + + return $resultSet; + } + + /** + * @param string $identifier + * @param int $year + * @param int $month + * @return array + */ + public function getMonthlyStatistics($identifier, $year, $month) + { + $sql = " + SELECT sd.year_week, sum(sd.count_views) AS views, sum(sd.count_plings) AS plings, sum(sd.count_updates) AS updates, sum(sd.count_comments) AS comments, avg(sd.count_followers) AS followers, avg(sd.count_supporters) AS supporters + FROM stat_daily AS sd + WHERE + sd.project_id = ? + AND sd.year = ? + AND sd.month = ? + GROUP BY sd.year_week + ORDER BY sd.day ASC; + "; + $database = Zend_Db_Table::getDefaultAdapter(); + $sql = $database->quoteInto($sql, $identifier, 'INTEGER', 1); + $sql = $database->quoteInto($sql, $year, 'INTEGER', 1); + $sql = $database->quoteInto($sql, $month, 'INTEGER', 1); + + $resultSet = $database->query($sql)->fetchAll(); + + return $resultSet; + + } + + /** + * @param string $identifier + * @param int $yearWeek + * @return array + */ + public function getWeeklyStatistics($identifier, $yearWeek) + { + $sql = " + SELECT sd.day, sd.count_views AS views, sd.count_plings AS plings, sd.count_updates AS updates, sd.count_comments AS comments, sd.count_followers AS followers, sd.count_supporters AS supporters + FROM stat_daily AS sd + WHERE + sd.project_id = ? + AND sd.year_week = ? + ORDER BY sd.day ASC; + "; + $database = Zend_Db_Table::getDefaultAdapter(); + $sql = $database->quoteInto($sql, $identifier, 'INTEGER', 1); + $sql = $database->quoteInto($sql, $yearWeek, 'INTEGER', 1); + + $resultSet = $database->query($sql)->fetchAll(); + + return $resultSet; + + } + + /** + * @param DateTime $forDate + * @throws Exception + */ + protected function generateRanking(DateTime $forDate) + { + throw new Exception('this code is outdated'); + + $statisticsTable = new Statistics_Model_DbTable_StatDaily(); + + $statement = $statisticsTable->select(); + $statement->setIntegrityCheck(false)->where('year = ?', $forDate->format('Y')) + ->where('month = ?', $forDate->format('m')) + ->where('day = ?', $forDate->format('d')) + ->forUpdate(true); + + $rowSet = $statisticsTable->fetchAll($statement); + + foreach ($rowSet as $row) { + $row->ranking_value = $this->_rankingPlugin->calculateRankingValue($row->toArray()); + $row->save(); + } + + } + +} diff --git a/application/modules/statistics/models/Stat.php b/application/modules/statistics/models/Stat.php new file mode 100644 index 000000000..165ae9ede --- /dev/null +++ b/application/modules/statistics/models/Stat.php @@ -0,0 +1,39 @@ +. + **/ +class Statistics_Model_Stat +{ + + public function dailyPageviews() + { + $sql = ' + INSERT INTO stat_daily_pageviews + SELECT project.project_id, count(stat_page_views.project_id) AS cnt, project.project_category_id, CURDATE() AS created_at + FROM project + JOIN stat_page_views on project.project_id = stat_page_views.project_id AND stat_page_views.created_at > DATE_SUB(CURDATE(), INTERVAL 6 MONTH) + WHERE project.type_id = '.Default_Model_Project::PROJECT_TYPE_STANDARD.' + GROUP BY project.project_id; + '; + $database = Zend_Db_Table::getDefaultAdapter(); + $database->query($sql)->execute(); + } + +}