File indexing completed on 2024-12-22 05:33:33

0001 <?php
0002 
0003 /**
0004  *  ocs-webserver
0005  *
0006  *  Copyright 2016 by pling GmbH.
0007  *
0008  *    This file is part of ocs-webserver.
0009  *
0010  *    This program is free software: you can redistribute it and/or modify
0011  *    it under the terms of the GNU Affero General Public License as
0012  *    published by the Free Software Foundation, either version 3 of the
0013  *    License, or (at your option) any later version.
0014  *
0015  *    This program is distributed in the hope that it will be useful,
0016  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
0017  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0018  *    GNU Affero General Public License for more details.
0019  *
0020  *    You should have received a copy of the GNU Affero General Public License
0021  *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
0022  **/
0023 class ProductController extends Local_Controller_Action_DomainSwitch
0024 {
0025 
0026     const IMAGE_SMALL_UPLOAD = 'image_small_upload';
0027     const IMAGE_BIG_UPLOAD = 'image_big_upload';
0028     /**
0029      * Zend_Controller_Request_Abstract object wrapping the request environment
0030      *
0031      * @var Zend_Controller_Request_Http
0032      */
0033     protected $_request = null;
0034     /** @var  int */
0035     protected $_projectId;
0036     /** @var  int */
0037     protected $_collectionId;
0038     /** @var  Zend_Auth */
0039     protected $_auth;
0040     /** @var  string */
0041     protected $_browserTitlePrepend;
0042 
0043     public function init()
0044     {
0045         parent::init();
0046         $this->_projectId = (int)$this->getParam('project_id');
0047         $this->_collectionId = (int)$this->getParam('collection_id');
0048         $this->_auth = Zend_Auth::getInstance();
0049         $this->_browserTitlePrepend = $this->templateConfigData['head']['browser_title_prepend'];
0050 
0051         $action = $this->getRequest()->getActionName();
0052         $title = $action;
0053         if ($action == 'add') {
0054             $title = 'add product';
0055         } else {
0056             $title = $action;
0057         }
0058         $this->view->headTitle($title . ' - ' . $this->getHeadTitle(), 'SET');
0059     }
0060 
0061     public function ratingAction()
0062     {
0063         $this->_helper->layout()->disableLayout();
0064         if (array_key_exists($this->_projectId, $this->_authMember->projects)) {
0065             return;
0066         }
0067         $userRating = (int)$this->getParam('rate', 0);
0068         $modelRating = new Default_Model_DbTable_ProjectRating();
0069         $modelRating->rateForProject($this->_projectId, $this->_authMember->member_id, $userRating);
0070     }
0071 
0072 
0073     public function pploadAction()
0074     {
0075         $this->_helper->layout->disableLayout();
0076         $modelProduct = new Default_Model_Project();
0077         $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
0078         //create ppload download hash: secret + collection_id + expire-timestamp
0079         $salt = PPLOAD_DOWNLOAD_SECRET;
0080         $collectionID = $productInfo->ppload_collection_id;
0081         $timestamp = time() + 3600; // one hour valid
0082         //20181009 ronald: change hash from MD5 to SHA512
0083         //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying
0084         $hash = hash('sha512',$salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying
0085 
0086         $this->view->download_hash = $hash;
0087         $this->view->download_timestamp = $timestamp;
0088 
0089         $this->view->product = $productInfo;
0090         $this->_helper->viewRenderer('/partials/pploadajax');
0091     }
0092 
0093     public function gettaggroupsforcatajaxAction()
0094     {
0095         $this->_helper->layout()->disableLayout();
0096 
0097         $catId = null;
0098         $fileId = null;
0099 
0100         if ($this->hasParam('file_id')) {
0101             $fileId = $this->getParam('file_id');
0102         }
0103 
0104         if ($this->hasParam('project_cat_id')) {
0105             $catId = $this->getParam('project_cat_id');
0106             $catTagModel = new Default_Model_Tags();
0107             $catTagGropuModel = new Default_Model_TagGroup();
0108             $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId);
0109 
0110             $tableTags = new Default_Model_DbTable_Tags();
0111 
0112             $result = array();
0113             $resultGroup = array();
0114 
0115             foreach ($tagGroups as $group) {
0116                 $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']);
0117                 $selectedTags = null;
0118                 if (!empty($fileId)) {
0119                     $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE, $group['tag_group_id']);
0120                 }
0121 
0122                 $group['tag_list'] = $tags;
0123                 $group['selected_tags'] = $selectedTags;
0124                 $result[] = $group;
0125             }
0126 
0127             $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($tagGroups), 'tag_groups' => $result));
0128 
0129             return;
0130         }
0131 
0132         $this->_helper->json(array('status' => 'error'));
0133     }
0134 
0135     public function listsamesourceurlAction()
0136     {
0137         $this->_helper->layout()->disableLayout();
0138         $this->_helper->viewRenderer->setNoRender(true);
0139         $modelProduct = new Default_Model_Project();
0140         $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
0141         $result = $modelProduct->getSourceUrlProjects($productInfo->source_url);
0142         $r = '<div class="container containerduplicates">';
0143         foreach ($result as $value) {
0144             $r = $r . '<div class="row"><div class="col-lg-2"><a href="/p/' . $value['project_id'] . '">' . $value['project_id'] . '</a></div>'
0145                  . '<div class="col-lg-4">' . $value['title'] . '</div>'
0146                  . '<div class="col-lg-2"><a href="/u/' . $value['username'] . '">' . $value['username'] . '</a></div>'
0147                  . '<div class="col-lg-2">' . $value['created_at'] . '</div>'
0148                  . '<div class="col-lg-2">' . $value['changed_at'] . '</div>'
0149                  . '</div>';
0150         }
0151 
0152         $r = $r . '</div>';
0153 
0154 
0155         /*$response='<ul class="list-group" style="min-height:300px;min-width:1000px; max-height:500px; overflow:auto">';
0156         foreach ($result as $value) {
0157             $response=$response.'<li class="list-group-item"><a href="/p/'.$value['project_id'].'">'.$value['project_id'].'</a></li>';
0158         }
0159         $response=$response.'</ul>';*/
0160         echo $r;
0161 
0162     }
0163 
0164     public function getfilesajaxAction()
0165     {
0166         $this->_helper->layout()->disableLayout();
0167 
0168         $collection_id = null;
0169         $file_status = null;
0170         $ignore_status_code = null;
0171 
0172         $helperUserRole = new Backend_View_Helper_UserRole();
0173         $userRoleName = $helperUserRole->userRole();
0174 
0175         if ($this->hasParam('status')) {
0176             $file_status = $this->getParam('status');
0177         }
0178         if ($this->hasParam('ignore_status_code')) {
0179             $ignore_status_code = $this->getParam('ignore_status_code');
0180         }
0181 
0182         $filesTable = new Default_Model_DbTable_PploadFiles();
0183 
0184         if ($this->hasParam('collection_id')) {
0185             $collection_id = $this->getParam('collection_id');
0186             $result = array();
0187             $isForAdmin = false;
0188             if ($userRoleName == Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN) {
0189                 $isForAdmin = true;
0190             }
0191 
0192             //Load files from DB
0193             if ($ignore_status_code == 0 && $file_status == 'active') {
0194                 $files = $filesTable->fetchAllActiveFilesForProject($collection_id, $isForAdmin);
0195             } else {
0196                 $files = $filesTable->fetchAllFilesForProject($collection_id, $isForAdmin);
0197             }
0198 
0199             //Check, if the project category has tag-grous
0200             $modelProduct = new Default_Model_Project();
0201             $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
0202             $catTagGropuModel = new Default_Model_TagGroup();
0203             $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($productInfo->project_category_id);
0204 
0205             foreach ($files as $file) {
0206                 //add tag grous, if needed
0207                 if (!empty($tagGroups)) {
0208                     $groups = $this->getTagGroupsForCat($file['id']);
0209                     $file['tag_groups'] = $groups;
0210                 }
0211 
0212                 //Download Counter
0213 
0214 
0215                 //new counter IP based
0216                 $counterUkAll = $file['count_dl_all_uk'];
0217                 $counterNoUkAll = $file['count_dl_all_nouk'];
0218                 $counterUkToday = $file['count_dl_uk_today'];
0219                 $counterNew = 0;
0220                 if (!empty($counterUkAll)) {
0221                     $counterNew = $counterNew + $counterUkAll;
0222                 }
0223                 if (!empty($counterUkToday)) {
0224                     $counterNew = $counterNew + $counterUkToday;
0225                 }
0226                 if (!empty($counterNoUkAll)) {
0227                     $counterNew = $counterNew + $counterNoUkAll;
0228                 }
0229                 $file['downloaded_count_uk'] = $counterNew;
0230 
0231 
0232                 if ($userRoleName == Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN) {
0233                     //$file['downloaded_count_live'] = $this->getFileDownloadCount($collection_id, $file['id']);
0234                     $counterToday = $file['count_dl_today'];
0235                     $counterAll = $file['count_dl_all'];
0236                     $counter = 0;
0237                     if (!empty($counterToday)) {
0238                         $counter = $counterToday;
0239                     }
0240                     if (!empty($counterAll)) {
0241                         $counter = $counter + $counterAll;
0242                     }
0243                     $file['downloaded_count_live'] = $counter;
0244                 } else {
0245                     unset($file['count_dl_all']);
0246                     unset($file['count_dl_all_nouk']);
0247                     unset($file['count_dl_all_uk']);
0248                     unset($file['count_dl_uk_today']);
0249                     unset($file['count_dl_today']);
0250                     unset($file['downloaded_count']);
0251                 }
0252                 $result[] = $file;
0253             }
0254 
0255             $this->_helper->json(array('status' => 'success', 'ResultSize' => count($result), 'files' => $result));
0256 
0257             return;
0258         }
0259 
0260         $this->_helper->json(array('status' => 'error'));
0261     }
0262 
0263     private function getTagGroupsForCat($fileId)
0264     {
0265         $modelProduct = new Default_Model_Project();
0266         $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
0267         $catId = $productInfo->project_category_id;
0268 
0269         if (!empty($catId)) {
0270             $catTagModel = new Default_Model_Tags();
0271             $catTagGropuModel = new Default_Model_TagGroup();
0272             $tagGroups = $catTagGropuModel->fetchTagGroupsForCategory($catId);
0273 
0274             $tableTags = new Default_Model_DbTable_Tags();
0275 
0276             $result = array();
0277 
0278             foreach ($tagGroups as $group) {
0279                 $tags = $tableTags->fetchForGroupForSelect($group['tag_group_id']);
0280                 $selectedTags = null;
0281                 if (!empty($fileId)) {
0282                     $selectedTags = $catTagModel->getTagsArray($fileId, Default_Model_DbTable_Tags::TAG_TYPE_FILE,
0283                         $group['tag_group_id']);
0284                 }
0285 
0286                 $group['tag_list'] = $tags;
0287                 $group['selected_tags'] = $selectedTags;
0288                 $result[] = $group;
0289             }
0290 
0291             return $result;
0292         }
0293 
0294         return null;
0295     }
0296 
0297     public function getfiletagsajaxAction()
0298     {
0299         $this->_helper->layout()->disableLayout();
0300 
0301         $fileId = null;
0302 
0303         if ($this->hasParam('file_id')) {
0304             $fileId = $this->getParam('file_id');
0305 
0306             $tagModel = new Default_Model_Tags();
0307             $fileTags = $tagModel->getFileTags($fileId);
0308 
0309             $this->_helper->json(array('status' => 'ok', 'ResultSize' => count($fileTags), 'file_tags' => $fileTags));
0310 
0311             return;
0312         }
0313 
0314         $this->_helper->json(array('status' => 'error'));
0315     }
0316 
0317     public function showAction()
0318     {
0319         $this->view->authMember = $this->_authMember;
0320         $this->_helper->viewRenderer('index');
0321         $this->indexAction();
0322     }
0323 
0324     public function indexAction()
0325     {
0326 
0327         if (!empty($this->_collectionId)) {
0328             $modelProduct = new Default_Model_Project();
0329             $productInfo = $modelProduct->fetchProductForCollectionId($this->_collectionId);
0330             $this->_projectId = $productInfo->project_id;
0331         }
0332 
0333 
0334         if (empty($this->_projectId)) {
0335             $this->redirect('/explore');
0336         }
0337 
0338         $this->view->paramPageId = (int)$this->getParam('page');
0339         $this->view->member_id = null;
0340         if (null != $this->_authMember && null != $this->_authMember->member_id) {
0341             $this->view->member_id = $this->_authMember->member_id;
0342         }
0343 
0344         $modelProduct = new Default_Model_Project();
0345         $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
0346         if (empty($productInfo)) {
0347             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
0348         }
0349 
0350         //Check if this is a collection
0351         if ($productInfo->type_id == $modelProduct::PROJECT_TYPE_COLLECTION) {
0352             $this->redirect('/c/' . $this->_projectId);
0353         }
0354 
0355         $this->view->product = $productInfo;
0356         $this->view->headTitle($productInfo->title . ' - ' . $this->getHeadTitle(), 'SET');
0357         $this->view->cat_id = $this->view->product->project_category_id;
0358 
0359         $tagGroupFilter = Zend_Registry::isRegistered('config_store_taggroups') ? Zend_Registry::get('config_store_taggroups') : null;
0360         if (!empty($tagGroupFilter)) {
0361             $filterArray = array();
0362             foreach ($tagGroupFilter as $tagGroupId) {
0363                 $inputFilter = $this->getFilterTagFromCookie($tagGroupId);
0364                 $filterArray[$tagGroupId] = $inputFilter;
0365             }
0366             $this->view->tag_group_filter = $filterArray;
0367         }
0368 
0369         //create ppload download hash: secret + collection_id + expire-timestamp
0370         $salt = PPLOAD_DOWNLOAD_SECRET;
0371         $collectionID = $this->view->product->ppload_collection_id;
0372         $timestamp = time() + 3600; // one hour valid
0373         //20181009 ronald: change hash from MD5 to SHA512
0374         //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying
0375         $hash = hash('sha512',
0376             $salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying
0377 
0378         $this->view->download_hash = $hash;
0379         $this->view->download_timestamp = $timestamp;
0380 
0381         $helperUserRole = new Backend_View_Helper_UserRole();
0382         $userRoleName = $helperUserRole->userRole();
0383         $isAdmin = false;
0384         if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) {
0385             $isAdmin = true;
0386         }
0387 
0388         $helperUserIsOwner = new Default_View_Helper_UserIsOwner();
0389         $helperIsProjectActive = new Default_View_Helper_IsProjectActive();
0390         if (!$isAdmin AND (false === $helperIsProjectActive->isProjectActive($this->view->product->project_status))
0391                           AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id))
0392         ) {
0393             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
0394         }
0395 
0396         if ((APPLICATION_ENV != 'searchbotenv') AND (false == SEARCHBOT_DETECTED)) {
0397             Default_Model_Views::saveViewProduct($this->_projectId);
0398 
0399             $tablePageViews = new Default_Model_DbTable_StatPageViews();
0400             $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(),
0401                 $this->_authMember->member_id);
0402         }
0403 
0404         $fmodel = new  Default_Model_DbTable_PploadFiles();
0405 
0406         $filesList = array();
0407 
0408         if (isset($this->view->product->ppload_collection_id)) {
0409             $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id);
0410             if (!empty($files)) {
0411                 foreach ($files as $file) {
0412                     $timestamp = time() + 3600; // one hour valid
0413                     $hash = hash('sha512',
0414                         $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying
0415                     $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp;
0416                     if (null != $this->_authMember) {
0417                         $url .= '/u/' . $this->_authMember->member_id;
0418                     }
0419                     $url .= '/lt/filepreview/' . $file['name'];
0420 
0421                     $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview');
0422                     $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload);
0423 
0424                     $file['url'] = urlencode($url);
0425 
0426                     //If this file is a video, we have to convert it for preview
0427                     if (!empty($file['type']) && in_array($file['type'], Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES) && empty($file['ppload_file_preview_id'])) {
0428                         $queue = Local_Queue_Factory::getQueue();
0429                         $command = new Backend_Commands_ConvertVideo($file['collection_id'], $file['id'], $file['type']);
0430                         $queue->send(serialize($command));
0431                     }
0432 
0433                     if (!empty($file['url_preview'])) {
0434                         $file['url_preview'] = urlencode($file['url_preview']);
0435                     }
0436                     if (!empty($file['url_thumb'])) {
0437                         $file['url_thumb'] = urlencode($file['url_thumb']);
0438                     }
0439 
0440                     $filesList[] = $file;
0441                 }
0442             }
0443         }
0444 
0445         $this->view->filesJson = Zend_Json::encode($filesList);
0446 
0447 
0448         //gitlab
0449         if ($this->view->product->is_gitlab_project) {
0450             $gitProject = $this->fetchGitlabProject($this->view->product->gitlab_project_id);
0451             if (null == $gitProject) {
0452                 $this->view->product->is_gitlab_project = 0;
0453                 $this->view->product->show_gitlab_project_issues = 0;
0454                 $this->view->product->use_gitlab_project_readme = 0;
0455                 $this->view->product->gitlab_project_id = null;
0456             } else {
0457                 $this->view->gitlab_project = $gitProject;
0458 
0459                 //show issues?
0460                 if ($this->view->product->show_gitlab_project_issues) {
0461                     $issues = $this->fetchGitlabProjectIssues($this->view->product->gitlab_project_id);
0462                     $this->view->gitlab_project_issues = $issues;
0463                     $this->view->gitlab_project_issues_url = $this->view->gitlab_project['web_url'] . '/issues/';
0464                 }
0465 
0466                 //show readme.md?
0467                 if ($this->view->product->use_gitlab_project_readme && null != $this->view->gitlab_project['readme_url']) {
0468                     $config = Zend_Registry::get('config')->settings->server->opencode;
0469                     $readme = $this->view->gitlab_project['web_url'] . '/raw/master/README.md?inline=false';
0470                     $httpClient = new Zend_Http_Client($readme, array('keepalive' => true, 'strictredirects' => true));
0471                     $httpClient->resetParameters();
0472                     $httpClient->setUri($readme);
0473                     $httpClient->setHeaders('Private-Token', $config->private_token);
0474                     $httpClient->setHeaders('Sudo', $config->user_sudo);
0475                     $httpClient->setHeaders('User-Agent', $config->user_agent);
0476                     $httpClient->setMethod(Zend_Http_Client::GET);
0477 
0478                     $response = $httpClient->request();
0479 
0480                     $body = $response->getRawBody();
0481 
0482                     if (count($body) == 0) {
0483                         return array();
0484                     }
0485                     include_once('Parsedown.php');
0486                     $Parsedown = new Parsedown();
0487 
0488                     $this->view->readme = $Parsedown->text($body);
0489 
0490                 } else {
0491                     $this->view->readme = null;
0492                 }
0493             }
0494         }
0495 
0496         // products related
0497         $pc = new Default_Model_ProjectClone();
0498         $cntRelatedProducts = 0;
0499         $ancesters = $pc->fetchAncestersIds($this->_projectId);
0500         //$siblings = $pc->fetchSiblings($this->_projectId);
0501         //$parents = $pc->fetchParentIds($this->_projectId);
0502         if ($ancesters && strlen($ancesters) > 0) {
0503             $parents = $pc->fetchParentLevelRelatives($this->_projectId);
0504         } else {
0505             $parents = $pc->fetchParentIds($this->_projectId);
0506         }
0507         if ($parents && strlen($parents) > 0) {
0508             $siblings = $pc->fetchSiblingsLevelRelatives($parents, $this->_projectId);
0509         } else {
0510             $siblings = null;
0511         }
0512         $childrens = $pc->fetchChildrensIds($this->_projectId);
0513         $childrens2 = null;
0514         $childrens3 = null;
0515         if (strlen($childrens) > 0) {
0516             $childrens2 = $pc->fetchChildrensChildrenIds($childrens);
0517             if (strlen($childrens2) > 0) {
0518                 $childrens3 = $pc->fetchChildrensChildrenIds($childrens2);
0519             }
0520         }
0521 
0522         $this->view->related_ancesters = null;
0523         $this->view->related_siblings = null;
0524         $this->view->related_parents = null;
0525         $this->view->related_children = null;
0526         // $this->view->related_children2 = null;
0527         // $this->view->related_children3 = null;
0528         if ($ancesters && strlen($ancesters) > 0) {
0529             $pts = $modelProduct->fetchProjects($ancesters);
0530             $this->view->related_ancesters = sizeof($pts) == 0 ? null : $pts;
0531             $cntRelatedProducts += sizeof($pts);
0532         }
0533         if ($siblings && strlen($siblings) > 0) {
0534             $pts = $modelProduct->fetchProjects($siblings);
0535             $this->view->related_siblings = sizeof($pts) == 0 ? null : $pts;
0536             $cntRelatedProducts += sizeof($pts);
0537         }
0538         if ($parents && strlen($parents) > 0) {
0539             $pts = $modelProduct->fetchProjects($parents);
0540             $this->view->related_parents = sizeof($pts) == 0 ? null : $pts;
0541             $cntRelatedProducts += sizeof($pts);
0542         }
0543         if ($childrens && strlen($childrens) > 0) {
0544             $pts = $modelProduct->fetchProjects($childrens);
0545             $this->view->related_children = sizeof($pts) == 0 ? null : $pts;
0546             $cntRelatedProducts += sizeof($pts);
0547         }
0548         // if ($childrens2 && strlen($childrens2) > 0) {
0549         //     $pts = $modelProduct->fetchProjects($childrens2);
0550         //     $this->view->related_children2 = sizeof($pts) == 0 ? null : $pts;
0551         //     $cntRelatedProducts += sizeof($pts);
0552         // }
0553         // if ($childrens3 && strlen($childrens3) > 0) {
0554         //     $pts = $modelProduct->fetchProjects($childrens3);
0555         //     $this->view->related_children3 = sizeof($pts) == 0 ? null : $pts;
0556         //     $cntRelatedProducts += sizeof($pts);
0557         // }
0558 
0559         $this->view->cntRelatedProducts = $cntRelatedProducts;
0560 
0561         $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null;
0562         if ($storeConfig->layout_pagedetail && $storeConfig->isRenderReact()) {
0563             $this->initJsonForReact();
0564             $this->_helper->viewRenderer('index-react');
0565         }
0566 
0567     }
0568 
0569     private function getFilterTagFromCookie($group)
0570     {
0571         $config = Zend_Registry::get('config');
0572         $cookieName = $config->settings->session->filter_browse_original . $group;
0573 
0574         $storedInCookie = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : null;
0575 
0576         return $storedInCookie;
0577     }
0578 
0579     private function fetchGitlabProject($gitProjectId)
0580     {
0581         $gitlab = new Default_Model_Ocs_Gitlab();
0582 
0583         try {
0584             $gitProject = $gitlab->getProject($gitProjectId);
0585         } catch (Exception $exc) {
0586             //Project is gone
0587             $modelProject = new Default_Model_Project();
0588             $modelProject->updateProject($this->_projectId, array(
0589                 'is_gitlab_project'          => 0,
0590                 'gitlab_project_id'          => null,
0591                 'show_gitlab_project_issues' => 0,
0592                 'use_gitlab_project_readme'  => 0
0593             ));
0594             $gitProject = null;
0595         }
0596 
0597         return $gitProject;
0598     }
0599 
0600     private function fetchGitlabProjectIssues($gitProjectId)
0601     {
0602         $gitlab = new Default_Model_Ocs_Gitlab();
0603 
0604         try {
0605             $gitProjectIssues = $gitlab->getProjectIssues($gitProjectId);
0606         } catch (Exception $exc) {
0607             //Project is gone
0608             $modelProject = new Default_Model_Project();
0609             $modelProject->updateProject($this->_projectId, array(
0610                 'is_gitlab_project'          => 0,
0611                 'gitlab_project_id'          => null,
0612                 'show_gitlab_project_issues' => 0,
0613                 'use_gitlab_project_readme'  => 0
0614             ));
0615 
0616             $gitProjectIssues = null;
0617         }
0618 
0619 
0620         return $gitProjectIssues;
0621     }
0622 
0623     public function initJsonForReact()
0624     {
0625         $modelProduct = new Default_Model_Project();
0626         $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
0627         $this->view->product = $productInfo;
0628         if (empty($this->view->product)) {
0629             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
0630         }
0631 
0632         if (null != $this->_authMember) {
0633             $this->view->authMemberJson = Zend_Json::encode(Default_Model_Member::cleanAuthMemberForJson($this->_authMember));
0634         }
0635 
0636         $helpAddDefaultScheme = new Default_View_Helper_AddDefaultScheme();
0637         $this->view->product->title = Default_Model_HtmlPurify::purify($this->view->product->title);
0638         $this->view->product->description = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify($this->view->product->description));
0639         $this->view->product->version = Default_Model_HtmlPurify::purify($this->view->product->version);
0640         $this->view->product->link_1 = Default_Model_HtmlPurify::purify($helpAddDefaultScheme->addDefaultScheme($this->view->product->link_1),
0641             Default_Model_HtmlPurify::ALLOW_URL);
0642         $this->view->product->source_url = Default_Model_HtmlPurify::purify($this->view->product->source_url,
0643             Default_Model_HtmlPurify::ALLOW_URL);
0644         $this->view->product->facebook_code = Default_Model_HtmlPurify::purify($this->view->product->facebook_code,
0645             Default_Model_HtmlPurify::ALLOW_URL);
0646         $this->view->product->twitter_code = Default_Model_HtmlPurify::purify($this->view->product->twitter_code,
0647             Default_Model_HtmlPurify::ALLOW_URL);
0648         $this->view->product->google_code = Default_Model_HtmlPurify::purify($this->view->product->google_code,
0649             Default_Model_HtmlPurify::ALLOW_URL);
0650         $this->view->productJson = Zend_Json::encode(Default_Model_Collection::cleanProductInfoForJson($this->view->product));
0651 
0652         $fmodel = new  Default_Model_DbTable_PploadFiles();
0653         $files = $fmodel->fetchFilesForProject($this->view->product->ppload_collection_id);
0654 
0655         $salt = PPLOAD_DOWNLOAD_SECRET;
0656 
0657         $filesList = array();
0658 
0659         foreach ($files as $file) {
0660             $timestamp = time() + 3600; // one hour valid
0661             $hash = hash('sha512',
0662                 $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying
0663             $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp;
0664             if (null != $this->_authMember) {
0665                 $url .= '/u/' . $this->_authMember->member_id;
0666             }
0667             $url .= '/lt/filepreview/' . $file['name'];
0668 
0669             $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview');
0670             $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload);
0671 
0672             $file['url'] = urlencode($url);
0673             $filesList[] = $file;
0674         }
0675 
0676         $this->view->filesJson = Zend_Json::encode($filesList);
0677         $this->view->filesCntJson = Zend_Json::encode($fmodel->fetchFilesCntForProject($this->view->product->ppload_collection_id));
0678 
0679         $tableProjectUpdates = new Default_Model_ProjectUpdates();
0680         $this->view->updatesJson = Zend_Json::encode($tableProjectUpdates->fetchProjectUpdates($this->_projectId));
0681         $tableProjectRatings = new Default_Model_DbTable_ProjectRating();
0682         $ratings = $tableProjectRatings->fetchRating($this->_projectId);
0683         $cntRatingsActive = 0;
0684         foreach ($ratings as $p) {
0685             if ($p['rating_active'] == 1) {
0686                 $cntRatingsActive = $cntRatingsActive + 1;
0687             }
0688         }
0689         $this->view->ratingsJson = Zend_Json::encode($ratings);
0690         $this->view->cntRatingsActiveJson = Zend_Json::encode($cntRatingsActive);
0691 
0692         $identity = Zend_Auth::getInstance()->getStorage()->read();
0693         if (Zend_Auth::getInstance()->hasIdentity()) {
0694             $ratingOfUserJson = $tableProjectRatings->getProjectRateForUser($this->_projectId, $identity->member_id);
0695             $this->view->ratingOfUserJson = Zend_Json::encode($ratingOfUserJson);
0696         } else {
0697             $this->view->ratingOfUserJson = Zend_Json::encode(null);
0698         }
0699         $tableProjectFollower = new Default_Model_DbTable_ProjectFollower();
0700         $likes = $tableProjectFollower->fetchLikesForProject($this->_projectId);
0701         $this->view->likeJson = Zend_Json::encode($likes);
0702 
0703         $projectplings = new Default_Model_ProjectPlings();
0704         $plings = $projectplings->fetchPlingsForProject($this->_projectId);
0705         $this->view->projectplingsJson = Zend_Json::encode($plings);
0706 
0707         $tableProject = new Default_Model_Project();
0708         $galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId);
0709         $this->view->galleryPicturesJson = Zend_Json::encode($galleryPictures);
0710 
0711         $tagmodel = new Default_Model_Tags();
0712         $tagsuser = $tagmodel->getTagsUser($this->_projectId, Default_Model_Tags::TAG_TYPE_PROJECT);
0713         $tagssystem = $tagmodel->getTagsSystemList($this->_projectId);
0714         $this->view->tagsuserJson = Zend_Json::encode($tagsuser);
0715         $this->view->tagssystemJson = Zend_Json::encode($tagssystem);
0716 
0717         $modelComments = new Default_Model_ProjectComments();
0718         $offset = 0;
0719         $testComments = $modelComments->getCommentTreeForProjectList($this->_projectId);
0720         $this->view->commentsJson = Zend_Json::encode($testComments);
0721 
0722         $modelClone = new Default_Model_ProjectClone();
0723         $origins = $modelClone->fetchOrigins($this->_projectId);
0724         $this->view->originsJson = Zend_Json::encode($origins);
0725         $related = $modelClone->fetchRelatedProducts($this->_projectId);
0726         $this->view->relatedJson = Zend_Json::encode($related);
0727 
0728         $moreProducts = $tableProject->fetchMoreProjects($this->view->product, 8);
0729         $this->view->moreProductsJson = Zend_Json::encode($moreProducts);
0730 
0731         $moreProducts = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8);
0732         $this->view->moreProductsOfOtherUsrJson = Zend_Json::encode($moreProducts);
0733 
0734 
0735     }
0736 
0737     public function addAction()
0738     {
0739         $this->view->member = $this->_authMember;
0740         $this->view->mode = 'add';
0741 
0742         if ($this->getParam('catId')) {
0743             $this->view->catId = $this->getParam('catId');
0744         }
0745         $form = new Default_Form_Product(array('member_id' => $this->view->member->member_id));
0746         $this->view->form = $form;
0747 
0748         if ($this->_request->isGet()) {
0749             return;
0750         }
0751 
0752         if (isset($_POST['cancel'])) { // user cancel function
0753             $this->redirect('/member/' . $this->_authMember->member_id . '/news/');
0754         }
0755 
0756         if (false === $form->isValid($_POST)) { // form not valid
0757             $this->view->form = $form;
0758             $this->view->error = 1;
0759 
0760             return;
0761         }
0762 
0763         $values = $form->getValues();
0764 
0765         $imageModel = new Default_Model_DbTable_Image();
0766         try {
0767             $values['image_small'] = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD));
0768         } catch (Exception $e) {
0769             Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true));
0770         }
0771 
0772         // form was valid, so we can set status to active
0773         $values['status'] = Default_Model_DbTable_Project::PROJECT_ACTIVE;
0774 
0775         // save new project
0776         $modelProject = new Default_Model_Project();
0777 
0778         Zend_Registry::get('logger')->info(__METHOD__ . ' - $post: ' . print_r($_POST, true));
0779         Zend_Registry::get('logger')->info(__METHOD__ . ' - $files: ' . print_r($_FILES, true));
0780         Zend_Registry::get('logger')->info(__METHOD__ . ' - input values: ' . print_r($values, true));
0781 
0782         $newProject = null;
0783         try {
0784             if (isset($values['project_id'])) {
0785                 $newProject = $modelProject->updateProject($values['project_id'], $values);
0786             } else {
0787                 $newProject = $modelProject->createProject($this->_authMember->member_id, $values,
0788                     $this->_authMember->username);
0789                 //$this->createSystemPlingForNewProject($newProject->project_id);
0790             }
0791         } catch (Exception $exc) {
0792             Zend_Registry::get('logger')->warn(__METHOD__ . ' - traceString: ' . $exc->getTraceAsString());
0793         }
0794 
0795         if (!$newProject) {
0796             $this->_helper->flashMessenger->addMessage('<p class="text-error">You did not choose a Category in the last level.</p>');
0797             $this->forward('add');
0798 
0799             return;
0800         }
0801 
0802         //update the gallery pics
0803         $mediaServerUrls = $this->saveGalleryPics($form->gallery->upload->upload_picture);
0804         $modelProject->updateGalleryPictures($newProject->project_id, $mediaServerUrls);
0805 
0806         //If there is no Logo, we take the 1. gallery pic
0807         if (!isset($values['image_small']) || $values['image_small'] == '') {
0808             $values['image_small'] = $mediaServerUrls[0];
0809             $newProject = $modelProject->updateProject($newProject->project_id, $values);
0810         }
0811 
0812         //New Project in Session, for AuthValidation (owner)
0813         $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id);
0814 
0815         $modelTags = new Default_Model_Tags();
0816         if ($values['tagsuser']) {
0817             $modelTags->processTagsUser($newProject->project_id, implode(',', $values['tagsuser']),
0818                 Default_Model_Tags::TAG_TYPE_PROJECT);
0819         } else {
0820             $modelTags->processTagsUser($newProject->project_id, null, Default_Model_Tags::TAG_TYPE_PROJECT);
0821         }
0822 
0823         $modelTags->processTagProductOriginalOrModification($newProject->project_id,
0824             $values['is_original_or_modification'][0]);
0825 
0826         //set license, if needed
0827         $licenseTag = $form->getElement('license_tag_id')->getValue();
0828         //only set/update license tags if something was changed
0829         if ($licenseTag && count($licenseTag) > 0) {
0830             $modelTags->saveLicenseTagForProject($newProject->project_id, $licenseTag);
0831             $activityLog = new Default_Model_ActivityLog();
0832             $activityLog->logActivity($newProject->project_id, $newProject->project_id, $this->_authMember->member_id,
0833                 Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED,
0834                 array('title' => 'Set new License Tag', 'description' => 'New TagId: ' . $licenseTag));
0835         }
0836 
0837         $isGitlabProject = $form->getElement('is_gitlab_project')->getValue();
0838         $gitlabProjectId = $form->getElement('gitlab_project_id')->getValue();
0839         if ($isGitlabProject && $gitlabProjectId == 0) {
0840             $values['gitlab_project_id'] = null;
0841         }
0842 
0843         $activityLog = new Default_Model_ActivityLog();
0844         $activityLog->writeActivityLog($newProject->project_id, $newProject->member_id,
0845             Default_Model_ActivityLog::PROJECT_CREATED, $newProject->toArray());
0846 
0847         // ppload
0848         $this->processPploadId($newProject);
0849 
0850         try {
0851             if (100 < $this->_authMember->roleId) {
0852                 if (Default_Model_Spam::hasSpamMarkers($newProject->toArray())) {
0853                     $tableReportComments = new Default_Model_DbTable_ReportProducts();
0854                     $tableReportComments->save(array(
0855                         'project_id'  => $newProject->project_id,
0856                         'reported_by' => 24,
0857                         'text'        => "System: automatic spam detection"
0858                     ));
0859                 }
0860                 Default_Model_DbTable_SuspicionLog::logProject($newProject, $this->_authMember, $this->getRequest());
0861             }
0862         } catch (Zend_Exception $e) {
0863             Zend_Registry::get('logger')->err($e->getMessage());
0864         }
0865 
0866         $this->redirect('/member/' . $newProject->member_id . '/products/');
0867     }
0868 
0869     private function saveGalleryPics($form_element)
0870     {
0871         $imageModel = new Default_Model_DbTable_Image();
0872 
0873         return $imageModel->saveImages($form_element);
0874     }
0875 
0876     /**
0877      * @param $projectData
0878      */
0879     protected function processPploadId($projectData)
0880     {
0881         if ($projectData->ppload_collection_id) {
0882             $pploadApi = new Ppload_Api(array(
0883                 'apiUri'   => PPLOAD_API_URI,
0884                 'clientId' => PPLOAD_CLIENT_ID,
0885                 'secret'   => PPLOAD_SECRET
0886             ));
0887             // Update collection information
0888             $collectionCategory = $projectData->project_category_id;
0889             if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) {
0890                 $collectionCategory .= '-published';
0891             }
0892             $collectionRequest = array(
0893                 'title'       => $projectData->title,
0894                 'description' => $projectData->description,
0895                 'category'    => $collectionCategory,
0896                 'content_id'  => $projectData->project_id
0897             );
0898 
0899             $collectionResponse = $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest);
0900 
0901             // Store product image as collection thumbnail
0902             $this->_updatePploadMediaCollectionthumbnail($projectData);
0903         }
0904     }
0905 
0906     /**
0907      * ppload
0908      */
0909     protected function _updatePploadMediaCollectionthumbnail($projectData)
0910     {
0911         if (empty($projectData->ppload_collection_id)
0912             || empty($projectData->image_small)
0913         ) {
0914             return false;
0915         }
0916 
0917         $pploadApi = new Ppload_Api(array(
0918             'apiUri'   => PPLOAD_API_URI,
0919             'clientId' => PPLOAD_CLIENT_ID,
0920             'secret'   => PPLOAD_SECRET
0921         ));
0922 
0923         $filename = sys_get_temp_dir() . '/' . $projectData->image_small;
0924         if (false === file_exists(dirname($filename))) {
0925             mkdir(dirname($filename), 0777, true);
0926         }
0927         $viewHelperImage = new Default_View_Helper_Image();
0928         $uri = $viewHelperImage->Image($projectData->image_small, array(
0929             'width'  => 600,
0930             'height' => 600
0931         ));
0932 
0933         file_put_contents($filename, file_get_contents($uri));
0934 
0935         $mediaCollectionthumbnailResponse =
0936             $pploadApi->postMediaCollectionthumbnail($projectData->ppload_collection_id, array('file' => $filename));
0937 
0938         unlink($filename);
0939 
0940         if (isset($mediaCollectionthumbnailResponse->status)
0941             && $mediaCollectionthumbnailResponse->status == 'success'
0942         ) {
0943             return true;
0944         }
0945 
0946         return false;
0947     }
0948 
0949     public function editAction()
0950     {
0951         if (empty($this->_projectId)) {
0952             $this->redirect($this->_helper->url('add'));
0953 
0954             return;
0955         }
0956 
0957         $this->_helper->viewRenderer('add'); // we use the same view as you can see at add a product
0958         $this->view->mode = 'edit';
0959 
0960         $projectTable = new Default_Model_DbTable_Project();
0961         $projectModel = new Default_Model_Project();
0962         $modelTags = new Default_Model_Tags();
0963         $tagTable = new Default_Model_DbTable_Tags();
0964 
0965         //check if product with given id exists
0966         $projectData = $projectTable->find($this->_projectId)->current();
0967         if (empty($projectData)) {
0968             $this->redirect($this->_helper->url('add'));
0969 
0970             return;
0971         }
0972 
0973         $member = null;
0974         if (isset($this->_authMember) AND (false === empty($this->_authMember->member_id))) {
0975             $member = $this->_authMember;
0976         } else {
0977             throw new Zend_Controller_Action_Exception('no authorization found');
0978         }
0979 
0980         if (("admin" == $this->_authMember->roleName)) {
0981             $modelMember = new Default_Model_Member();
0982             $member = $modelMember->fetchMember($projectData->member_id, false);
0983         }
0984 
0985         $helperUserRole = new Backend_View_Helper_UserRole();
0986         $userRoleName = $helperUserRole->userRole();
0987         $isAdmin = false;
0988         if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) {
0989             $isAdmin = true;
0990         }
0991 
0992 
0993         //set ppload-collection-id in view
0994         $this->view->ppload_collection_id = $projectData->ppload_collection_id;
0995         $this->view->project_id = $projectData->project_id;
0996         $this->view->product = $projectData;
0997 
0998         //create ppload download hash: secret + collection_id + expire-timestamp
0999         $salt = PPLOAD_DOWNLOAD_SECRET;
1000         $collectionID = $projectData->ppload_collection_id;
1001         $timestamp = time() + 3600; // one hour valid
1002         //20181009 ronald: change hash from MD5 to SHA512
1003         //$hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying
1004         $hash = hash('sha512',
1005             $salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying
1006 
1007         $this->view->download_hash = $hash;
1008         $this->view->download_timestamp = $timestamp;
1009         $this->view->member_id = $member->member_id;
1010         $this->view->member = $member;
1011 
1012 
1013         //read the already existing gallery pics and add them to the form
1014         $sources = $projectModel->getGalleryPictureSources($this->_projectId);
1015 
1016         //get the gitlab projects for this user
1017 
1018         //setup form
1019         $form = new Default_Form_Product(array('pictures' => $sources, 'member_id' => $this->view->member_id));
1020         if (false === empty($projectData->image_small)) {
1021             $form->getElement('image_small_upload')->setRequired(false);
1022         }
1023         $form->getElement('preview')->setLabel('Save');
1024 
1025         $form->removeElement('project_id'); // we don't need this field in edit mode
1026 
1027         if ($this->_request->isGet()) {
1028             $form->populate($projectData->toArray());
1029             // $form->populate(array('tags' => $modelTags->getTags($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT)));
1030             $form->populate(array(
1031                 'tagsuser' => $modelTags->getTagsUser($projectData->project_id, Default_Model_Tags::TAG_TYPE_PROJECT)
1032             ));
1033             $form->getElement('image_small')->setValue($projectData->image_small);
1034             //Bilder voreinstellen
1035             $form->getElement(self::IMAGE_SMALL_UPLOAD)->setValue($projectData->image_small);
1036 
1037             $licenseTags = $tagTable->fetchLicenseTagsForProject($this->_projectId);
1038             $licenseTag = null;
1039             if ($licenseTags) {
1040                 $licenseTag = $licenseTags[0]['tag_id'];
1041             }
1042             $form->getElement('license_tag_id')->setValue($licenseTag);
1043 
1044             $is_original = $modelTags->isProductOriginal($projectData->project_id);
1045             $is_modification = $modelTags->isProductModification($projectData->project_id);
1046             if ($is_original) {
1047                 $form->getElement('is_original_or_modification')->setValue(1);
1048             } else {
1049                 if ($is_modification) {
1050                     $form->getElement('is_original_or_modification')->setValue(2);
1051                 }
1052             }
1053 
1054             $this->view->form = $form;
1055 
1056             return;
1057         }
1058 
1059         if (isset($_POST['cancel'])) { // user cancel function
1060             $this->redirect('/member/' . $member->member_id . '/news/');
1061         }
1062 
1063         if (false === $form->isValid($_POST, $this->_projectId)) { // form not valid
1064             $this->view->form = $form;
1065             $this->view->error = 1;
1066 
1067             return;
1068         }
1069 
1070         $values = $form->getValues();
1071 
1072 
1073         //set license, if needed
1074         $tagList = $modelTags->getTagsArray($this->_projectId, $modelTags::TAG_TYPE_PROJECT,
1075             $modelTags::TAG_LICENSE_GROUPID);
1076         $oldLicenseTagId = null;
1077         if ($tagList && count($tagList) == 1) {
1078             $oldLicenseTagId = $tagList[0]['tag_id'];
1079         }
1080 
1081         $licenseTag = $form->getElement('license_tag_id')->getValue();
1082         //only set/update license tags if something was changed
1083         if ($licenseTag <> $oldLicenseTagId) {
1084             $modelTags->saveLicenseTagForProject($this->_projectId, $licenseTag);
1085             $activityLog = new Default_Model_ActivityLog();
1086             $activityLog->logActivity($this->_projectId, $this->_projectId, $this->_authMember->member_id,
1087                 Default_Model_ActivityLog::PROJECT_LICENSE_CHANGED, array(
1088                     'title'       => 'License Tag',
1089                     'description' => 'Old TagId: ' . $oldLicenseTagId . ' - New TagId: ' . $licenseTag
1090                 ));
1091         }
1092 
1093         //gitlab project
1094         $isGitlabProject = $form->getElement('is_gitlab_project')->getValue();
1095         $gitlabProjectId = $form->getElement('gitlab_project_id')->getValue();
1096         if ($isGitlabProject && $gitlabProjectId == 0) {
1097             $values['gitlab_project_id'] = null;
1098         }
1099 
1100 
1101         $imageModel = new Default_Model_DbTable_Image();
1102         try {
1103             $uploadedSmallImage = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD));
1104             $values['image_small'] = $uploadedSmallImage ? $uploadedSmallImage : $values['image_small'];
1105         } catch (Exception $e) {
1106             Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true));
1107         }
1108 
1109         // save changes
1110         $projectModel->updateProject($this->_projectId, $values);
1111 
1112         //update the gallery pics
1113         $pictureSources = array_merge($values['gallery']['online_picture'],
1114             $this->saveGalleryPics($form->gallery->upload->upload_picture));
1115         $projectModel->updateGalleryPictures($this->_projectId, $pictureSources);
1116 
1117         //If there is no Logo, we take the 1. gallery pic
1118         if (!isset($projectData->image_small) || $projectData->image_small == '') {
1119             $projectData->image_small = $pictureSources[0];
1120         }
1121         //20180219 ronald: we set the changed_at only by new files or new updates
1122         //$projectData->changed_at = new Zend_Db_Expr('NOW()');
1123         $projectData->save();
1124 
1125         $modelTags->processTagProductOriginalOrModification($this->_projectId,
1126             $values['is_original_or_modification'][0]);
1127 
1128         if ($values['tagsuser']) {
1129             $modelTags->processTagsUser($this->_projectId, implode(',', $values['tagsuser']),
1130                 Default_Model_Tags::TAG_TYPE_PROJECT);
1131         } else {
1132             $modelTags->processTagsUser($this->_projectId, null, Default_Model_Tags::TAG_TYPE_PROJECT);
1133         }
1134 
1135         $activityLog = new Default_Model_ActivityLog();
1136         $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
1137             Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray());
1138 
1139         // ppload
1140         $this->processPploadId($projectData);
1141 
1142         try {
1143             if (100 < $this->_authMember->roleId) {
1144                 if (Default_Model_Spam::hasSpamMarkers($projectData->toArray())) {
1145                     $tableReportComments = new Default_Model_DbTable_ReportProducts();
1146                     $tableReportComments->save(array(
1147                         'project_id'  => $projectData->project_id,
1148                         'reported_by' => 24,
1149                         'text'        => "System: automatic spam detection on product edit"
1150                     ));
1151                 }
1152                 Default_Model_DbTable_SuspicionLog::logProject($projectData, $this->_authMember, $this->getRequest());
1153             }
1154         } catch (Zend_Exception $e) {
1155             Zend_Registry::get('logger')->err($e->getMessage());
1156         }
1157 
1158         $helperBuildMemberUrl = new Default_View_Helper_BuildMemberUrl();
1159         $this->redirect($helperBuildMemberUrl->buildMemberUrl($member->username, 'products'));
1160     }
1161 
1162     public function getupdatesajaxAction()
1163     {
1164         $this->view->authMember = $this->_authMember;
1165         $tableProject = new Default_Model_ProjectUpdates();
1166 
1167         $updates = $tableProject->fetchProjectUpdates($this->_projectId);
1168 
1169         foreach ($updates as $key => $update) {
1170             $updates[$key]['title'] = Default_Model_HtmlPurify::purify($update['title']);
1171             $updates[$key]['text'] = Default_Model_BBCode::renderHtml(Default_Model_HtmlPurify::purify(htmlentities($update['text'],
1172                 ENT_QUOTES | ENT_IGNORE)));
1173             $updates[$key]['raw_title'] = $update['title'];
1174             $updates[$key]['raw_text'] = $update['text'];
1175         }
1176 
1177         $result['status'] = 'success';
1178         $result['ResultSize'] = count($updates);
1179         $result['updates'] = $updates;
1180 
1181         $this->_helper->json($result);
1182     }
1183 
1184     public function saveupdateajaxAction()
1185     {
1186         $filter =
1187             new Zend_Filter_Input(
1188                 array(
1189                     '*' => 'StringTrim'
1190                 ),
1191                 array(
1192                     '*'         => array(),
1193                     'title'     => array(
1194                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 200)),
1195                         'presence'   => 'required',
1196                         'allowEmpty' => false
1197                     ),
1198                     'text'      => array(
1199                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 16383)),
1200                         'presence'   => 'required',
1201                         'allowEmpty' => false
1202                     ),
1203                     'update_id' => array('digits', 'allowEmpty' => true)
1204                 ), $this->getAllParams(), array('allowEmpty' => true));
1205 
1206         if ($filter->hasInvalid() OR $filter->hasMissing() OR $filter->hasUnknown()) {
1207             $result['status'] = 'error';
1208             $result['messages'] = $filter->getMessages();
1209             $result['update_id'] = null;
1210 
1211             $this->_helper->json($result);
1212         }
1213 
1214         $update_id = $filter->getEscaped('update_id');
1215         $tableProjectUpdates = new Default_Model_ProjectUpdates();
1216 
1217         //Save update
1218         if (!empty($update_id)) {
1219             //Update old update
1220             $updateArray = array();
1221             $updateArray['title'] = $filter->getUnescaped('title');
1222             $updateArray['text'] = $filter->getUnescaped('text');
1223             $updateArray['changed_at'] = new Zend_Db_Expr('Now()');
1224             $countUpdated = $tableProjectUpdates->update($updateArray, 'project_update_id = ' . $update_id);
1225         } else {
1226             //Add new update
1227             $updateArray = array();
1228             $updateArray['title'] = $filter->getUnescaped('title');
1229             $updateArray['text'] = $filter->getUnescaped('text');
1230             $updateArray['public'] = 1;
1231             $updateArray['project_id'] = $this->_projectId;
1232             $updateArray['member_id'] = $this->_authMember->member_id;
1233             $updateArray['created_at'] = new Zend_Db_Expr('Now()');
1234             $updateArray['changed_at'] = new Zend_Db_Expr('Now()');
1235             $rowset = $tableProjectUpdates->save($updateArray);
1236             $update_id = $rowset->project_update_id;
1237 
1238             //20180219 ronald: we set the changed_at only by new files or new updates
1239             $projectTable = new Default_Model_Project();
1240             $projectUpdateRow = $projectTable->find($this->_projectId)->current();
1241             if (count($projectUpdateRow) == 1) {
1242                 $projectUpdateRow->changed_at = new Zend_Db_Expr('NOW()');
1243                 $projectUpdateRow->save();
1244             }
1245         }
1246 
1247         $result['status'] = 'success';
1248         $result['update_id'] = $update_id;
1249 
1250         $this->_helper->json($result);
1251     }
1252 
1253     public function deleteupdateajaxAction()
1254     {
1255         $this->view->authMember = $this->_authMember;
1256         $tableProject = new Default_Model_ProjectUpdates();
1257 
1258         $params = $this->getAllParams();
1259         $project_update_id = $params['update_id'];
1260         $updateArray = array();
1261         $updateArray['public'] = 0;
1262         $updateArray['changed_at'] = new Zend_Db_Expr('Now()');
1263         $tableProject->update($updateArray, 'project_update_id = ' . $project_update_id);
1264 
1265         $result['status'] = 'success';
1266         $result['update_id'] = $project_update_id;
1267 
1268         $this->_helper->json($result);
1269     }
1270 
1271     public function updatesAction()
1272     {
1273         $this->view->authMember = $this->_authMember;
1274         $tableProject = new Default_Model_Project();
1275         $this->view->product = $tableProject->fetchProductInfo($this->_projectId);
1276         if (false === isset($this->view->product)) {
1277             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
1278         }
1279         $this->view->relatedProducts = $tableProject->fetchSimilarProjects($this->view->product, 6);
1280         $this->view->supporter = $tableProject->fetchProjectSupporter($this->_projectId);
1281         $this->view->product_views = $tableProject->fetchProjectViews($this->_projectId);
1282 
1283         $modelPlings = new Default_Model_DbTable_Plings();
1284         $this->view->comments = $modelPlings->getCommentsForProject($this->_projectId, 10);
1285 
1286         $tableMember = new Default_Model_Member();
1287         $this->view->member = $tableMember->fetchMemberData($this->view->product->member_id);
1288 
1289         $this->view->updates = $tableProject->fetchProjectUpdates($this->_projectId);
1290 
1291         $tablePageViews = new Default_Model_DbTable_StatPageViews();
1292         $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(),
1293             $this->_authMember->member_id);
1294     }
1295 
1296     public function updateAction()
1297     {
1298 
1299         $this->_helper->layout()->setLayout('flat_ui');
1300 
1301         $this->view->headScript()->setFile('');
1302         $this->view->headLink()->setStylesheet('');
1303 
1304         $this->_helper->viewRenderer('add');
1305 
1306         $form = new Default_Form_ProjectUpdate();
1307         $projectTable = new Default_Model_Project();
1308         $projectData = null;
1309         $projectUpdateId = (int)$this->getParam('upid');
1310 
1311         $this->view->member = $this->_authMember;
1312         $this->view->title = 'Add an update for your product';
1313 
1314         $activityLogType = Default_Model_ActivityLog::PROJECT_ITEM_CREATED;
1315 
1316         if (false === empty($projectUpdateId)) {
1317             $this->view->title = 'Edit an product update';
1318             $projectData = $projectTable->find($projectUpdateId)->current();
1319             $form->populate($projectData->toArray());
1320             $form->getElement('upid')->setValue($projectUpdateId);
1321             $activityLogType = Default_Model_ActivityLog::PROJECT_ITEM_EDITED;
1322         }
1323 
1324         $this->view->form = $form;
1325 
1326         if ($this->_request->isGet()) {
1327             return;
1328         }
1329 
1330         if (isset($_POST['cancel'])) { // user cancel function
1331             $this->_redirect('/member/' . $this->_authMember->member_id . '/news/');
1332         }
1333 
1334         if (false === $form->isValid($_POST)) { // form not valid
1335             $this->view->form = $form;
1336             $this->view->error = 1;
1337 
1338             return;
1339         }
1340 
1341         $values = $form->getValues();
1342 
1343         $projectUpdateRow = $projectTable->find($values['upid'])->current();
1344 
1345         if (count($projectUpdateRow) == 0) {
1346             $projectUpdateRow = $projectTable->createRow($values);
1347             $projectUpdateRow->project_id = $values['upid'];
1348             $projectUpdateRow->created_at = new Zend_Db_Expr('NOW()');
1349             $projectUpdateRow->start_date = new Zend_Db_Expr('NOW()');
1350             $projectUpdateRow->member_id = $this->_authMember->member_id;
1351             $projectUpdateRow->creator_id = $this->_authMember->member_id;
1352             $projectUpdateRow->status = Default_Model_Project::PROJECT_ACTIVE;
1353             $projectUpdateRow->type_id = 2;
1354             $projectUpdateRow->pid = $this->_projectId;
1355         } else {
1356             $projectUpdateRow->setFromArray($values);
1357             //20180219 ronald: we set the changed_at only by new files or new updates
1358             //$projectUpdateRow->changed_at = new Zend_Db_Expr('NOW()');
1359         }
1360 
1361         $lastId = $projectUpdateRow->save();
1362 
1363         //New Project in Session, for AuthValidation (owner)
1364         $this->_auth->getIdentity()->projects[$lastId] = array('project_id' => $lastId);
1365 
1366         $tableProduct = new Default_Model_Project();
1367         $product = $tableProduct->find($this->_projectId)->current();
1368         $activityLogValues = $projectUpdateRow->toArray();
1369         $activityLogValues['image_small'] = $product->image_small;
1370         $activityLog = new Default_Model_ActivityLog();
1371         //$activityLog->writeActivityLog($lastId, $projectUpdateRow->member_id, $activityLogType, $activityLogValues);
1372         $activityLog->writeActivityLog($lastId, $this->_authMember->member_id, $activityLogType, $activityLogValues);
1373 
1374         $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
1375         $urlProjectShow = $helperBuildProductUrl->buildProductUrl($this->_projectId);
1376 
1377         $this->redirect($urlProjectShow);
1378     }
1379 
1380     public function previewAction()
1381     {
1382         $this->view->authMember = $this->_authMember;
1383 
1384         $form = new Default_Form_ProjectConfirm();
1385 
1386         if ($this->_request->isGet()) {
1387             $form->populate(get_object_vars($this->_authMember));
1388             $this->view->form = $form;
1389             $this->fetchDataForIndexView();
1390             $this->view->preview = $this->view->render('product/index.phtml');
1391 
1392             return;
1393         }
1394 
1395         if (isset($_POST['save'])) {
1396             $projectTable = new Default_Model_Project();
1397             $projectTable->setStatus(Default_Model_Project::PROJECT_INACTIVE, $this->_projectId);
1398 
1399             //todo: maybe we have to delete the project data from database otherwise we produce many zombies
1400             $this->redirect('/member/' . $this->_authMember->member_id . '/products/');
1401         }
1402 
1403         if (isset($_POST['back'])) {
1404             $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
1405             $this->redirect($helperBuildProductUrl->buildProductUrl($this->_projectId, 'edit'));
1406         }
1407 
1408         if (false === $form->isValid($_POST)) { // form not valid
1409             $this->view->form = $form;
1410             $this->fetchDataForIndexView();
1411             $this->view->preview = $this->view->render('product/index.phtml');
1412             $this->view->error = 1;
1413 
1414             return;
1415         }
1416 
1417         $projectTable = new Default_Model_Project();
1418         $projectTable->setStatus(Default_Model_Project::PROJECT_ACTIVE, $this->_projectId);
1419 
1420         // add to search index
1421         $modelProject = new Default_Model_Project();
1422         $productInfo = $modelProject->fetchProductInfo($this->_projectId);
1423         $modelSearch = new Default_Model_Search_Lucene();
1424         $modelSearch->addDocument($productInfo->toArray());
1425 
1426         $this->redirect('/member/' . $this->_authMember->member_id . '/products/');
1427     }
1428 
1429     protected function fetchDataForIndexView()
1430     {
1431         $tableProject = new Default_Model_Project();
1432         $this->view->product = $tableProject->fetchProductInfo($this->_projectId);
1433         if (false === isset($this->view->product)) {
1434             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
1435         }
1436 
1437         $desc = $this->view->product->description;
1438         $newDesc = $this->bbcode2html($desc);
1439         $this->view->product->description = $newDesc;
1440 
1441         // switch off temporally 02.05.2017
1442         //$this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId);
1443         //$orgUpdates = $tableProjectUpdates->fetchLastProjectUpdate($this->_projectId);
1444         $tableProjectUpdates = new Default_Model_ProjectUpdates();
1445         $orgUpdates = $tableProjectUpdates->fetchProjectUpdates($this->_projectId);
1446         $newUpdates = array();
1447         foreach ($orgUpdates as $update) {
1448             $desc = $update['text'];
1449             $newDesc = $this->bbcode2html($desc);
1450             $update['text'] = $newDesc;
1451             $newUpdates[] = $update;
1452         }
1453 
1454         $this->view->updates = $newUpdates;
1455         // switch off temporally 02.05.2017
1456         //$this->view->supporter = $tableProject->fetchProjectSupporter($this->_projectId);
1457 
1458         $this->view->galleryPictures = $tableProject->getGalleryPictureSources($this->_projectId);
1459         $this->view->product_views = $tableProject->fetchProjectViews($this->_projectId);
1460 
1461         $helperFetchCategory = new Default_View_Helper_CatTitle();
1462         $helperFetchCatParent = new Default_View_Helper_CatParent();
1463 
1464         $this->view->catId = $this->view->product->project_category_id;
1465         $this->view->catTitle = $helperFetchCategory->catTitle($this->view->product->project_category_id);
1466         $this->view->catParentId =
1467             $helperFetchCatParent->getCatParentId(array('project_category_id' => $this->view->product->project_category_id));
1468         if ($this->view->catParentId) {
1469             $this->view->catParentTitle = $helperFetchCategory->catTitle($this->view->catParentId);
1470         }
1471 
1472         $AuthCodeExist = new Local_Verification_WebsiteProject();
1473         $this->view->websiteAuthCode = $AuthCodeExist->generateAuthCode(stripslashes($this->view->product->link_1));
1474 
1475         // switch off temporally 02.05.2017
1476         //$modelPlings = new Default_Model_DbTable_Plings();
1477         //$this->view->plings = $modelPlings->getDonationsForProject($this->_projectId, 10);
1478 
1479         $tableMember = new Default_Model_Member();
1480         $this->view->member = $tableMember->fetchMemberData($this->view->product->member_id);
1481 
1482         $this->view->more_products = $tableProject->fetchMoreProjects($this->view->product, 8);
1483         $this->view->more_products_otheruser = $tableProject->fetchMoreProjectsOfOtherUsr($this->view->product, 8);
1484 
1485         $widgetDefaultModel = new Default_Model_DbTable_ProjectWidgetDefault();
1486         $widgetDefault = $widgetDefaultModel->fetchConfig($this->_projectId);
1487         $widgetDefault->text->headline = $this->view->product->title;
1488         //$widgetDefault->amounts->current = $this->view->product->amount_received;
1489         $widgetDefault->amounts->goal = $this->view->product->amount;
1490         $widgetDefault->project = $this->_projectId;
1491         $this->view->widgetConfig = $widgetDefault;
1492 
1493         $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
1494         $this->view->permaLink = $helperBuildProductUrl->buildProductUrl($this->_projectId, null, null, true);
1495         $this->view->urlPay = $helperBuildProductUrl->buildProductUrl($this->_projectId, 'pay');
1496 
1497         $referrerUrl = $this->readExploreUrlFromReferrer();
1498         if (false === empty($referrerUrl)) {
1499             $this->view->referrerUrl = $referrerUrl;
1500         }
1501     }
1502 
1503     /**
1504      * transforms a string with bbcode markup into html
1505      *
1506      * @param string $txt
1507      * @param bool   $nl2br
1508      *
1509      * @return string
1510      */
1511     private function bbcode2html($txt, $nl2br = true, $forcecolor = '')
1512     {
1513 
1514         if (!empty($forcecolor)) {
1515             $fc = ' style="color:' . $forcecolor . ';"';
1516         } else {
1517             $fc = '';
1518         }
1519         $newtxt = htmlspecialchars($txt);
1520         if ($nl2br) {
1521             $newtxt = nl2br($newtxt);
1522         }
1523 
1524         $patterns = array(
1525             '`\[b\](.+?)\[/b\]`is',
1526             '`\[i\](.+?)\[/i\]`is',
1527             '`\[u\](.+?)\[/u\]`is',
1528             '`\[li\](.+?)\[/li\]`is',
1529             '`\[strike\](.+?)\[/strike\]`is',
1530             '`\[url\]([a-z0-9]+?://){1}([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)\[/url\]`si',
1531             '`\[quote\](.+?)\[/quote\]`is',
1532             '`\[indent](.+?)\[/indent\]`is'
1533         );
1534 
1535         $replaces = array(
1536             '<strong' . $fc . '>\\1</strong>',
1537             '<em' . $fc . '>\\1</em>',
1538             '<span style="border-bottom: 1px dotted">\\1</span>',
1539             '<li' . $fc . ' style="margin-left:20px;">\\1</li>',
1540             '<strike' . $fc . '>\\1</strike>',
1541             '<a href="\1\2" rel="nofollow" target="_blank">\1\2</a>',
1542             '<strong' . $fc
1543             . '>Quote:</strong><div style="margin:0px 10px;padding:5px;background-color:#F7F7F7;border:1px dotted #CCCCCC;width:80%;"><em>\1</em></div>',
1544             '<pre' . $fc . '>\\1</pre>'
1545         );
1546 
1547         $newtxt = preg_replace($patterns, $replaces, $newtxt);
1548 
1549         return ($newtxt);
1550     }
1551 
1552     protected function readExploreUrlFromReferrer()
1553     {
1554         $helperBuildExploreUrl = new Default_View_Helper_BuildExploreUrl();
1555         $referrerExplore = $helperBuildExploreUrl->buildExploreUrl(null, null, null, null, true);
1556 
1557         /** @var Zend_Controller_Request_Http $request */
1558         $request = $this->getRequest();
1559         if (strpos($request->getHeader('referer'), $referrerExplore) !== false) {
1560             return $request->getHeader('referer');
1561         }
1562     }
1563 
1564     public function plingAction()
1565     {
1566 
1567         if (empty($this->_projectId)) {
1568             $this->redirect('/explore');
1569         }
1570 
1571         $this->view->authMember = $this->_authMember;
1572 
1573         $this->fetchDataForIndexView();
1574         $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
1575         $this->view->urlPay = $helperBuildProductUrl->buildProductUrl($this->_projectId, 'pay');
1576         $this->view->amount = (float)$this->getParam('amount', 1);
1577         $this->view->comment = html_entity_decode(strip_tags($this->getParam('comment'), null), ENT_QUOTES, 'utf-8');
1578         $this->view->provider =
1579             mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'),
1580                 'utf-8');
1581 
1582         $this->view->headTitle($this->_browserTitlePrepend . $this->view->product->title, 'SET');
1583 
1584         $helperUserIsOwner = new Default_View_Helper_UserIsOwner();
1585         $helperIsProjectActive = new Default_View_Helper_IsProjectActive();
1586         if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status)) AND (false
1587                                                                                                            === $helperUserIsOwner->UserIsOwner($this->view->product->member_id))
1588         ) {
1589             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
1590         }
1591 
1592         $tableProject = new Default_Model_Project();
1593         $this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId);
1594     }
1595 
1596     public function payAction()
1597     {
1598         $this->_helper->layout()->disableLayout();
1599         $tableProject = new Default_Model_Project();
1600         $project = $tableProject->fetchProductInfo($this->_projectId);
1601 
1602         //get parameter
1603         $amount = (float)$this->getParam('amount', 1);
1604         $comment = Default_Model_HtmlPurify::purify($this->getParam('comment'));
1605         $paymentProvider =
1606             mb_strtolower(html_entity_decode(strip_tags($this->getParam('provider'), null), ENT_QUOTES, 'utf-8'),
1607                 'utf-8');
1608         $hideIdentity = (int)$this->getParam('hideId', 0);
1609 
1610         $paymentGateway = $this->createPaymentGateway($paymentProvider);
1611         $paymentGateway->getUserDataStore()->generateFromArray($project->toArray());
1612 
1613         $requestMessage = 'Thank you for supporting: ' . $paymentGateway->getUserDataStore()->getProductTitle();
1614 
1615         $response = null;
1616         try {
1617             $response = $paymentGateway->requestPayment($amount, $requestMessage);
1618             $this->view->checkoutEndpoint = $paymentGateway->getCheckoutEndpoint();
1619             $this->view->paymentKey = $response->getPaymentId();
1620             $this->_helper->viewRenderer->setRender('pay_' . $paymentProvider);
1621         } catch (Exception $e) {
1622             throw new Zend_Controller_Action_Exception('payment error', 500, $e);
1623         }
1624 
1625         if (false === $response->isSuccessful()) {
1626             throw new Zend_Controller_Action_Exception('payment failure', 500);
1627         }
1628 
1629         if (empty($this->_authMember->member_id) or ($hideIdentity == 1)) {
1630             $memberId = 1;
1631         } else {
1632             $memberId = $this->_authMember->member_id;
1633         }
1634 
1635         //Add pling
1636         $modelPlings = new Default_Model_DbTable_Plings();
1637         $plingId = $modelPlings->createNewPlingFromResponse($response, $memberId, $project->project_id, $amount);
1638 
1639         if (false == empty($comment)) {
1640             $modelComments = new Default_Model_ProjectComments();
1641             $dataComment = array(
1642                 'comment_type'      => Default_Model_DbTable_Comments::COMMENT_TYPE_PLING,
1643                 'comment_target_id' => $project->project_id,
1644                 'comment_member_id' => $memberId,
1645                 'comment_pling_id'  => $plingId,
1646                 'comment_text'      => $comment
1647             );
1648             $modelComments->save($dataComment);
1649         }
1650 
1651         $activityLog = new Default_Model_ActivityLog();
1652         $activityLog->writeActivityLog($this->_projectId, $memberId, Default_Model_ActivityLog::PROJECT_PLINGED,
1653             $project->toArray());
1654     }
1655 
1656     /**
1657      * @param string $paymentProvider
1658      *
1659      * @return Local_Payment_GatewayInterface
1660      * @throws Exception
1661      * @throws Local_Payment_Exception
1662      * @throws Zend_Controller_Exception
1663      * @throws Zend_Exception
1664      */
1665     protected function createPaymentGateway($paymentProvider)
1666     {
1667         $httpHost = $this->getRequest()->getHttpHost();
1668         /** @var Zend_Config $config */
1669         $config = Zend_Registry::get('config');
1670         $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
1671         switch ($paymentProvider) {
1672             case 'paypal':
1673                 $paymentGateway = new Default_Model_PayPal_Gateway($config->third_party->paypal);
1674                 $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal');
1675                 //                $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/paypal?XDEBUG_SESSION_START=1');
1676                 $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId,
1677                     'paymentcancel', null, true));
1678                 $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok',
1679                     null, true));
1680                 break;
1681 
1682             case 'dwolla':
1683                 $paymentGateway = new Default_Model_Dwolla_Gateway($config->third_party->dwolla);
1684                 $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/dwolla');
1685                 //                $paymentGateway->setIpnNotificationUrl('http://' . $_SERVER ['HTTP_HOST'] . '/gateway/dwolla?XDEBUG_SESSION_START=1');
1686                 $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'dwolla', null,
1687                     true));
1688                 break;
1689 
1690             case 'amazon':
1691                 $paymentGateway = new Default_Model_Amazon_Gateway($config->third_party->amazon);
1692                 $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon');
1693                 //                $paymentGateway->setIpnNotificationUrl('http://' . $httpHost . '/gateway/amazon?XDEBUG_SESSION_START=1');
1694                 $paymentGateway->setCancelUrl($helperBuildProductUrl->buildProductUrl($this->_projectId,
1695                     'paymentcancel', null, true));
1696                 $paymentGateway->setReturnUrl($helperBuildProductUrl->buildProductUrl($this->_projectId, 'paymentok',
1697                     null, true));
1698                 break;
1699 
1700             default:
1701                 throw new Zend_Controller_Exception('No known payment provider found in parameters.');
1702                 break;
1703         }
1704 
1705         return $paymentGateway;
1706     }
1707 
1708     public function dwollaAction()
1709     {
1710         $modelPling = new Default_Model_DbTable_Plings();
1711         $plingData = $modelPling->fetchRow(array('payment_reference_key = ?' => $this->getParam('checkoutId')));
1712         $plingData->payment_transaction_id = (int)$this->getParam('transaction');
1713         $plingData->save();
1714 
1715         if ($this->_getParam('status') == 'Completed') {
1716             $this->_helper->viewRenderer('paymentok');
1717             $this->paymentokAction();
1718         } else {
1719             $this->_helper->viewRenderer('paymentcancel');
1720             $this->paymentcancelAction();
1721         }
1722     }
1723 
1724     public function paymentokAction()
1725     {
1726         $this->_helper->layout()->disableLayout();
1727         $this->view->paymentStatus = 'success';
1728         $this->view->paymentMessage = 'Payment successful.';
1729         $this->fetchDataForIndexView();
1730     }
1731 
1732     public function paymentcancelAction()
1733     {
1734         $this->_helper->layout()->disableLayout();
1735         $this->view->paymentStatus = 'danger';
1736         $this->view->paymentMessage = 'Payment cancelled.';
1737         $this->fetchDataForIndexView();
1738     }
1739 
1740     public function deleteAction()
1741     {
1742         $this->_helper->layout()->setLayout('flat_ui');
1743 
1744         $memberId = (int)$this->getParam('m');
1745 
1746         if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id
1747                                                                              != $memberId)
1748         ) {
1749             $this->forward('products', 'user', 'default');
1750 
1751             return;
1752         }
1753 
1754         $tableProduct = new Default_Model_Project();
1755         $tableProduct->setDeleted($this->_authMember->member_id, $this->_projectId);
1756 
1757         $product = $tableProduct->find($this->_projectId)->current();
1758 
1759         // ppload
1760         // Delete collection
1761         if ($product->ppload_collection_id) {
1762             $pploadApi = new Ppload_Api(array(
1763                 'apiUri'   => PPLOAD_API_URI,
1764                 'clientId' => PPLOAD_CLIENT_ID,
1765                 'secret'   => PPLOAD_SECRET
1766             ));
1767 
1768             $collectionResponse = $pploadApi->deleteCollection($product->ppload_collection_id);
1769         }
1770 
1771         $activityLog = new Default_Model_ActivityLog();
1772         $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
1773             Default_Model_ActivityLog::PROJECT_DELETED,
1774             $product->toArray());
1775 
1776         $this->forward('products', 'user', 'default');
1777     }
1778 
1779     public function unpublishAction()
1780     {
1781         $this->_helper->layout()->setLayout('flat_ui');
1782 
1783         $memberId = (int)$this->getParam('m');
1784 
1785         if (
1786             (empty($this->_authMember->member_id))
1787             OR
1788             (empty($memberId))
1789             OR ($this->_authMember->member_id != $memberId)
1790         ) {
1791             return;
1792         }
1793 
1794         $tableProduct = new Default_Model_Project();
1795         $tableProduct->setInActive($this->_projectId, $memberId);
1796 
1797         $product = $tableProduct->find($this->_projectId)->current();
1798 
1799         if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) {
1800             $parentProduct = $tableProduct->find($product->pid)->current();
1801             $product->image_small = $parentProduct->image_small;
1802         }
1803 
1804         $activityLog = new Default_Model_ActivityLog();
1805         $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
1806             Default_Model_ActivityLog::PROJECT_UNPUBLISHED,
1807             $product->toArray());
1808 
1809         // remove unpublished project from search index
1810         $modelSearch = new Default_Model_Search_Lucene();
1811         $modelSearch->deleteDocument($product);
1812 
1813         // ppload
1814         if ($product->ppload_collection_id) {
1815             $pploadApi = new Ppload_Api(array(
1816                 'apiUri'   => PPLOAD_API_URI,
1817                 'clientId' => PPLOAD_CLIENT_ID,
1818                 'secret'   => PPLOAD_SECRET
1819             ));
1820             // Update collection information
1821             $collectionRequest = array(
1822                 'category' => $product->project_category_id
1823             );
1824 
1825             $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest);
1826         }
1827 
1828         $this->forward('products', 'user', 'default', array('member_id' => $memberId));
1829         //$this->redirect('/member/'.$memberId.'/products');
1830     }
1831 
1832     public function publishAction()
1833     {
1834         $memberId = (int)$this->getParam('m');
1835 
1836         if ((empty($this->_authMember->member_id)) OR (empty($memberId)) OR ($this->_authMember->member_id
1837                                                                              != $memberId)
1838         ) {
1839             return;
1840         }
1841 
1842         $tableProduct = new Default_Model_Project();
1843         $tableProduct->setActive($this->_authMember->member_id, $this->_projectId);
1844 
1845         $product = $tableProduct->find($this->_projectId)->current();
1846 
1847         if (isset($product->type_id) && $product->type_id == Default_Model_Project::PROJECT_TYPE_UPDATE) {
1848             $parentProduct = $tableProduct->find($product->pid)->current();
1849             $product->image_small = $parentProduct->image_small;
1850         }
1851 
1852         $activityLog = new Default_Model_ActivityLog();
1853         $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
1854             Default_Model_ActivityLog::PROJECT_PUBLISHED,
1855             $product->toArray());
1856 
1857         // ppload
1858         if ($product->ppload_collection_id) {
1859             $pploadApi = new Ppload_Api(array(
1860                 'apiUri'   => PPLOAD_API_URI,
1861                 'clientId' => PPLOAD_CLIENT_ID,
1862                 'secret'   => PPLOAD_SECRET
1863             ));
1864             // Update collection information
1865             $collectionRequest = array(
1866                 'category' => $product->project_category_id . '-published'
1867             );
1868 
1869             $collectionResponse = $pploadApi->putCollection($product->ppload_collection_id, $collectionRequest);
1870         }
1871 
1872         $this->forward('products', 'user', 'default', array('member_id' => $memberId));
1873         //$this->redirect('/member/'.$memberId.'/products');
1874     }
1875 
1876     public function loadratingsAction()
1877     {
1878         $this->_helper->layout->disableLayout();
1879         $tableProjectRatings = new Default_Model_DbTable_ProjectRating();
1880         $ratings = $tableProjectRatings->fetchRating($this->_projectId);
1881         $this->_helper->json($ratings);
1882     }
1883 
1884     public function loadcommentAction()
1885     {
1886         $this->_helper->layout->disableLayout();
1887         $this->view->comments = $this->loadComments(1, $this->_projectId, 0);
1888         $tableProject = new Default_Model_Project();
1889         $project = $tableProject->fetchProductInfo($this->_projectId);
1890         $this->view->product = $project;
1891         $this->view->member_id = (int)$this->_authMember->member_id;
1892         $requestResult = $this->view->render('product/partials/productCommentsUX1.phtml');
1893         $this->_helper->json(array('status' => 'ok', 'data' => $requestResult));
1894 
1895     }
1896 
1897     private function loadComments($page_offset, $project_id, $comment_type)
1898     {
1899         $modelComments = new Default_Model_ProjectComments();
1900         $paginationComments = $modelComments->getCommentTreeForProject($project_id, $comment_type);
1901         $paginationComments->setItemCountPerPage(25);
1902         $paginationComments->setCurrentPageNumber($page_offset);
1903 
1904         return $paginationComments;
1905     }
1906 
1907     public function loadtagratingAction()
1908     {
1909         $this->_helper->layout->disableLayout();
1910         //$tableProjectRatings = new Default_Model_DbTable_ProjectRating();
1911         //$ratings = $tableProjectRatings->fetchTagRating($this->_projectId);
1912         $category_id = $this->getParam('gid');
1913         $model = new Default_Model_ProjectTagRatings();
1914         $ratingsLabel = $model->getCategoryTagRatings($category_id);
1915         $ratingsValue = null;
1916         if ($ratingsLabel != null && sizeof($ratingsLabel) > 0) {
1917             $ratingsValue = $model->getProjectTagRatings($this->_projectId);
1918         }
1919 
1920         $this->_helper->json(array(
1921             'status' => 'ok',
1922             'labels' => $ratingsLabel,
1923             'values' => $ratingsValue
1924         ));
1925     }
1926 
1927     public function votetagratingAction()
1928     {
1929         $this->_helper->layout->disableLayout();
1930         $vote = $this->getParam('vote');
1931         $tag_id = $this->getParam('tid');
1932         $msg = $this->getParam('msg');
1933         if (strlen($msg) < 1) {
1934             $this->_helper->json(array(
1935                 'status' => 'error',
1936                 'msg'    => 'Please add a comment.'
1937             ));
1938 
1939             return;
1940         };
1941 
1942         $model = new Default_Model_ProjectTagRatings();
1943         if ($this->_authMember->member_id) {
1944             $checkVote = $model->checkIfVote($this->_authMember->member_id, $this->_projectId, $tag_id);
1945             if (!$checkVote) {
1946                 $model->doVote($this->_authMember->member_id, $this->_projectId, $tag_id, $vote, $msg);
1947             } else {
1948                 if ($checkVote['vote'] == $vote) {
1949                     $model->removeVote($checkVote['tag_rating_id']);
1950                 } else {
1951                     $model->removeVote($checkVote['tag_rating_id']);
1952                     $model->doVote($this->_authMember->member_id, $this->_projectId, $tag_id, $vote, $msg);
1953                 }
1954             }
1955 
1956             $this->_helper->json(array(
1957                 'status' => 'ok'
1958             ));
1959         } else {
1960             $this->_helper->json(array(
1961                 'status' => 'error',
1962                 'msg'    => 'Login please'
1963             ));
1964         }
1965     }
1966 
1967     public function loadfilesjsonAction()
1968     {
1969         $this->_helper->layout->disableLayout();
1970         // $project_id = $this->getParam('pid');
1971         $modelProject = new Default_Model_Project();
1972         $files = $modelProject->fetchFilesForProject($this->_projectId);
1973         $salt = PPLOAD_DOWNLOAD_SECRET;
1974         foreach ($files as &$file) {
1975             $timestamp = time() + 3600; // one hour valid
1976             $hash = hash('sha512',
1977                 $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying
1978             $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp;
1979             if (null != $this->_authMember && null != $this->_authMember->member_id) {
1980                 $url .= '/u/' . $this->_authMember->member_id;
1981             }
1982             $url .= '/lt/filepreview/' . $file['name'];
1983 
1984             $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview');
1985             $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload);
1986 
1987             $file['url'] = urlencode($url);
1988         }
1989         $this->_helper->json($files);
1990     }
1991 
1992     public function loadfirstfilejsonAction()
1993     {
1994         $this->_helper->layout->disableLayout();
1995         // $project_id = $this->getParam('pid');
1996         $modelProject = new Default_Model_Project();
1997         $files = $modelProject->fetchFilesForProject($this->_projectId);
1998         $salt = PPLOAD_DOWNLOAD_SECRET;
1999         $file = $files[0];
2000 
2001         $timestamp = time() + 3600; // one hour valid
2002         $hash = hash('sha512',
2003             $salt . $file['collection_id'] . $timestamp); // order isn't important at all... just do the same when verifying
2004         $url = PPLOAD_API_URI . 'files/download/id/' . $file['id'] . '/s/' . $hash . '/t/' . $timestamp;
2005         if (null != $this->_authMember) {
2006             $url .= '/u/' . $this->_authMember->member_id;
2007         }
2008         $url .= '/lt/filepreview/' . $file['name'];
2009 
2010         $payload = array('id' => $file['id'], 'u' => $this->_authMember->member_id, 'lt' => 'filepreview');
2011         $url = Default_Model_PpLoad::createDownloadUrlJwt($file['collection_id'], $file['name'], $payload);
2012 
2013         $file['url'] = urlencode($url);
2014 
2015         $this->_helper->json($file);
2016     }
2017 
2018     public function loadinstallinstructionAction()
2019     {
2020         $this->_helper->layout->disableLayout();
2021         $infomodel = new Default_Model_Info();
2022         $text = $infomodel->getOCSInstallInstruction();
2023 
2024 
2025         $this->_helper->json(array(
2026             'status' => 'ok',
2027             'data'   => $text
2028         ));
2029     }
2030 
2031     public function followAction()
2032     {
2033         $this->_helper->layout()->disableLayout();
2034         //        $this->_helper->viewRenderer->setNoRender(true);
2035 
2036         $this->view->project_id = $this->_projectId;
2037         $this->view->authMember = $this->_authMember;
2038 
2039         if (array_key_exists($this->_projectId, $this->_authMember->projects)) {
2040             return;
2041         }
2042 
2043         $projectFollowTable = new Default_Model_DbTable_ProjectFollower();
2044 
2045         $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id);
2046         $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id)
2047                                     ->where('project_id = ?', $this->_projectId, 'INTEGER');
2048         $result = $projectFollowTable->fetchRow($where);
2049 
2050         if (null === $result) {
2051             $projectFollowTable->createRow($newVals)->save();
2052             $tableProduct = new Default_Model_Project();
2053             $product = $tableProduct->find($this->_projectId)->current();
2054 
2055             $activityLog = new Default_Model_ActivityLog();
2056             $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
2057                 Default_Model_ActivityLog::PROJECT_FOLLOWED, $product->toArray());
2058         }
2059     }
2060 
2061     public function unfollowAction()
2062     {
2063         $this->_helper->layout()->disableLayout();
2064         $this->_helper->viewRenderer('follow');
2065 
2066         $this->view->project_id = $this->_projectId;
2067         $this->view->authMember = $this->_authMember;
2068 
2069         $projectFollowTable = new Default_Model_DbTable_ProjectFollower();
2070 
2071         $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id='
2072                                     . $this->_projectId);
2073 
2074 
2075         $tableProduct = new Default_Model_Project();
2076         $product = $tableProduct->find($this->_projectId)->current();
2077 
2078         $activityLog = new Default_Model_ActivityLog();
2079         $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
2080             Default_Model_ActivityLog::PROJECT_UNFOLLOWED, $product->toArray());
2081     }
2082 
2083     public function followpAction()
2084     {
2085         $this->_helper->layout()->disableLayout();
2086         //        $this->_helper->viewRenderer->setNoRender(true);
2087 
2088         $this->view->project_id = $this->_projectId;
2089         $this->view->authMember = $this->_authMember;
2090 
2091         if (array_key_exists($this->_projectId, $this->_authMember->projects)) {
2092             return;
2093         }
2094 
2095         $projectFollowTable = new Default_Model_DbTable_ProjectFollower();
2096 
2097         $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id);
2098         $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id)
2099                                     ->where('project_id = ?', $this->_projectId, 'INTEGER');
2100         $result = $projectFollowTable->fetchRow($where);
2101 
2102         if (null === $result) {
2103             $projectFollowTable->createRow($newVals)->save();
2104             $tableProduct = new Default_Model_Project();
2105             $product = $tableProduct->find($this->_projectId)->current();
2106             $activityLog = new Default_Model_ActivityLog();
2107             $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
2108                 Default_Model_ActivityLog::PROJECT_FOLLOWED, $product->toArray());
2109         }
2110     }
2111 
2112     public function unfollowpAction()
2113     {
2114         $this->_helper->layout()->disableLayout();
2115         $this->_helper->viewRenderer('followp');
2116 
2117         $this->view->project_id = $this->_projectId;
2118         $this->view->authMember = $this->_authMember;
2119 
2120         $projectFollowTable = new Default_Model_DbTable_ProjectFollower();
2121 
2122         $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id='
2123                                     . $this->_projectId);
2124 
2125 
2126         $tableProduct = new Default_Model_Project();
2127         $product = $tableProduct->find($this->_projectId)->current();
2128 
2129         $activityLog = new Default_Model_ActivityLog();
2130         $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
2131             Default_Model_ActivityLog::PROJECT_UNFOLLOWED, $product->toArray());
2132 
2133     }
2134 
2135     public function followprojectAction()
2136     {
2137         $this->_helper->layout()->disableLayout();
2138 
2139         $this->view->project_id = $this->_projectId;
2140         $this->view->authMember = $this->_authMember;
2141 
2142         // not allow to pling himself
2143         if (array_key_exists($this->_projectId, $this->_authMember->projects)) {
2144             $this->_helper->json(array(
2145                 'status' => 'error',
2146                 'msg'    => 'not allowed'
2147             ));
2148 
2149             return;
2150         }
2151 
2152 
2153         $projectFollowTable = new Default_Model_DbTable_ProjectFollower();
2154 
2155         $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id);
2156         $where = $projectFollowTable->select()->where('member_id = ?', $this->_authMember->member_id)
2157                                     ->where('project_id = ?', $this->_projectId, 'INTEGER');
2158 
2159         $result = $projectFollowTable->fetchRow($where);
2160 
2161         if (null === $result) {
2162             $projectFollowTable->createRow($newVals)->save();
2163             $this->logActivity(Default_Model_ActivityLog::PROJECT_FOLLOWED);
2164             $cnt = $projectFollowTable->countForProject($this->_projectId);
2165             $this->_helper->json(array(
2166                 'status' => 'ok',
2167                 'msg'    => 'Success.',
2168                 'cnt'    => $cnt,
2169                 'action' => 'insert'
2170             ));
2171         } else {
2172             $projectFollowTable->delete('member_id=' . $this->_authMember->member_id . ' AND project_id='
2173                                         . $this->_projectId);
2174             $this->logActivity(Default_Model_ActivityLog::PROJECT_UNFOLLOWED);
2175             $cnt = $projectFollowTable->countForProject($this->_projectId);
2176             $this->_helper->json(array(
2177                 'status' => 'ok',
2178                 'msg'    => 'Success.',
2179                 'cnt'    => $cnt,
2180                 'action' => 'delete'
2181             ));
2182         }
2183 
2184     }
2185 
2186     protected function logActivity($logId)
2187     {
2188         $tableProduct = new Default_Model_Project();
2189         $product = $tableProduct->find($this->_projectId)->current();
2190         $activityLog = new Default_Model_ActivityLog();
2191         $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
2192             $logId, $product->toArray());
2193     }
2194 
2195     public function plingprojectAction()
2196     {
2197         $this->_helper->layout()->disableLayout();
2198 
2199         $this->view->project_id = $this->_projectId;
2200         $this->view->authMember = $this->_authMember;
2201 
2202         // not allow to pling himself
2203         if (array_key_exists($this->_projectId, $this->_authMember->projects)) {
2204             $this->_helper->json(array(
2205                 'status' => 'error',
2206                 'msg'    => 'not allowed'
2207             ));
2208 
2209             return;
2210         }
2211 
2212         // not allow to pling if not supporter
2213         $helperIsSupporter = new Default_View_Helper_IsSupporter();
2214         if (!$helperIsSupporter->isSupporter($this->_authMember->member_id)) {
2215             $this->_helper->json(array(
2216                 'status' => 'error',
2217                 'msg'    => 'become a supporter first please. '
2218             ));
2219 
2220             return;
2221         }
2222 
2223 
2224         $projectplings = new Default_Model_ProjectPlings();
2225 
2226         $newVals = array('project_id' => $this->_projectId, 'member_id' => $this->_authMember->member_id);
2227         $sql = $projectplings->select()
2228                              ->where('member_id = ?', $this->_authMember->member_id)
2229                              ->where('is_deleted = ?', 0)
2230                              ->where('project_id = ?', $this->_projectId, 'INTEGER');
2231         $result = $projectplings->fetchRow($sql);
2232 
2233         if (null === $result) {
2234             $projectplings->createRow($newVals)->save();
2235             //$this->logActivity(Default_Model_ActivityLog::PROJECT_PLINGED_2);
2236 
2237             $cnt = $projectplings->getPlingsAmount($this->_projectId);
2238             $this->_helper->json(array(
2239                 'status' => 'ok',
2240                 'msg'    => 'Success.',
2241                 'cnt'    => $cnt,
2242                 'action' => 'insert'
2243             ));
2244         } else {
2245 
2246             // delete pling
2247             $projectplings->setDelete($result->project_plings_id);
2248             //$this->logActivity(Default_Model_ActivityLog::PROJECT_DISPLINGED_2);
2249 
2250             $cnt = $projectplings->getPlingsAmount($this->_projectId);
2251             $this->_helper->json(array(
2252                 'status' => 'ok',
2253                 'msg'    => 'Success.',
2254                 'cnt'    => $cnt,
2255                 'action' => 'delete'
2256             ));
2257         }
2258 
2259     }
2260 
2261     /**
2262      *
2263      * public function unplingprojectAction()
2264      * {
2265      * $this->_helper->layout()->disableLayout();
2266      *
2267      * $projectplings = new Default_Model_ProjectPlings();
2268      * $pling = $projectplings->getPling($this->_projectId,$this->_authMember->member_id);
2269      *
2270      * if($pling)
2271      * {
2272      * $projectplings->setDelete($pling->project_plings_id);
2273      * $cnt = count($projectplings->getPlings($this->_projectId));
2274      * $this->_helper->json(array(
2275      * 'status' => 'ok',
2276      * 'deleted' => $pling->project_plings_id,
2277      * 'msg'   => 'Success. ',
2278      * 'cnt'  => $cnt
2279      * ));
2280      *
2281      * $tableProduct = new Default_Model_Project();
2282      * $product = $tableProduct->find($this->_projectId)->current();
2283      *
2284      * $activityLog = new Default_Model_ActivityLog();
2285      * $activityLog->writeActivityLog($this->_projectId, $this->_authMember->member_id,
2286      * Default_Model_ActivityLog::PROJECT_DISPLINGED_2, $product->toArray());
2287      * }else{
2288      * $this->_helper->json(array(
2289      * 'status' => 'error',
2290      * 'msg'   => 'not existing.'
2291      * ));
2292      * }
2293      *
2294      *
2295      * }
2296      **/
2297 
2298     public function followsAction()
2299     {
2300         $projectFollowTable = new Default_Model_Member();
2301 
2302         $memberId = $this->_authMember->member_id;
2303         $this->view->productList = $projectFollowTable->fetchFollowedProjects($memberId);
2304 
2305         $projectArray = $this->generateFollowedProjectsViewData($this->view->productList);
2306 
2307         $this->view->productArray['followedProjects'] = $projectArray;
2308     }
2309 
2310     /**
2311      * @param $list
2312      *
2313      * @return array
2314      */
2315     protected function generateFollowedProjectsViewData($list)
2316     {
2317         $viewArray = array();
2318 
2319         if (count($list) == 0) {
2320             return $viewArray;
2321         }
2322 
2323         $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
2324         foreach ($list as $element) {
2325             $arr = array();
2326             $arr['id'] = $element->project_id;
2327             $arr['name'] = $element->title;
2328             $arr['image'] = $element->image_small;
2329             $arr['url'] = $helperBuildProductUrl->buildProductUrl($element->project_id);
2330             $arr['urlUnFollow'] = $helperBuildProductUrl->buildProductUrl($element->project_id, 'unfollow');
2331             #$arr['showUrlUnFollow'] = $this->view->isMember;
2332 
2333             $viewArray[] = $arr;
2334         }
2335 
2336         return $viewArray;
2337     }
2338 
2339     public function verifycodeAction()
2340     {
2341         $this->_helper->layout()->disableLayout();
2342 
2343         if ($this->_request->isXmlHttpRequest()) {
2344             $tabProject = new Default_Model_DbTable_Project();
2345             $dataProject = $tabProject->find($this->_projectId)->current();
2346             $this->createTaskWebsiteOwnerVerification($dataProject);
2347             $this->view->message = 'Your product page is stored for validation.';
2348 
2349             return;
2350         }
2351 
2352         $this->view->message = 'This service is not available at the moment. Please try again later.';
2353     }
2354 
2355     /**
2356      * @param $projectData
2357      *
2358      * @throws Zend_Exception
2359      * @throws Zend_Queue_Exception
2360      */
2361     protected function createTaskWebsiteOwnerVerification($projectData)
2362     {
2363         if (empty($projectData->link_1)) {
2364             return;
2365         }
2366         $checkAuthCode = new Local_Verification_WebsiteProject();
2367         $authCode = $checkAuthCode->generateAuthCode(stripslashes($projectData->link_1));
2368         $queue = Local_Queue_Factory::getQueue();
2369         $command = new Backend_Commands_CheckProjectWebsite($projectData->project_id, $projectData->link_1, $authCode);
2370         $queue->send(serialize($command));
2371     }
2372 
2373     /**
2374      * @throws Zend_Controller_Action_Exception
2375      * @deprecated
2376      */
2377     public function fetchAction()
2378     {
2379         $this->_helper->layout()->disableLayout();
2380 
2381         if ($this->_request->isXmlHttpRequest()) {
2382             $this->view->authMember = $this->_authMember;
2383 
2384             $this->fetchDataForIndexView();
2385             $tableProject = new Default_Model_Project();
2386             $this->view->supporting = $tableProject->fetchProjectSupporterWithPlings($this->_projectId);
2387 
2388             if (false === isset($this->view->product)) {
2389                 throw new Zend_Controller_Action_Exception('This page does not exist', 404);
2390             }
2391 
2392             $helperUserIsOwner = new Default_View_Helper_UserIsOwner();
2393             $helperIsProjectActive = new Default_View_Helper_IsProjectActive();
2394             if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status))
2395                 AND
2396                 (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id))
2397             ) {
2398                 throw new Zend_Controller_Action_Exception('This page does not exist', 404);
2399             }
2400 
2401             $tablePageViews = new Default_Model_DbTable_StatPageViews();
2402             $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(),
2403                 $this->_authMember->member_id);
2404         }
2405 
2406         $this->_helper->json(get_object_vars($this->view));
2407     }
2408 
2409     public function claimAction()
2410     {
2411         $modelProduct = new Default_Model_Project();
2412         $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
2413         if ($productInfo->claimable != Default_Model_Project::PROJECT_CLAIMABLE) {
2414             throw new Zend_Controller_Action_Exception('Method not available', 404);
2415         }
2416         $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
2417         if (empty($productInfo->claimed_by_member)) {
2418             $modelProduct->setClaimedByMember($this->_authMember->member_id, $this->_projectId);
2419 
2420             $claimMail = new Default_Plugin_SendMail('tpl_mail_claim_product');
2421             $claimMail->setTemplateVar('sender', $this->_authMember->mail);
2422             $claimMail->setTemplateVar('productid', $productInfo->project_id);
2423             $claimMail->setTemplateVar('producttitle', $productInfo->title);
2424             $claimMail->setTemplateVar('userid', $this->_authMember->member_id);
2425             $claimMail->setTemplateVar('username', $this->_authMember->username);
2426             $claimMail->setTemplateVar('usermail', $this->_authMember->mail);
2427             $claimMail->setReceiverMail(array('contact@opendesktop.org'));
2428             $claimMail->send();
2429 
2430             $claimMailConfirm = new Default_Plugin_SendMail('tpl_mail_claim_confirm');
2431             $claimMailConfirm->setTemplateVar('sender', 'contact@opendesktop.org');
2432             $claimMailConfirm->setTemplateVar('producttitle', $productInfo->title);
2433             $claimMailConfirm->setTemplateVar('productlink', 'http://' . $this->getRequest()->getHttpHost()
2434                                                              . $helperBuildProductUrl->buildProductUrl($productInfo->project_id));
2435             $claimMailConfirm->setTemplateVar('username', $this->_authMember->username);
2436             $claimMailConfirm->setReceiverMail($this->_authMember->mail);
2437             $claimMailConfirm->send();
2438         }
2439 
2440         $this->_helper->viewRenderer('index');
2441         $this->indexAction();
2442     }
2443 
2444     public function makerconfigAction()
2445     {
2446         $this->_helper->layout()->disableLayout();
2447 
2448         $widgetProjectId = (int)$this->getParam('project_id');
2449         if (false == isset($widgetProjectId)) {
2450             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
2451         }
2452         $widgetDefaultModel = new Default_Model_DbTable_ProjectWidgetDefault();
2453         $widgetDefault = $widgetDefaultModel->fetchConfig($widgetProjectId);
2454         if (!isset($widgetDefault)) {
2455             throw new Zend_Controller_Action_Exception('This page does not exist', 404);
2456         } else {
2457             $this->view->widgetConfig = $widgetDefault;
2458             $productModel = new Default_Model_Project();
2459             $this->view->product = $productModel->fetchProductDataFromMV($widgetProjectId);
2460             $this->view->supporting = $productModel->fetchProjectSupporterWithPlings($widgetProjectId);
2461             $plingModel = new Default_Model_DbTable_Plings();
2462             $this->view->comments = $plingModel->getCommentsForProject($widgetProjectId, 10);
2463             $websiteOwner = new Local_Verification_WebsiteProject();
2464             $this->view->authCode = '<meta name="ocs-site-verification" content="'
2465                                     . $websiteOwner->generateAuthCode(stripslashes($this->view->product->link_1)) . '" />';
2466         }
2467     }
2468 
2469     /**
2470      * ppload
2471      */
2472     public function addpploadfileAction()
2473     {
2474         $this->_helper->layout()->disableLayout();
2475         $log = Zend_Registry::get('logger');
2476         $log->debug('**********' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n");
2477 
2478         $projectTable = new Default_Model_DbTable_Project();
2479         $projectData = $projectTable->find($this->_projectId)->current();
2480 
2481         $error_text = '';
2482 
2483         // Add file to ppload collection
2484         if (!empty($_FILES['file_upload']['tmp_name'])
2485             && $_FILES['file_upload']['error'] == UPLOAD_ERR_OK
2486         ) {
2487             $tmpFilename = dirname($_FILES['file_upload']['tmp_name']) . '/' . basename($_FILES['file_upload']['name']);
2488             $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($tmpFilename, true) . "\n");
2489             move_uploaded_file($_FILES['file_upload']['tmp_name'], $tmpFilename);
2490 
2491             $pploadApi = new Ppload_Api(array(
2492                 'apiUri'   => PPLOAD_API_URI,
2493                 'clientId' => PPLOAD_CLIENT_ID,
2494                 'secret'   => PPLOAD_SECRET
2495             ));
2496 
2497             $fileRequest = array(
2498                 'file'     => $tmpFilename,
2499                 'owner_id' => $this->_authMember->member_id
2500             );
2501 
2502             //Admins can upload files for users
2503             $helperUserRole = new Backend_View_Helper_UserRole();
2504             $userRoleName = $helperUserRole->userRole();
2505             if (Default_Model_DbTable_MemberRole::ROLE_NAME_ADMIN == $userRoleName) {
2506                 $member_id = $projectData->member_id;
2507                 $fileRequest = array(
2508                     'file'     => $tmpFilename,
2509                     'owner_id' => $member_id
2510                 );
2511             }
2512 
2513             if ($projectData->ppload_collection_id) {
2514                 // Append to existing collection
2515                 $fileRequest['collection_id'] = $projectData->ppload_collection_id;
2516             }
2517             //if (isset($_POST['file_description'])) {
2518             //  $fileRequest['description'] = mb_substr($_POST['file_description'], 0, 140);
2519             //}
2520             $fileResponse = $pploadApi->postFile($fileRequest);
2521             $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($fileResponse, true) . "\n");
2522 
2523             unlink($tmpFilename);
2524 
2525             if (!empty($fileResponse->file->collection_id)) {
2526                 if (!$projectData->ppload_collection_id) {
2527                     // Save collection ID
2528                     $projectData->ppload_collection_id = $fileResponse->file->collection_id;
2529                     //20180219 ronald: we set the changed_at only by new files or new updates
2530                     if ((int)$this->_authMember->member_id == (int)$projectData->member_id) {
2531                         $projectData->changed_at = new Zend_Db_Expr('NOW()');
2532                     } else {
2533                         $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n");
2534                     }
2535                     $projectData->ghns_excluded = 0;
2536                     $projectData->save();
2537 
2538                     $activityLog = new Default_Model_ActivityLog();
2539                     $activityLog->writeActivityLog($this->_projectId, $projectData->member_id,
2540                         Default_Model_ActivityLog::PROJECT_EDITED, $projectData->toArray());
2541                     // Update profile information
2542                     $memberTable = new Default_Model_DbTable_Member();
2543                     $memberSettings = $memberTable->find($this->_authMember->member_id)->current();
2544                     $mainproject = $projectTable->find($memberSettings->main_project_id)->current();
2545                     $profileName = '';
2546                     if ($memberSettings->firstname
2547                         || $memberSettings->lastname
2548                     ) {
2549                         $profileName = trim($memberSettings->firstname . ' ' . $memberSettings->lastname);
2550                     } else {
2551                         if ($memberSettings->username) {
2552                             $profileName = $memberSettings->username;
2553                         }
2554                     }
2555                     $profileRequest = array(
2556                         'owner_id'    => $this->_authMember->member_id,
2557                         'name'        => $profileName,
2558                         'email'       => $memberSettings->mail,
2559                         'homepage'    => $memberSettings->link_website,
2560                         'description' => $mainproject->description
2561                     );
2562                     $profileResponse = $pploadApi->postProfile($profileRequest);
2563                     // Update collection information
2564                     $collectionCategory = $projectData->project_category_id;
2565                     if (Default_Model_Project::PROJECT_ACTIVE == $projectData->status) {
2566                         $collectionCategory .= '-published';
2567                     }
2568                     $collectionRequest = array(
2569                         'title'       => $projectData->title,
2570                         'description' => $projectData->description,
2571                         'category'    => $collectionCategory,
2572                         'content_id'  => $projectData->project_id
2573                     );
2574                     $collectionResponse =
2575                         $pploadApi->putCollection($projectData->ppload_collection_id, $collectionRequest);
2576                     // Store product image as collection thumbnail
2577                     $this->_updatePploadMediaCollectionthumbnail($projectData);
2578                 } else {
2579                     //20180219 ronald: we set the changed_at only by new files or new updates
2580                     if ((int)$this->_authMember->member_id == (int)$projectData->member_id) {
2581                         $projectData->changed_at = new Zend_Db_Expr('NOW()');
2582                     } else {
2583                         $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n");
2584                     }
2585                     $projectData->ghns_excluded = 0;
2586                     $projectData->save();
2587                 }
2588 
2589                 //If this file is a video, we have to convert it for preview
2590                 if (!empty($fileResponse->file->type) && in_array($fileResponse->file->type,
2591                         Backend_Commands_ConvertVideo::$VIDEO_FILE_TYPES)) {
2592                     $queue = Local_Queue_Factory::getQueue();
2593                     $command = new Backend_Commands_ConvertVideo($projectData->ppload_collection_id,
2594                         $fileResponse->file->id, $fileResponse->file->type);
2595                     $queue->send(serialize($command));
2596                 }
2597 
2598                 //If this file is bigger than XXX MB (see application.ini), then create a webtorrent file
2599                 $config = Zend_Registry::get('config');
2600                 $minFileSize = $config->torrent->media->min_filesize;
2601                 if (!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) {
2602                     $queue = Local_Queue_Factory::getQueue();
2603                     $command = new Backend_Commands_CreateTorrent($fileResponse->file);
2604                     $queue->send(serialize($command));
2605                 }
2606 
2607                 //If this is a cbr or cbz comic archive, then start an extracting job
2608                 if ($this->endsWith($fileResponse->file->name, '.cbr') || $this->endsWith($fileResponse->file->name,
2609                         '.cbz')) {
2610                     $queue = Local_Queue_Factory::getQueue();
2611                     $command = new Backend_Commands_ExtractComic($fileResponse->file);
2612                     $queue->send(serialize($command));
2613                 }
2614 
2615                 $this->_helper->json(array(
2616                     'status' => 'ok',
2617                     'file'   => $fileResponse->file
2618                 ));
2619 
2620                 return;
2621             }
2622         }
2623 
2624         $log->debug('********** END ' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n");
2625         $this->_helper->json(array('status' => 'error', 'error_text' => $error_text));
2626     }
2627 
2628     private function endsWith($haystack, $needle)
2629     {
2630         return $needle === "" || substr(strtolower($haystack), -strlen($needle)) === strtolower($needle);
2631     }
2632 
2633     /**
2634      * ppload
2635      */
2636     public function updatepploadfileAction()
2637     {
2638         $this->_helper->layout()->disableLayout();
2639         $log = Zend_Registry::get('logger');
2640         $log->debug('**********' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n");
2641 
2642         $projectTable = new Default_Model_DbTable_Project();
2643         $projectData = $projectTable->find($this->_projectId)->current();
2644 
2645         $error_text = '';
2646 
2647         // Update a file in ppload collection
2648         if (!empty($_POST['file_id'])) {
2649             $pploadApi = new Ppload_Api(array(
2650                 'apiUri'   => PPLOAD_API_URI,
2651                 'clientId' => PPLOAD_CLIENT_ID,
2652                 'secret'   => PPLOAD_SECRET
2653             ));
2654 
2655             $fileResponse = $pploadApi->getFile($_POST['file_id']);
2656             if (isset($fileResponse->file->collection_id)
2657                 && $fileResponse->file->collection_id == $projectData->ppload_collection_id
2658             ) {
2659                 $fileRequest = array();
2660                 $tmpFilename = '';
2661                 if (!empty($_FILES['file_upload']['tmp_name'])
2662                     && $_FILES['file_upload']['error'] == UPLOAD_ERR_OK
2663                 ) {
2664                     $tmpFilename = dirname($_FILES['file_upload']['tmp_name']) . '/' . basename($_FILES['file_upload']['name']);
2665                     $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($tmpFilename, true) . "\n");
2666                     move_uploaded_file($_FILES['file_upload']['tmp_name'], $tmpFilename);
2667                     $fileRequest['file'] = $tmpFilename;
2668 
2669                     //20180219 ronald: we set the changed_at only by new files or new updates
2670                     if ((int)$this->_authMember->member_id == (int)$projectData->member_id) {
2671                         $projectData->changed_at = new Zend_Db_Expr('NOW()');
2672                     } else {
2673                         $log->info('********** ' . __CLASS__ . '::' . __FUNCTION__ . ' Project ChangedAt is not set: Auth-Member (' . $this->_authMember->member_id . ') != Project-Owner (' . $projectData->member_id . '): **********' . "\n");
2674                     }
2675                     $projectData->ghns_excluded = 0;
2676                     $projectData->save();
2677 
2678                 }
2679                 if (isset($_POST['file_description'])) {
2680                     $fileRequest['description'] = mb_substr($_POST['file_description'], 0, 140);
2681                 }
2682                 if (isset($_POST['file_category'])) {
2683                     $fileRequest['category'] = $_POST['file_category'];
2684                 }
2685                 if (isset($_POST['file_tags'])) {
2686                     $fileRequest['tags'] = $_POST['file_tags'];
2687                 }
2688                 if (isset($_POST['ocs_compatible'])) {
2689                     $fileRequest['ocs_compatible'] = $_POST['ocs_compatible'];
2690                 }
2691                 if (isset($_POST['file_version'])) {
2692                     $fileRequest['version'] = $_POST['file_version'];
2693                 }
2694 
2695                 $fileResponse = $pploadApi->putFile($_POST['file_id'], $fileRequest);
2696                 $log->debug(__CLASS__ . '::' . __FUNCTION__ . '::' . print_r($fileResponse, true) . "\n");
2697 
2698                 if ($tmpFilename) {
2699                     unlink($tmpFilename);
2700                 }
2701 
2702                 if (isset($fileResponse->status)
2703                     && $fileResponse->status == 'success'
2704                 ) {
2705 
2706                     //If this file is bigger than XXX MB (see application.ini), then create a webtorrent file
2707                     $config = Zend_Registry::get('config');
2708                     $minFileSize = $config->torrent->media->min_filesize;
2709                     if (!empty($fileResponse->file->size) && $fileResponse->file->size >= $minFileSize) {
2710                         $queue = Local_Queue_Factory::getQueue();
2711                         $command = new Backend_Commands_CreateTorrent($fileResponse->file);
2712                         $queue->send(serialize($command));
2713                     }
2714 
2715                     $this->_helper->json(array(
2716                         'status' => 'ok',
2717                         'file'   => $fileResponse->file
2718                     ));
2719 
2720                     return;
2721                 } else {
2722                     $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse)
2723                                    . '; $fileResponse->status: ' . $fileResponse->status;
2724                 }
2725             } else {
2726                 $error_text .= 'PPload Response: ' . json_encode($fileResponse)
2727                                . '; fileResponse->file->collection_id: ' . $fileResponse->file->collection_id
2728                                . ' != $projectData->ppload_collection_id: ' . $projectData->ppload_collection_id;
2729             }
2730         } else {
2731             $error_text .= 'No CollectionId or no FileId. CollectionId: ' . $projectData->ppload_collection_id
2732                            . ', FileId: ' . $_POST['file_id'];
2733         }
2734 
2735         $log->debug('********** END ' . __CLASS__ . '::' . __FUNCTION__ . '**********' . "\n");
2736         $this->_helper->json(array('status' => 'error', 'error_text' => $error_text));
2737     }
2738 
2739     public function updatefiletagAction()
2740     {
2741         $this->_helper->layout()->disableLayout();
2742 
2743         $error_text = '';
2744 
2745         // Update a file information in ppload collection
2746         if (!empty($_POST['file_id'])) {
2747             $tagId = null;
2748             if (isset($_POST['tag_id'])) {
2749                 $tagId = $_POST['tag_id'];
2750             }
2751             $tagGroupId = null;
2752             if (isset($_POST['tag_group_id'])) {
2753                 $tagGroupId = $_POST['tag_group_id'];
2754             }
2755 
2756             //set architecture
2757             $modelTags = new Default_Model_Tags();
2758             $modelTags->saveFileTagForProjectAndTagGroup($this->_projectId, $_POST['file_id'], $tagId, $tagGroupId);
2759 
2760             $this->_helper->json(array('status' => 'ok'));
2761 
2762             return;
2763         } else {
2764             $error_text .= 'No FileId. , FileId: ' . $_POST['file_id'];
2765         }
2766 
2767         $this->_helper->json(array('status' => 'error', 'error_text' => $error_text));
2768     }
2769 
2770     public function deletefiletagAction()
2771     {
2772         $this->_helper->layout()->disableLayout();
2773 
2774         $error_text = '';
2775 
2776         // Update a file information in ppload collection
2777         if (!empty($_POST['file_id'])) {
2778             $tagId = null;
2779             if (isset($_POST['tag_id'])) {
2780                 $tagId = $_POST['tag_id'];
2781             }
2782 
2783             //set architecture
2784             $modelTags = new Default_Model_Tags();
2785             $modelTags->deleteFileTagForProject($this->_projectId, $_POST['file_id'], $tagId);
2786 
2787             $this->_helper->json(array('status' => 'ok'));
2788 
2789             return;
2790         } else {
2791             $error_text .= 'No FileId. , FileId: ' . $_POST['file_id'];
2792         }
2793 
2794         $this->_helper->json(array('status' => 'error', 'error_text' => $error_text));
2795     }
2796 
2797     public function updatecompatibleAction()
2798     {
2799         $this->_helper->layout()->disableLayout();
2800 
2801         $error_text = '';
2802 
2803         // Update a file information in ppload collection
2804         if (!empty($_POST['file_id'])) {
2805             $typeId = null;
2806             if (isset($_POST['is_compatible'])) {
2807                 $is_compatible = $_POST['is_compatible'];
2808             }
2809 
2810             return;
2811         } else {
2812             $error_text .= 'No FileId. , FileId: ' . $_POST['file_id'];
2813         }
2814 
2815         $this->_helper->json(array('status' => 'error', 'error_text' => $error_text));
2816     }
2817 
2818     public function startdownloadAction()
2819     {
2820         $this->_helper->layout()->disableLayout();
2821 
2822         /**
2823          * Save Download-Data in Member_Download_History
2824          */
2825         $file_id = $this->getParam('file_id');
2826         $file_type = $this->getParam('file_type');
2827         $file_name = $this->getParam('file_name');
2828         $file_size = $this->getParam('file_size');
2829         $projectId = $this->_projectId;
2830 
2831         $this->redirect('/dl?file_id=' . $file_id . '&file_type=' . $file_type . '&file_name=' . $file_name . '&file_size=' . $file_size . '&project_id=' . $projectId);
2832     }
2833 
2834     /**
2835      * ppload
2836      */
2837     public function deletepploadfileAction()
2838     {
2839         $this->_helper->layout()->disableLayout();
2840 
2841         $projectTable = new Default_Model_DbTable_Project();
2842         $projectData = $projectTable->find($this->_projectId)->current();
2843 
2844         $error_text = '';
2845 
2846         // Delete file from ppload collection
2847         if (!empty($_POST['file_id'])) {
2848             $pploadApi = new Ppload_Api(array(
2849                 'apiUri'   => PPLOAD_API_URI,
2850                 'clientId' => PPLOAD_CLIENT_ID,
2851                 'secret'   => PPLOAD_SECRET
2852             ));
2853 
2854             $fileResponse = $pploadApi->getFile($_POST['file_id']);
2855             if (isset($fileResponse->file->collection_id)
2856                 && $fileResponse->file->collection_id == $projectData->ppload_collection_id
2857             ) {
2858                 $fileResponse = $pploadApi->deleteFile($_POST['file_id']);
2859                 if (isset($fileResponse->status)
2860                     && $fileResponse->status == 'success'
2861                 ) {
2862 
2863                     $this->_helper->json(array('status' => 'ok'));
2864 
2865                     return;
2866                 } else {
2867                     $error_text .= 'Response: $pploadApi->putFile(): ' . json_encode($fileResponse);
2868                 }
2869             }
2870         }
2871 
2872         $this->_helper->json(array('status' => 'error', 'error_text' => $error_text));
2873     }
2874 
2875     /**
2876      * ppload
2877      */
2878     public function deletepploadfilesAction()
2879     {
2880         $this->_helper->layout()->disableLayout();
2881 
2882         $projectTable = new Default_Model_DbTable_Project();
2883         $projectData = $projectTable->find($this->_projectId)->current();
2884 
2885         // Delete all files in ppload collection
2886         if ($projectData->ppload_collection_id) {
2887             $pploadApi = new Ppload_Api(array(
2888                 'apiUri'   => PPLOAD_API_URI,
2889                 'clientId' => PPLOAD_CLIENT_ID,
2890                 'secret'   => PPLOAD_SECRET
2891             ));
2892 
2893             $filesRequest = array(
2894                 'collection_id' => $projectData->ppload_collection_id,
2895                 'perpage'       => 1000
2896             );
2897 
2898             $filesResponse = $pploadApi->getFiles($filesRequest);
2899 
2900             if (isset($filesResponse->status)
2901                 && $filesResponse->status == 'success'
2902             ) {
2903                 foreach ($filesResponse->files as $file) {
2904                     $fileResponse = $pploadApi->deleteFile($file->id);
2905                     if (!isset($fileResponse->status)
2906                         || $fileResponse->status != 'success'
2907                     ) {
2908                         $this->_helper->json(array('status' => 'error'));
2909 
2910                         return;
2911                     }
2912                 }
2913             }
2914 
2915             $this->_helper->json(array('status' => 'ok'));
2916 
2917             return;
2918         }
2919 
2920         $this->_helper->json(array('status' => 'error'));
2921     }
2922 
2923 
2924     public function saveproductAction()
2925     {
2926         $form = new Default_Form_Product();
2927 
2928         // we don't need to test a file which doesn't exist in this case. The Framework stumbles if $_FILES is empty.
2929         if ($this->_request->isXmlHttpRequest() AND (count($_FILES) == 0)) {
2930             $form->removeElement('image_small_upload');
2931             //            $form->removeElement('image_big_upload');
2932             $form->removeSubForm('gallery');
2933             $form->removeElement('project_id'); //(workaround: Some Browsers send "0" in some cases.)
2934         }
2935 
2936         if (false === $form->isValid($_POST)) {
2937             $errors = $form->getMessages();
2938             $messages = $this->getErrorMessages($errors);
2939             $this->_helper->json(array('status' => 'error', 'messages' => $messages));
2940         }
2941 
2942         $formValues = $form->getValues();
2943         $formValues['status'] = Default_Model_Project::PROJECT_INCOMPLETE;
2944 
2945         $modelProject = new Default_Model_Project();
2946         $newProject =
2947             $modelProject->createProject($this->_authMember->member_id, $formValues, $this->_authMember->username);
2948         //$this->createSystemPlingForNewProject($newProject->project_id);
2949         //New Project in Session, for AuthValidation (owner)
2950         $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id);
2951 
2952         $this->_helper->json(array('status' => 'ok', 'project_id' => $newProject->project_id));
2953     }
2954 
2955     /**
2956      * @param $errors
2957      *
2958      * @return array
2959      */
2960     protected function getErrorMessages($errors)
2961     {
2962         $messages = array();
2963         foreach ($errors as $element => $row) {
2964             if (!empty($row) && $element != 'submit') {
2965                 foreach ($row as $validator => $message) {
2966                     $messages[$element][] = $message;
2967                 }
2968             }
2969         }
2970 
2971         return $messages;
2972     }
2973 
2974     public function searchAction()
2975     {
2976         // Filter-Parameter
2977         $params = $this->getAllParams();
2978         $filterInput =
2979             new Zend_Filter_Input(
2980                 array(
2981                     '*'                 => 'StringTrim',
2982                     'projectSearchText' => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'),
2983                     'page'              => 'digits',
2984                     'pci'               => 'digits',
2985                     'ls'                => 'digits',
2986                     't'                 => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'),
2987                     'pkg'               => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'),
2988                     'lic'               => array(new Zend_Filter_Callback('stripslashes'), 'StripTags'),
2989                     'arch'              => array(new Zend_Filter_Callback('stripslashes'), 'StripTags')
2990 
2991                 ),
2992                 array(
2993                     'projectSearchText' => array(
2994                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)),
2995                         'presence' => 'required'
2996                     ),
2997                     'page'              => array('digits', 'default' => '1'),
2998                     'f'                 => array(
2999                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)),
3000                         //new Zend_Validate_InArray(array('f'=>'tags')),
3001                         'allowEmpty' => true
3002                     ),
3003                     'pci'               => array(
3004                         'digits',
3005                         'allowEmpty' => true
3006                     ),
3007                     'ls'                => array(
3008                         'digits',
3009                         'allowEmpty' => true
3010                     ),
3011                     't'                 => array(
3012                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)),
3013                         'allowEmpty' => true
3014                     ),
3015                     'pkg'               => array(
3016                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)),
3017                         'allowEmpty' => true
3018                     ),
3019                     'lic'               => array(
3020                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)),
3021                         'allowEmpty' => true
3022                     ),
3023                     'arch'              => array(
3024                         new Zend_Validate_StringLength(array('min' => 3, 'max' => 100)),
3025                         'allowEmpty' => true
3026                     )
3027                 ), $params);
3028 
3029 
3030         if ($filterInput->hasInvalid()) {
3031             $this->_helper->flashMessenger->addMessage('<p class="text-error">There was an error. Please check your input and try again.</p>');
3032 
3033             return;
3034         }
3035 
3036 
3037         $this->view->searchText = $filterInput->getEscaped('projectSearchText');
3038         $this->view->page = $filterInput->getEscaped('page');
3039         $this->view->searchField = $filterInput->getEscaped('f');
3040         $this->view->pci = $filterInput->getEscaped('pci');
3041         $this->view->ls = $filterInput->getEscaped('ls');
3042         $this->view->t = $filterInput->getEscaped('t');
3043         $this->view->pkg = $filterInput->getEscaped('pkg');
3044         $this->view->arch = $filterInput->getEscaped('arch');
3045         $this->view->lic = $filterInput->getEscaped('lic');
3046         $this->view->store = $this->getParam('domain_store_id');
3047 
3048         if (isset($params['isJson'])) {
3049             $this->_helper->layout()->disableLayout();
3050             $filterScore = $this->view->ls ? 'laplace_score:[' . $this->view->ls . ' TO ' . ($this->view->ls + 9) . ']' : null;
3051             $filterCat = $this->view->pci ? 'project_category_id:(' . $this->view->pci . ')' : null;
3052             $filterTags = $this->view->t ? 'tags:(' . $this->view->t . ')' : null;
3053             $filterPkg = $this->view->pkg ? 'package_names:(' . $this->view->pkg . ')' : null;
3054             $filterArch = $this->view->arch ? 'arch_names:(' . $this->view->arch . ')' : null;
3055             $filterLic = $this->view->lic ? 'license_names:(' . $this->view->lic . ')' : null;
3056             // $param = array('q' => $this->view->searchText ,'store'=>$this->view->store,'page' => $this->view->page
3057             // , 'count' => 10, 'qf' => $this->view->searchField, 'fq' => array($filterCat, $filterScore, $filterTags,$filterPkg,$filterArch,$filterLic));
3058 
3059             $param = array(
3060                 'q'     => 'test',
3061                 'store' => null,
3062                 'page'  => 1,
3063                 'count' => 10
3064             );
3065             $viewHelperImage = new Default_View_Helper_Image();
3066 
3067             $modelSearch = new Default_Model_Solr();
3068             try {
3069                 $result = $modelSearch->search($param);
3070                 $products = $result['hits'];
3071 
3072                 // var_dump($products);
3073                 // die;
3074                 $ps = array();
3075                 foreach ($products as $p) {
3076                     $img = $viewHelperImage->Image($p->image_small, array(
3077                         'width'  => 50,
3078                         'height' => 50
3079                     ));
3080                     $ps[] = array(
3081                         'description'   => $p->description,
3082                         'title'         => $p->title,
3083                         'project_id'    => $p->project_id,
3084                         'member_id'     => $p->member_id,
3085                         'username'      => $p->username,
3086                         'laplace_score' => $p->laplace_score,
3087                         'score'         => $p->score,
3088                         'image_small'   => $img
3089                     );
3090                 }
3091 
3092                 $this->_helper->json(array(
3093                     'status'   => 'ok',
3094                     'products' => $ps,
3095                     'q'        => $param
3096                 ));
3097             } catch (Exception $e) {
3098                 $this->_helper->json(array(
3099                     'status' => 'err',
3100                     'msg'    => 'Not Found! Try again.'
3101                 ));
3102             }
3103 
3104         }
3105 
3106 
3107     }
3108 
3109     public function startmediaviewajaxAction()
3110     {
3111         return $this->startvideoajaxAction();
3112     }
3113 
3114     public function startvideoajaxAction()
3115     {
3116         $this->_helper->layout()->disableLayout();
3117 
3118         $collection_id = null;
3119         $file_id = null;
3120         $memberId = $this->_authMember->member_id;
3121         $media_view_type_id = (int)$this->getParam('type_id', Default_Model_DbTable_MediaViews::MEDIA_TYPE_VIDEO);
3122 
3123         if ($this->hasParam('collection_id') && $this->hasParam('file_id')) {
3124             $collection_id = (int)$this->getParam('collection_id');
3125             $file_id = (int)$this->getParam('file_id');
3126             $id = null;
3127 
3128             //Log media view
3129             try {
3130                 $this->saveMediaView($file_id, $media_view_type_id);
3131 
3132                 $mediaviewsTable = new Default_Model_DbTable_MediaViews();
3133                 $id = $mediaviewsTable->getNewId();
3134                 $data = array(
3135                     'media_view_id'      => $id,
3136                     'media_view_type_id' => $media_view_type_id,
3137                     'project_id'         => $this->_projectId,
3138                     'collection_id'      => $collection_id,
3139                     'file_id'            => $file_id,
3140                     'start_timestamp'    => new Zend_Db_Expr ('Now()'),
3141                     'ip'                 => $this->getRealIpAddr(),
3142                     'referer'            => $this->getReferer()
3143                 );
3144                 if (!empty($memberId)) {
3145                     $data['member_id'] = $memberId;
3146                 }
3147                 $data['source'] = 'OCS-Webserver';
3148 
3149                 $mediaviewsTable->createRow($data)->save();
3150 
3151             } catch (Exception $exc) {
3152                 $errorLog = Zend_Registry::get('logger');
3153                 $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL);
3154             }
3155 
3156             $this->_helper->json(array('status' => 'success', 'MediaViewId' => $id));
3157 
3158             return;
3159         }
3160 
3161         $this->_helper->json(array('status' => 'error'));
3162     }
3163 
3164     /**
3165      * @param int $file_id
3166      * @param int $media_view_type_id
3167      */
3168     protected function saveMediaView($file_id, $media_view_type_id)
3169     {
3170         switch ($media_view_type_id) {
3171             case Default_Model_DbTable_MediaViews::MEDIA_TYPE_VIDEO:
3172                 Default_Model_Views::saveViewVideo($file_id);
3173                 break;
3174             case Default_Model_DbTable_MediaViews::MEDIA_TYPE_MUSIC:
3175                 Default_Model_Views::saveViewMusic($file_id);
3176                 break;
3177             case Default_Model_DbTable_MediaViews::MEDIA_TYPE_BOOK:
3178                 Default_Model_Views::saveViewBook($file_id);
3179                 break;
3180             default:
3181                 error_log(__METHOD__ . ' :: no mediatype found for value: ' . $media_view_type_id);
3182         }
3183     }
3184 
3185     /**
3186      * @return string|null
3187      */
3188     public function getRealIpAddr()
3189     {
3190         $ip = null;
3191         if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
3192         {
3193             $ip = $_SERVER['HTTP_CLIENT_IP'];
3194         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
3195         {
3196             list($ip) = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); // this could be an array
3197         } else {
3198             $ip = $_SERVER['REMOTE_ADDR'];
3199         }
3200 
3201         return $ip;
3202     }
3203 
3204     /**
3205      * @return string|null
3206      */
3207     public function getReferer()
3208     {
3209         if (isset($_SERVER['HTTP_X_FORWARDED_REFERRER'])) {
3210             return $_SERVER['HTTP_X_FORWARDED_REFERRER'];
3211         }
3212         if (!empty($_SERVER['HTTP_REFERER'])) {
3213             return $_SERVER['HTTP_REFERER'];
3214         }
3215 
3216         return null;
3217     }
3218 
3219     public function stopmediaviewajaxAction()
3220     {
3221         return $this->stopvideoajaxAction();
3222     }
3223 
3224     public function stopvideoajaxAction()
3225     {
3226         $this->_helper->layout()->disableLayout();
3227 
3228         $view_id = null;
3229 
3230         if ($this->hasParam('media_view_id')) {
3231             $view_id = $this->getParam('media_view_id');
3232 
3233             //Log media view stop
3234             try {
3235                 $mediaviewsTable = new Default_Model_DbTable_MediaViews();
3236                 $data = array('stop_timestamp' => new Zend_Db_Expr ('Now()'));
3237                 $mediaviewsTable->update($data, 'media_view_id = ' . $view_id);
3238             } catch (Exception $exc) {
3239                 //echo $exc->getTraceAsString();
3240                 $errorLog = Zend_Registry::get('logger');
3241                 $errorLog->err(__METHOD__ . ' - ' . $exc->getMessage() . ' ---------- ' . PHP_EOL);
3242             }
3243             $this->_helper->json(array('status' => 'success', 'MediaViewId' => $view_id));
3244 
3245             return;
3246         }
3247 
3248         $this->_helper->json(array('status' => 'error'));
3249     }
3250 
3251     protected function createPling($member_id, $project_id)
3252     {
3253         $projectplings = new Default_Model_ProjectPlings();
3254         $newVals = array('project_id' => $project_id, 'member_id' => $member_id);
3255         $sql = $projectplings->select()
3256                              ->where('member_id = ?', $this->_authMember->member_id)
3257                              ->where('is_deleted = ?', 0)
3258                              ->where('project_id = ?', $this->_projectId, 'INTEGER');
3259         $result = $projectplings->fetchRow($sql);
3260         if (null === $result) {
3261             $projectplings->createRow($newVals)->save();
3262         }
3263     }
3264 
3265     /**
3266      * @param $memberId
3267      *
3268      * @throws Zend_Db_Table_Exception
3269      */
3270     protected function setViewDataForMyProducts($memberId)
3271     {
3272         $tableMember = new Default_Model_Member();
3273         $this->view->member = $tableMember->find($memberId)->current();
3274 
3275         $tableProduct = new Default_Model_Project();
3276         $this->view->products = $tableProduct->fetchAllProjectsForMember($memberId);
3277     }
3278 
3279     protected function _initResponseHeader()
3280     {
3281         $duration = 1800; // in seconds
3282         $expires = gmdate("D, d M Y H:i:s", time() + $duration) . " GMT";
3283 
3284         $this->getResponse()->setHeader('X-FRAME-OPTIONS', 'ALLOWALL',
3285             true)//            ->setHeader('Last-Modified', $modifiedTime, true)
3286              ->setHeader('Expires', $expires, true)->setHeader('Pragma', 'no-cache', true)
3287              ->setHeader('Cache-Control', 'private, max-age=0, no-cache, no-store, must-revalidate', true);
3288     }
3289 
3290     /**
3291      * @param $hits
3292      *
3293      * @return array
3294      */
3295     protected function generateProjectsArrayForView($hits)
3296     {
3297         $viewArray = array();
3298         $helperBuildProductUrl = new Default_View_Helper_BuildProductUrl();
3299         /** @var $hit Zend_Search_Lucene_Search_QueryHit */
3300         foreach ($hits as $hit) {
3301             $project = $hit->getDocument();
3302             if (null != $project->username) {
3303                 $isUpdate = ($project->type_id == 2);
3304                 if ($isUpdate) {
3305                     $showUrl =
3306                         $helperBuildProductUrl->buildProductUrl($project->pid) . '#anker_' . $project->project_id;
3307                     $plingUrl = $helperBuildProductUrl->buildProductUrl($project->pid, 'pling');
3308                 } else {
3309                     $showUrl = $helperBuildProductUrl->buildProductUrl($project->project_id);
3310                     $plingUrl = $helperBuildProductUrl->buildProductUrl($project->project_id, 'pling');
3311                 }
3312                 $projectArr = array(
3313                     'score'        => $hit->score,
3314                     'id'           => $project->project_id,
3315                     'type_id'      => $project->type_id,
3316                     'title'        => $project->title,
3317                     'description'  => $project->description,
3318                     'image'        => $project->image_small,
3319                     'plings'       => 0,
3320                     'urlGoal'      => $showUrl,
3321                     'urlPling'     => $plingUrl,
3322                     'showUrlPling' => ($project->paypal_mail != null),
3323                     'member'       => array(
3324                         'name'  => $project->username,
3325                         'url'   => 'member/' . $project->member_id,
3326                         'image' => $project->profile_image_url,
3327                         'id'    => $project->member_id
3328                     )
3329                 );
3330                 $viewArray[] = $projectArr;
3331             }
3332         }
3333 
3334         return $viewArray;
3335     }
3336 
3337     protected function setLayout()
3338     {
3339         $layoutName = 'flat_ui_template';
3340         $storeConfig = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null;
3341         if ($storeConfig && $storeConfig->layout_pagedetail) {
3342             $this->_helper->layout()->setLayout($storeConfig->layout_pagedetail);
3343         } else {
3344             $this->_helper->layout()->setLayout($layoutName);
3345         }
3346     }
3347 
3348     private function getFileDownloadCount($collection_id, $fileId)
3349     {
3350         $modelFiles = new Default_Model_DbTable_PploadFiles();
3351 
3352         $countAll = $modelFiles->fetchCountDownloadsForFileAllTime($collection_id, $fileId);
3353         $countToday = $modelFiles->fetchCountDownloadsForFileToday($collection_id, $fileId);
3354 
3355         $count = (int)$countAll + (int)$countToday;
3356 
3357         return $count;
3358     }
3359 
3360 }