File indexing completed on 2024-05-12 05:58:47

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 Default_Model_Project extends Default_Model_DbTable_Project
0024 {
0025 
0026     const FILTER_NAME_PROJECT_ID_NOT_IN = 'project_id_not_in';
0027     const FILTER_NAME_RANKING = 'ranking';
0028     const FILTER_NAME_CATEGORY = 'category';
0029     const FILTER_NAME_TAG = 'tag';
0030     const FILTER_NAME_ORIGINAL = 'original';
0031     const FILTER_NAME_FAVORITE = 'favorite';
0032     const FILTER_NAME_MEMBER = 'member';
0033     const FILTER_NAME_ORDER = 'order';
0034     const FILTER_NAME_LOCATION = 'location';
0035 
0036     const ITEM_TYPE_DUMMY = 0;
0037     const ITEM_TYPE_PRODUCT = 1;
0038     const ITEM_TYPE_UPDATE = 2;
0039 
0040     const TAG_LICENCE_GID = 7;
0041     const TAG_TYPE_ID = 1;
0042 
0043     const TAG_ISORIGINAL = 'original-product';
0044 
0045     /**
0046      * @param int $status
0047      * @param int $id
0048      *
0049      * @throws Exception
0050      */
0051     public function setStatus($status, $id)
0052     {
0053         if (false === in_array($status, $this->_allowedStatusTypes)) {
0054             throw new Exception('Wrong value for project status.');
0055         }
0056         $updateValues = array(
0057             'status'     => $status,
0058             'changed_at' => new Zend_Db_Expr('Now()')
0059         );
0060 
0061         if (self::PROJECT_DELETED == $status) {
0062             $updateValues['deleted_at'] = new Zend_Db_Expr('NOW()');
0063         }
0064 
0065         $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER'));
0066     }
0067 
0068     /**
0069      * @param int $member_id
0070      * @param int $id
0071      */
0072     public function setClaimedByMember($member_id, $id)
0073     {
0074         $updateValues = array(
0075             'claimed_by_member' => $member_id,
0076             'changed_at'        => new Zend_Db_Expr('Now()')
0077         );
0078 
0079         $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER'));
0080     }
0081 
0082     /**
0083      * @param int $id
0084      */
0085     public function resetClaimedByMember($id)
0086     {
0087         $updateValues = array(
0088             'claimed_by_member' => new Zend_Db_Expr('NULL'),
0089             'changed_at'        => new Zend_Db_Expr('Now()')
0090         );
0091 
0092         $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER'));
0093     }
0094 
0095     /**
0096      * @param int $id
0097      */
0098     public function transferClaimToMember($id)
0099     {
0100         $project = $this->fetchProductInfo($id);
0101 
0102         //Update ppload
0103         $pploadFiles = new Default_Model_DbTable_PploadFiles();
0104         $updateValues = array(
0105             'owner_id'         => $project->claimed_by_member
0106         );
0107         $pploadFiles->update($updateValues, "collection_id = ".$project->ppload_collection_id);
0108 
0109         $pploadCollection = new Default_Model_DbTable_PploadCollections();
0110         $updateValues = array(
0111             'owner_id'         => $project->claimed_by_member
0112         );
0113         $pploadCollection->update($updateValues, "id = ".$project->ppload_collection_id);
0114 
0115         //And prohect
0116         $updateValues = array(
0117             'member_id'         => new Zend_Db_Expr('claimed_by_member'),
0118             'claimable'         => new Zend_Db_Expr('NULL'),
0119             'claimed_by_member' => new Zend_Db_Expr('NULL')
0120         );
0121 
0122         $this->update($updateValues, $this->_db->quoteInto('project_id=? and claimable = 1', $id, 'INTEGER'));
0123 
0124     }
0125 
0126     /**
0127      * @param int $project_id
0128      * @param     $member_id
0129      *
0130      * @throws Zend_Db_Statement_Exception
0131      * @throws Zend_Exception
0132      */
0133     public function setInActive($project_id, $member_id)
0134     {
0135         $project_id = (int)$project_id;
0136         $updateValues = array(
0137             'status'     => self::PROJECT_INACTIVE,
0138             'deleted_at' => new Zend_Db_Expr('Now()')
0139         );
0140 
0141         $this->update($updateValues, 'status > 40 AND project_id=' . $project_id);
0142 
0143         $this->setInActiveForUpdates($project_id);
0144         $this->setDeletedForComments($member_id,$project_id);
0145     }
0146 
0147     /**
0148      * @param int $id
0149      */
0150     protected function setInActiveForUpdates($id)
0151     {
0152         $id = (int)$id;
0153         $updateValues = array(
0154             'status'     => self::PROJECT_INACTIVE,
0155             'changed_at' => new Zend_Db_Expr('Now()')
0156         );
0157 
0158         $this->update($updateValues, 'status > 40 AND pid=' . $id);
0159     }
0160 
0161     /**
0162      * @param int $member_id
0163      * @param int $id
0164      *
0165      * @throws Zend_Db_Statement_Exception
0166      * @throws Zend_Exception
0167      */
0168     private function setDeletedForComments($member_id, $id)
0169     {
0170         $modelComments = new Default_Model_ProjectComments();
0171         $modelComments->setAllCommentsForProjectDeleted($member_id, $id);
0172     }
0173 
0174     /**
0175      * @param int $id
0176      *
0177      * @return mixed
0178      * @throws Zend_Db_Statement_Exception
0179      */
0180     public function fetchActiveBySourcePk($id)
0181     {
0182         $q = $this->select()->where('status = ?', self::PROJECT_ACTIVE)->where('source_pk = ?', (int)$id)
0183                   ->where('source_type = "project"')
0184         ;
0185 
0186         return $q->query()->fetch();
0187     }
0188 
0189     /**
0190      * @param int  $member_id
0191      * @param bool $onlyActiveProjects
0192      *
0193      * @return mixed
0194      */
0195     public function countAllProjectsForMember($member_id, $onlyActiveProjects = false)
0196     {
0197         $q = $this->select()->from($this, array('countAll' => new Zend_Db_Expr('count(*)')))->setIntegrityCheck(false)
0198                   ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE))
0199                   ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD)
0200         ;
0201         $resultSet = $q->query()->fetchAll();
0202 
0203         return $resultSet[0]['countAll'];
0204     }
0205 
0206     /**
0207      * @param int  $member_id
0208      * @param bool $onlyActiveProjects
0209      * @param      $catids
0210      *
0211      * @return mixed
0212      * @throws Zend_Cache_Exception
0213      * @throws Zend_Db_Statement_Exception
0214      */
0215     public function countAllProjectsForMemberCatFilter($member_id, $onlyActiveProjects = false, $catids = null)
0216     {
0217         $q = $this->select()->from($this, array('countAll' => new Zend_Db_Expr('count(*)')))->setIntegrityCheck(false)
0218                   ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE))
0219                   ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD)
0220         ;
0221         if (isset($catids)) {
0222             $q->where('project_category_id in (' . $this->_getCatIds($catids) . ')');
0223         }
0224         $resultSet = $q->query()->fetchAll();
0225 
0226         return $resultSet[0]['countAll'];
0227     }
0228 
0229     /**
0230      * @param $catids
0231      *
0232      * @return string
0233      * @throws Zend_Cache_Exception
0234      * @throws Zend_Db_Statement_Exception
0235      */
0236     protected function _getCatIds($catids)
0237     {
0238         $sqlwhereCat = "";
0239         $sqlwhereSubCat = "";
0240 
0241         $idCategory = explode(',', $catids);
0242         if (false === is_array($idCategory)) {
0243             $idCategory = array($idCategory);
0244         }
0245 
0246         $sqlwhereCat .= implode(',', $idCategory);
0247 
0248         $modelCategory = new Default_Model_DbTable_ProjectCategory();
0249         $subCategories = $modelCategory->fetchChildElements($idCategory);
0250 
0251         if (count($subCategories) > 0) {
0252             foreach ($subCategories as $element) {
0253                 $sqlwhereSubCat .= "{$element['project_category_id']},";
0254             }
0255         }
0256 
0257         return $sqlwhereSubCat . $sqlwhereCat;
0258     }
0259 
0260     /**
0261      * By default it will show all projects for a member included the unpublished elements.
0262      *
0263      * @param int      $member_id
0264      * @param int|null $limit
0265      * @param int|null $offset
0266      * @param bool     $onlyActiveProjects
0267      *
0268      * @return Zend_Db_Table_Rowset_Abstract
0269      */
0270     public function fetchAllProjectsForMember($member_id, $limit = null, $offset = null, $onlyActiveProjects = false)
0271     {
0272         $q = $this->select()->from($this, array(
0273             '*',
0274             'project_validated'  => 'project.validated',
0275             'project_uuid'       => 'project.uuid',
0276             'project_status'     => 'project.status',
0277             'project_created_at' => 'project.created_at',
0278             'project_changed_at' => 'project.changed_at',
0279             'member_type'        => 'member.type',
0280             'project_member_id'  => 'member_id',
0281             'laplace_score'      => new Zend_Db_Expr('laplace_score(count_likes,count_dislikes)'),
0282             'catTitle'           => new Zend_Db_Expr('(SELECT title FROM project_category WHERE project_category_id = project.project_category_id)')
0283         ))->setIntegrityCheck(false)->join('member', 'project.member_id = member.member_id', array('username'))
0284                   ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE))
0285                   ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD)
0286                   ->order('project_changed_at DESC')
0287         ;
0288         if (isset($limit)) {
0289             $q->limit($limit, $offset);
0290         }
0291 
0292         return $this->generateRowSet($q->query()->fetchAll());
0293     }
0294 
0295 
0296     /**
0297      * @param array $data
0298      *
0299      * @return Zend_Db_Table_Rowset_Abstract
0300      */
0301     protected function generateRowSet($data)
0302     {
0303         $classRowSet = $this->getRowsetClass();
0304 
0305         return new $classRowSet(array(
0306             'table'    => $this,
0307             'rowClass' => $this->getRowClass(),
0308             'stored'   => true,
0309             'data'     => $data
0310         ));
0311     }
0312 
0313     /**
0314      * By default it will show all projects for a member included the unpublished elements.
0315      *
0316      * @param int      $member_id
0317      * @param int|null $limit
0318      * @param int|null $offset
0319      * @param bool     $onlyActiveProjects
0320      *
0321      * @param null     $catids
0322      *
0323      * @return Zend_Db_Table_Rowset_Abstract
0324      * @throws Zend_Cache_Exception
0325      * @throws Zend_Db_Statement_Exception
0326      */
0327     public function fetchAllProjectsForMemberCatFilter(
0328         $member_id,
0329         $limit = null,
0330         $offset = null,
0331         $onlyActiveProjects = false,
0332         $catids = null
0333     ) {
0334         $q = $this->select()->from($this, array(
0335             '*',
0336             'project_validated'  => 'project.validated',
0337             'project_uuid'       => 'project.uuid',
0338             'project_status'     => 'project.status',
0339             'project_created_at' => 'project.created_at',
0340             'project_changed_at' => 'project.changed_at',
0341             'member_type'        => 'member.type',
0342             'project_member_id'  => 'member_id',
0343             'laplace_score'      => new Zend_Db_Expr('laplace_score(count_likes,count_dislikes)'),
0344             'catTitle'           => new Zend_Db_Expr('(SELECT title FROM project_category WHERE project_category_id = project.project_category_id)')
0345         ))->setIntegrityCheck(false)->join('member', 'project.member_id = member.member_id', array('username'))
0346                   ->where('project.status >= ?', ($onlyActiveProjects ? self::PROJECT_ACTIVE : self::PROJECT_INACTIVE))
0347                   ->where('project.member_id = ?', $member_id, 'INTEGER')->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD)
0348                   ->order('project_changed_at DESC')
0349         ;
0350 
0351         if (isset($catids)) {
0352             $q->where('project_category_id in (' . $this->_getCatIds($catids) . ')');
0353         }
0354 
0355         if (isset($limit)) {
0356             $q->limit($limit, $offset);
0357         }
0358 
0359         return $this->generateRowSet($q->query()->fetchAll());
0360     }
0361 
0362     /**
0363      * @param $collection_id
0364      *
0365      * @return null|Zend_Db_Table_Row_Abstract
0366      */
0367     public function fetchProductForCollectionId($collection_id)
0368     {
0369         $sql = '
0370                 SELECT
0371                   `p`.*
0372                 FROM `project` AS `p`
0373                 WHERE
0374                   `p`.`ppload_collection_id` = :collectionId
0375                   AND `p`.`status` >= :projectStatus AND `p`.`type_id` = :typeId
0376         ';
0377         $result = $this->_db->fetchRow($sql, array(
0378             'collectionId'  => $collection_id,
0379             'projectStatus' => self::PROJECT_INACTIVE,
0380             'typeId'        => self::PROJECT_TYPE_STANDARD
0381         ));
0382 
0383         if ($result) {
0384             return $this->generateRowClass($result);
0385         } else {
0386             return null;
0387         }
0388     }
0389 
0390     /**
0391      * @param int $project_id
0392      *
0393      * @return null|Zend_Db_Table_Row_Abstract
0394      */
0395     public function fetchProductInfo($project_id)
0396     {
0397         $sql = '
0398                 SELECT
0399                   `p`.*,
0400                   `p`.`validated` AS `project_validated`,
0401                   `p`.`uuid` AS `project_uuid`,
0402                   `p`.`status` AS `project_status`,
0403                   `p`.`created_at` AS `project_created_at`,
0404                   `p`.`major_updated_at` AS `project_major_updated_at`,
0405                   `p`.`changed_at` AS `project_changed_at`,
0406                   `p`.`member_id` AS `project_member_id`,
0407                   `p`.`source_pk` AS `project_source_pk`,
0408                   `p`.`version` AS `project_version`,
0409                   `pc`.`title` AS `cat_title`,
0410                   `m`.`username`,
0411                   `m`.`avatar`,
0412                   `m`.`profile_image_url`,
0413                   `m`.`roleId`,
0414                   `m`.`mail`,
0415                   `m`.`paypal_mail`,
0416                   `m`.`dwolla_id`,
0417                   IFNULL(pr.score_with_pling, 500) AS laplace_score,
0418                  `view_reported_projects`.`amount_reports` AS `amount_reports`,
0419                 (SELECT `tag`.`tag_fullname` FROM `tag_object`, `tag` WHERE `tag_object`.`tag_id`=`tag`.`tag_id` AND `tag_object_id` = `p`.`project_id` AND `tag_object`.`is_deleted`=0 AND `tag_group_id` = :tag_licence_gid AND `tag_type_id` = :tag_type_id  ORDER BY `tag_object`.`tag_created` DESC LIMIT 1)
0420                                 AS `project_license_title`
0421                 FROM `project` AS `p`
0422                   JOIN `member` AS `m` ON `p`.`member_id` = `m`.`member_id` AND `m`.`is_active` = 1 AND `m`.`is_deleted` = 0
0423                   JOIN `project_category` AS `pc` ON `p`.`project_category_id` = `pc`.`project_category_id`
0424                   LEFT join  stat_rating_project AS pr  ON p.project_id = pr.project_id
0425                   LEFT JOIN `view_reported_projects` ON ((`view_reported_projects`.`project_id` = `p`.`project_id`))
0426                 WHERE
0427                   `p`.`project_id` = :projectId
0428                   AND `p`.`status` >= :projectStatus AND (`p`.`type_id` = :typeIdStd OR `p`.`type_id` = :typeIdColl)
0429         ';
0430         $result = $this->_db->fetchRow($sql, array(
0431             'projectId'       => $project_id,
0432             'projectStatus'   => self::PROJECT_INACTIVE,
0433             'typeIdStd'       => self::PROJECT_TYPE_STANDARD,
0434             'typeIdColl'      => self::PROJECT_TYPE_COLLECTION,
0435             'tag_licence_gid' => self::TAG_LICENCE_GID,
0436             'tag_type_id'     => self::TAG_TYPE_ID
0437 
0438         ));
0439 
0440         if ($result) {
0441             return $this->generateRowClass($result);
0442         } else {
0443             return null;
0444         }
0445     }
0446 
0447     /**
0448      * @param $project_id
0449      *
0450      * @return Zend_Db_Table_Rowset_Abstract
0451      */
0452     public function fetchProjectUpdates($project_id)
0453     {
0454         $projectSel = $this->select()->setIntegrityCheck(false)->from($this->_name)
0455                            ->join('member', 'project.member_id = member.member_id', array('*'))
0456                            ->where('project.pid=?', $project_id, 'INTEGER')->where('project.status>?', self::PROJECT_INACTIVE)
0457                            ->where('project.type_id=?', self::PROJECT_TYPE_UPDATE)->order('RAND()')
0458         ;
0459 
0460         return $this->fetchAll($projectSel);
0461     }
0462 
0463     /**
0464      * @param $project_id
0465      *
0466      * @return Zend_Db_Table_Rowset_Abstract
0467      */
0468     public function fetchAllProjectUpdates($project_id)
0469     {
0470         $projectSel = $this->select()->setIntegrityCheck(false)->from($this->_name)->where('project.pid=?', $project_id, 'INTEGER')
0471                            ->where('project.status>?', self::PROJECT_INACTIVE)->where('project.type_id=?', self::PROJECT_TYPE_UPDATE)
0472         ;
0473 
0474         return $this->fetchAll($projectSel);
0475     }
0476 
0477     /**
0478      * @param     $project
0479      * @param int $count
0480      *
0481      * @return Zend_Db_Table_Rowset_Abstract
0482      */
0483     public function fetchSimilarProjects($project, $count = 10)
0484     {
0485         $count = (int)$count;
0486         $sql = "
0487                 SELECT *
0488                 FROM `stat_projects` AS `p`
0489                 WHERE `p`.`project_category_id` = :cat_id AND `project_id` <> :project_id
0490                 ORDER BY `p`.`changed_at` DESC
0491                 LIMIT {$count}
0492         ";
0493 
0494         $result = $this->_db->fetchAll($sql, array(
0495                 'cat_id'     => $project->project_category_id,
0496                 'project_id' => $project->project_id
0497             ));
0498 
0499         return $this->generateRowSet($result);
0500     }
0501 
0502     /**
0503      * @param Zend_Db_Table_Row $project
0504      * @param int               $count
0505      *
0506      * @return Zend_Db_Table_Rowset_Abstract
0507      * @throws Zend_Exception
0508      */
0509     public function fetchMoreProjects($project, $count = 6)
0510     {
0511         $q = $this->select()->from(array('project' => 'stat_projects'), array(
0512             'project_id',
0513             'image_small',
0514             'title',
0515             'catTitle' => 'cat_title',
0516             'changed_at'
0517         ))->setIntegrityCheck(false)
0518           ->where('project.status = ?', self::PROJECT_ACTIVE)
0519           ->where('project.member_id = ?', $project->member_id, 'INTEGER')
0520           ->where('project.project_id != ?', $project->project_id, 'INTEGER')
0521           ->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD)
0522           ->where('project.amount_reports is null')
0523           ->where('project.project_category_id = ?', $project->project_category_id, 'INTEGER')
0524           ->limit($count)
0525           ->order('project.project_created_at DESC')
0526         ;
0527 
0528         $tagFilter  = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null;
0529 
0530         if ($tagFilter) {
0531             $q = $this->generateTagFilter($q, array(self::FILTER_NAME_TAG => $tagFilter));
0532         }
0533 
0534         $result = $this->fetchAll($q);
0535 
0536         return $result;
0537     }
0538 
0539     /**
0540      * @param Zend_Db_Select $statement
0541      * @param array          $filterArrayValue
0542      *
0543      * @return Zend_Db_Select
0544      */
0545     protected function generateTagFilter(Zend_Db_Select $statement, $filterArrayValue)
0546     {
0547         if (false == isset($filterArrayValue[self::FILTER_NAME_TAG])) {
0548             return $statement;
0549         }
0550 
0551         $filter = $filterArrayValue[self::FILTER_NAME_TAG];
0552 
0553         if (is_array($filter)) {
0554 
0555             $tagList = $filter;
0556             //build where statement fĂĽr projects
0557             $selectAnd = $this->select()->from(array('project' => 'stat_projects'));
0558 
0559             foreach($tagList as $item) {
0560                 #and
0561                 $selectAnd->where('find_in_set(?, tag_ids)', $item);
0562             }
0563             $statement->where(implode(' ', $selectAnd->getPart('where')));
0564 
0565             /*
0566             $statement->join(array(
0567                 'tags' => new Zend_Db_Expr('(SELECT DISTINCT project_id FROM stat_project_tagids WHERE tag_id in ('
0568                     . implode(',', $filter) . '))')
0569             ), 'project.project_id = tags.project_id', array());
0570              *
0571              */
0572 
0573         } else {
0574             $statement->where('find_in_set(?, tag_ids)', $filter);
0575         }
0576 
0577         return $statement;
0578     }
0579 
0580     /**
0581      * @param     $project
0582      * @param int $count
0583      *
0584      * @return Zend_Db_Table_Rowset_Abstract
0585      * @throws Zend_Db_Statement_Exception
0586      * @throws Zend_Exception
0587      * @todo improve processing speed
0588      */
0589     public function fetchMoreProjectsOfOtherUsr($project, $count = 8)
0590     {
0591         $sql = "
0592                 SELECT count(1) AS `count`
0593                 FROM `stat_projects`
0594                 WHERE `status` = :current_status
0595                   AND `member_id` <> :current_member_id
0596                   AND `project_category_id` = :category_id
0597                   AND `type_id` = :project_type
0598         ";
0599 
0600         $result = $this->_db->query($sql, array(
0601             'current_status'    => self::PROJECT_ACTIVE,
0602             'current_member_id' => $project->member_id,
0603             'category_id'       => $project->project_category_id,
0604             'project_type'      => self::PROJECT_TYPE_STANDARD
0605         ))->fetch()
0606         ;
0607 
0608         if ($result['count'] > $count) {
0609             $offset = rand(0, $result['count'] - $count);
0610         } else {
0611             $offset = 0;
0612         }
0613 
0614         $q = $this->select()->from(array('project' => 'stat_projects'), array(
0615             'project_id',
0616             'image_small',
0617             'title',
0618             'catTitle' => 'cat_title',
0619             'changed_at'
0620         ))->setIntegrityCheck(false)->where('status = ?', self::PROJECT_ACTIVE)
0621                   ->where('member_id != ?', $project->member_id, 'INTEGER')->where('type_id = ?', 1)
0622                   ->where('amount_reports is null')
0623                   ->where('project_category_id = ?', $project->project_category_id, 'INTEGER')->limit($count, $offset)
0624                   ->order('project_created_at DESC')
0625         ;
0626 
0627         $tagFilter  = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null;
0628 
0629         if ($tagFilter) {
0630             $q = $this->generateTagFilter($q, array(self::FILTER_NAME_TAG => $tagFilter));
0631         }
0632 
0633         $result = $this->fetchAll($q);
0634 
0635         return $result;
0636     }
0637 
0638     /**
0639      * @param int $project_id
0640      *
0641      * @return Zend_Db_Table_Rowset_Abstract
0642      */
0643     public function fetchProjectSupporter($project_id)
0644     {
0645         $plingTable = new Default_Model_DbTable_Plings();
0646 
0647         return $plingTable->getSupporterForProjectId($project_id);
0648     }
0649 
0650     /**
0651      * @param int $project_id
0652      *
0653      * @return Zend_Db_Table_Rowset_Abstract
0654      */
0655     public function fetchProjectSupporterWithPlings($project_id)
0656     {
0657         $plingTable = new Default_Model_DbTable_Plings();
0658 
0659         return $plingTable->getSupporterWithPlingsForProjectId($project_id);
0660     }
0661 
0662     /**
0663      * @param $projectId
0664      * @param $sources
0665      */
0666     public function updateGalleryPictures($projectId, $sources)
0667     {
0668         $galleryPictureTable = new Default_Model_DbTable_ProjectGalleryPicture();
0669         $galleryPictureTable->clean($projectId);
0670         $galleryPictureTable->insertAll($projectId, $sources);
0671     }
0672 
0673     /**
0674      * @param $projectId
0675      *
0676      * @return array
0677      */
0678     public function getGalleryPictureSources($projectId)
0679     {
0680         $galleryPictureTable = new Default_Model_DbTable_ProjectGalleryPicture();
0681         $stmt = $galleryPictureTable->select()->where('project_id = ?', $projectId)->order(array('sequence'));
0682 
0683         $pics = array();
0684         foreach ($galleryPictureTable->fetchAll($stmt) as $pictureRow) {
0685             $pics[] = $pictureRow['picture_src'];
0686         }
0687 
0688         return $pics;
0689     }
0690 
0691     /**
0692      * @param int $project_id
0693      *
0694      * @return array
0695      * @throws Zend_Db_Statement_Exception
0696      */
0697     public function fetchProjectViews($project_id)
0698     {
0699         $sql = "
0700                 SELECT
0701                     `project_id`,
0702                     `count_views`,
0703                     `count_visitor`,
0704                     `last_view`
0705                 FROM
0706                     `stat_page_views_mv`
0707                 WHERE `project_id` = ?
0708                 ";
0709         $database = Zend_Db_Table::getDefaultAdapter();
0710         $sql = $database->quoteInto($sql, $project_id, 'INTEGER', 1);
0711         $resultSet = $database->query($sql)->fetchAll();
0712 
0713         if (count($resultSet) > 0) {
0714             $result = $resultSet[0]['count_views'];
0715         } else {
0716             $result = 0;
0717         }
0718 
0719         return $result;
0720     }
0721 
0722     /**
0723      * @param int $member_id
0724      *
0725      * @return int
0726      * @throws Zend_Db_Statement_Exception
0727      */
0728     public function fetchOverallPageViewsByMember($member_id)
0729     {
0730         $sql = "
0731                 SELECT sum(`stat`.`amount`) AS `page_views`
0732                 FROM `project`
0733                 JOIN (SELECT `project_id`, count(`project_id`) AS `amount` FROM `stat_page_views` GROUP BY `project_id`) AS `stat` ON `stat`.`project_id` = `project`.`project_id`
0734                 WHERE `project`.`member_id` = :member_id AND `project`.`status` = :project_status
0735                 GROUP BY `member_id`
0736               ";
0737 
0738         $result = $this->_db->query($sql, array('member_id' => $member_id, 'project_status' => self::PROJECT_ACTIVE));
0739         if ($result->rowCount() > 0) {
0740             $row = $result->fetch();
0741 
0742             return $row['page_views'];
0743         } else {
0744             return 0;
0745         }
0746     }
0747 
0748     /**
0749      * @return array
0750      * @throws Zend_Db_Statement_Exception
0751      */
0752     public function getStatsForNewProjects()
0753     {
0754         $sql = "
0755                 SELECT
0756                     DATE_FORMAT(`time`, '%M %D') AS `projectdate`,
0757                     count(1) AS `daycount`
0758                 FROM
0759                     `activity_log`
0760                 WHERE
0761                     `activity_type_id` = 0
0762                 GROUP BY DATE_FORMAT(`time`, '%Y%M%D')
0763                 ORDER BY `time` DESC
0764                 LIMIT 14
0765                 ;";
0766         $database = Zend_Db_Table::getDefaultAdapter();
0767         $resultSet = $database->query($sql)->fetchAll();
0768 
0769         return $resultSet;
0770     }
0771 
0772     /**
0773      * @param int     $idCategory
0774      * @param int|null $limit
0775      *
0776      * @return Zend_Db_Table_Rowset_Abstract
0777      * @throws Zend_Cache_Exception
0778      * @throws Zend_Db_Statement_Exception
0779      */
0780     public function fetchProductsByCategory($idCategory, $limit = null)
0781     {
0782         $select =
0783             $this->select()->setIntegrityCheck(false)->from($this->_name)->where('project.project_category_id in (?)', $idCategory)
0784                  ->where('project.status = ?', self::PROJECT_ACTIVE)->where('project.type_id = ?', self::PROJECT_TYPE_STANDARD)
0785                  ->joinLeft(array(
0786                      'pling_amount' => new Zend_Db_Expr('(SELECT
0787                 project_id as plinged_project_id, SUM(amount) AS sumAmount, count(1) as countPlings
0788             FROM
0789                 plings
0790             where status_id >= 2
0791             group by project_id
0792             order by sumAmount DESC)')
0793                  ), 'pling_amount.plinged_project_id = project.project_id')
0794                  ->joinLeft('project_category', 'project_category.project_category_id = project.project_category_id',
0795                      array('cat_title' => 'title'))->order('pling_amount.sumAmount DESC')
0796         ;
0797         if (false === is_null($limit)) {
0798             $select->limit($limit);
0799         }
0800 
0801         $modelCategory = new Default_Model_DbTable_ProjectCategory();
0802         $subCategories = $modelCategory->fetchChildElements($idCategory);
0803 
0804         if (count($subCategories) > 0) {
0805             $sqlwhere = '';
0806             foreach ($subCategories as $element) {
0807                 $sqlwhere .= "{$element['project_category_id']},";
0808             }
0809             $sqlwhere = substr($sqlwhere, 0, -1);
0810             if (!empty($sqlwhere)) {
0811                 $sqlwhere = explode(',', $sqlwhere);
0812             }
0813 
0814             $select->orWhere('project.project_category_id in (?)', $sqlwhere);
0815         }
0816 
0817         return $this->fetchAll($select);
0818     }
0819 
0820     /**
0821      * @param int|array $idCategory id of a category or an array of id's
0822      * @param bool      $withSubCat if was set true it will also count products in sub categories
0823      * @param null      $store_id
0824      *
0825      * @return int count of products in given category
0826      * @throws Zend_Exception
0827      * @deprecated
0828      */
0829     public function countProductsInCategory($idCategory = null, $withSubCat = true, $store_id = null)
0830     {
0831         if (empty($idCategory)) {
0832             throw new Zend_Exception('idCategory param was not set');
0833         }
0834 
0835         if (false == is_array($idCategory)) {
0836             $idCategory = array($idCategory);
0837         }
0838 
0839         if (isset($store_id)) {
0840             $configurations = Zend_Registry::get('application_store_config_id_list');
0841             $store_config = isset($configurations[$store_id]) ? $configurations[$store_id] : null;
0842         } else {
0843             $store_config = Zend_Registry::isRegistered('store_config') ? Zend_Registry::get('store_config') : null;
0844         }
0845         $tagFilter  = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null;
0846 
0847         $cacheName = __FUNCTION__ . '_' . md5(serialize($idCategory) . $withSubCat . serialize($tagFilter));
0848         /** @var Zend_Cache_Core $cache */
0849         $cache = Zend_Registry::get('cache');
0850 
0851         if (false !== ($resultSet = $cache->load($cacheName))) {
0852             return (int)$resultSet[0]['count_active_projects'];
0853         }
0854 
0855         $select = $this->select()->setIntegrityCheck(false)->from('stat_projects', array('count_active_projects' => 'COUNT(1)'))
0856                        ->where('status = ? ', self::PROJECT_ACTIVE)->where('type_id = ?', self::PROJECT_TYPE_STANDARD)
0857         ;
0858 
0859         $select = $this->generateTagFilter($select, array(self::FILTER_NAME_TAG => $tagFilter));
0860 
0861         if ($withSubCat) {
0862             $modelCategory = new Default_Model_DbTable_ProjectCategory();
0863             $subCategories = $modelCategory->fetchChildIds($idCategory);
0864             $inCategories = implode(',', array_unique(array_merge($idCategory, $subCategories)));
0865         } else {
0866             $inCategories = implode(',', $idCategory);
0867         }
0868 
0869         $select->where('project_category_id in (' . $inCategories . ')');
0870         $resultSet = $this->fetchAll($select)->toArray();
0871 
0872         $cache->save($resultSet, $cacheName, array(), 60);
0873 
0874         return (int)$resultSet[0]['count_active_projects'];
0875     }
0876 
0877     /**
0878      * @param int|array $idCategory
0879      *
0880      * @return int
0881      * @throws Zend_Exception
0882      */
0883     public function countActiveMembersForCategory($idCategory)
0884     {
0885 
0886         $cacheName = __FUNCTION__ . md5(serialize($idCategory));
0887         $cache = Zend_Registry::get('cache');
0888 
0889         $result = $cache->load($cacheName);
0890 
0891         if ($result) {
0892             return (int)$result['count_active_members'];
0893         }
0894 
0895         $sqlwhereCat = "";
0896         $sqlwhereSubCat = "";
0897 
0898         if (false === is_array($idCategory)) {
0899             $idCategory = array($idCategory);
0900         }
0901         $sqlwhereCat .= implode(',', $idCategory);
0902 
0903         $modelCategory = new Default_Model_DbTable_ProjectCategory();
0904         $subCategories = $modelCategory->fetchChildElements($idCategory);
0905 
0906         if (count($subCategories) > 0) {
0907             foreach ($subCategories as $element) {
0908                 $sqlwhereSubCat .= "{$element['project_category_id']},";
0909             }
0910         }
0911 
0912         $selectWhere = 'AND p.project_category_id in (' . $sqlwhereSubCat . $sqlwhereCat . ')';
0913 
0914         $sql = "SELECT count(1) AS `count_active_members` FROM (
0915                     SELECT count(1) AS `count_active_projects` FROM `project` `p`
0916                     WHERE `p`.`status` = 100
0917                     AND `p`.`type_id` = 1
0918                     {$selectWhere} GROUP BY p.member_id
0919                 ) AS `A`;";
0920 
0921         $result = $this->_db->fetchRow($sql);
0922         $cache->save($result, $cacheName);
0923 
0924         return (int)$result['count_active_members'];
0925     }
0926 
0927     /**
0928      * @param int $project_id
0929      *
0930      * @return bool
0931      */
0932     public function isProjectFeatured($project_id)
0933     {
0934         $sql_object =
0935             "SELECT `project_id` FROM `project` WHERE `project_id`= :project_id AND  `status` = 100 AND `type_id` = 1 AND `featured` = 1";
0936         $r = $this->getAdapter()->fetchRow($sql_object, array('project_id' => $project_id));
0937         if ($r) {
0938             return true;
0939         } else {
0940             return false;
0941         }
0942     }
0943     
0944     /**
0945      * @param int $project_id
0946      *
0947      * @return bool
0948      */
0949     public function isProjectClone($project_id)
0950     {
0951         $sql_object =
0952             "SELECT c.project_clone_id FROM project_clone c
0953                 WHERE c.is_valid = 1
0954                 AND c.is_deleted = 0
0955                 AND c.project_id_parent IS NOT NULL
0956                 AND c.project_id = :project_id";
0957         $r = $this->getAdapter()->fetchRow($sql_object, array('project_id' => $project_id));
0958         if ($r) {
0959             return true;
0960         } else {
0961             return false;
0962         }
0963     }
0964 
0965 
0966     /**
0967      * @param bool $in_current_store
0968      *
0969      * @return int
0970      * @throws Zend_Exception
0971      */
0972     public function fetchTotalProjectsCount($in_current_store = false)
0973     {
0974         $sql = "SELECT count(1) AS `total_project_count` FROM `stat_projects`";
0975         if ($in_current_store) {
0976             $store_tags = Zend_Registry::isRegistered('config_store_tags') ? Zend_Registry::get('config_store_tags') : null;
0977             /*
0978             if ($store_tags) {
0979                 $sql .= ' JOIN (SELECT DISTINCT project_id FROM stat_project_tagids WHERE tag_id in (' . implode(',', $store_tags)
0980                     . ')) AS tags ON stat_projects.project_id = tags.project_id';
0981             }
0982              *
0983              */
0984 
0985             $info = new Default_Model_Info();
0986             $activeCategories = $info->getActiveCategoriesForCurrentHost();
0987             $sql .= ' WHERE project_category_id IN (' . implode(',', $activeCategories) . ')';
0988 
0989             //Store Tag Filter
0990             if ($store_tags) {
0991                 $tagList = $store_tags;
0992                 //build where statement fĂĽr projects
0993                 $sql .= " AND (";
0994 
0995                 if(!is_array($tagList)) {
0996                     $tagList = array($tagList);
0997                 }
0998 
0999                 foreach($tagList as $item) {
1000                     #and
1001                     $sql .= ' find_in_set('.$item.', tag_ids) AND ';
1002                 }
1003                 $sql .= ' 1=1)';;
1004             }
1005 
1006         }
1007         $result = $this->_db->fetchRow($sql);
1008 
1009         return (int)$result['total_project_count'];
1010     }
1011 
1012     /**
1013      * @param $member_id
1014      *
1015      * @throws Zend_Db_Statement_Exception
1016      * @throws Zend_Exception
1017      */
1018     public function setAllProjectsForMemberDeleted($member_id)
1019     {
1020         $sql =
1021             "SELECT `project_id` FROM `project` WHERE `member_id` = :memberId AND `type_id` = :typeId AND `status` > :project_status";
1022         $projectForDelete = $this->_db->fetchAll($sql, array(
1023             'memberId'       => $member_id,
1024             'typeId'         => self::PROJECT_TYPE_STANDARD,
1025             'project_status' => self::PROJECT_DELETED
1026         ));
1027         foreach ($projectForDelete as $item) {
1028             $this->setDeleted($member_id, $item['project_id']);
1029         }
1030 
1031         // set personal page deleted
1032         $sql = "SELECT project_id FROM project WHERE member_id = :memberId AND type_id = :typeId";
1033         $projectForDelete = $this->_db->fetchAll($sql, array(
1034             'memberId' => $member_id,
1035             'typeId'   => self::PROJECT_TYPE_PERSONAL
1036         ));
1037         foreach ($projectForDelete as $item) {
1038             $this->setDeleted($member_id, $item['project_id']);
1039         }
1040         /*
1041         $sql = "UPDATE project SET `status` = :statusCode, deleted_at = NOW() WHERE member_id = :memberId AND type_id = :typeId";
1042         $this->_db->query($sql, array(
1043             'statusCode' => self::PROJECT_DELETED,
1044             'memberId'   => $member_id,
1045             'typeId'     => self::PROJECT_TYPE_PERSONAL
1046         ))->execute();
1047         */
1048     }
1049 
1050     /**
1051      * @param int $member_id
1052      * @param int $id
1053      *
1054      * @throws Zend_Db_Statement_Exception
1055      * @throws Zend_Exception
1056      */
1057     public function setDeleted($member_id, $id)
1058     {
1059         $id = (int)$id;
1060         $updateValues = array(
1061             'status'     => self::PROJECT_DELETED,
1062             'deleted_at' => new Zend_Db_Expr('Now()')
1063         );
1064 
1065         $this->update($updateValues, 'status > 30 AND project_id=' . $id);
1066 
1067         $memberLog = new Default_Model_MemberDeactivationLog();
1068         $memberLog->logProjectAsDeleted($member_id, $id);
1069         
1070         // this will delete the product and request the ppload for deleting associated files
1071         $product = $this->find($id)->current();
1072         $command = new Backend_Commands_DeleteProductExtended($product);
1073         $command->doCommand();
1074 
1075         $this->setDeletedForUpdates($member_id, $id);
1076         $this->setDeletedForComments($member_id, $id);
1077         $this->setDeletedInMaterializedView($id);
1078     }
1079 
1080     /**
1081      * @param     $member_id
1082      * @param int $id
1083      */
1084     protected function setDeletedForUpdates($member_id, $id)
1085     {
1086         $id = (int)$id;
1087         $updateValues = array(
1088             'status'     => self::PROJECT_DELETED,
1089             'deleted_at' => new Zend_Db_Expr('Now()')
1090         );
1091 
1092         $this->update($updateValues, 'status > 30 AND pid=' . $id);
1093     }
1094 
1095     /**
1096      * @param $id
1097      *
1098      * @throws Zend_Db_Statement_Exception
1099      */
1100     private function setDeletedInMaterializedView($id)
1101     {
1102         $sql = "UPDATE `stat_projects` SET `status` = :new_status WHERE `project_id` = :project_id";
1103 
1104         $result = $this->_db->query($sql, array('new_status' => self::PROJECT_DELETED, 'project_id' => $id))->execute();
1105     }
1106 
1107     /**
1108      * @param int $member_id
1109      *
1110      * @throws Zend_Exception
1111      */
1112     public function setAllProjectsForMemberActivated($member_id)
1113     {
1114         $sql = "SELECT `p`.`project_id` FROM `project` `p`
1115                 JOIN `member_deactivation_log` `l` ON `l`.`object_type_id` = 3 AND `l`.`object_id` = `p`.`project_id` AND `l`.`deactivation_id` = `p`.`member_id`
1116                 WHERE `p`.`member_id` = :memberId";
1117         $projectForDelete = $this->_db->fetchAll($sql, array(
1118             'memberId' => $member_id
1119         ));
1120         foreach ($projectForDelete as $item) {
1121             $this->setActive($member_id, $item['project_id']);
1122         }
1123     }
1124 
1125     /**
1126      * @param int $member_id
1127      * @param int $id
1128      *
1129      * @throws Zend_Exception
1130      */
1131     public function setActive($member_id, $id)
1132     {
1133         $updateValues = array(
1134             'status'     => self::PROJECT_ACTIVE,
1135             'deleted_at' => null
1136         );
1137 
1138         $this->update($updateValues, $this->_db->quoteInto('project_id=?', $id, 'INTEGER'));
1139 
1140         $memberLog = new Default_Model_MemberDeactivationLog();
1141         $memberLog->removeLogProjectAsDeleted($member_id, $id);
1142 
1143         $this->setActiveForUpdates($member_id, $id);
1144         $this->setActiveForComments($member_id, $id);
1145     }
1146 
1147     /**
1148      * @param int $id
1149      */
1150     protected function setActiveForUpdates($member_id, $id)
1151     {
1152         $updateValues = array(
1153             'status'     => self::PROJECT_ACTIVE,
1154             'deleted_at' => null
1155         );
1156 
1157         $this->update($updateValues, $this->_db->quoteInto('pid=?', $id, 'INTEGER'));
1158     }
1159 
1160     /**
1161      * @param int $member_id
1162      * @param int $project_id
1163      */
1164     private function setActiveForComments($member_id, $project_id)
1165     {
1166         $modelComments = new Default_Model_ProjectComments();
1167         $modelComments->setAllCommentsForProjectActivated($member_id, $project_id);
1168     }
1169 
1170     /**
1171      * @param array    $inputFilterParams
1172      * @param int|null $limit
1173      * @param int|null $offset
1174      *
1175      * @return array
1176      * @throws Zend_Cache_Exception
1177      * @throws Zend_Db_Select_Exception
1178      * @throws Zend_Exception
1179      */
1180     public function fetchProjectsByFilter($inputFilterParams, $limit = null, $offset = null)
1181     {
1182         $cacheName = __FUNCTION__ . '_' . md5(serialize($inputFilterParams) . (string)$limit . (string)$offset);
1183         /** @var Zend_Cache_Core $cache */
1184         $cache = Zend_Registry::get('cache');
1185 
1186         if (false === ($returnValue = $cache->load($cacheName))) {
1187             $statement = $this->generateStatement($inputFilterParams, $limit, $offset);
1188 
1189             if (APPLICATION_ENV == 'development') {
1190                 Zend_Registry::get('logger')->debug(__METHOD__ . ' - ' . $statement->__toString());
1191             }
1192 
1193             /** @var Zend_Db_Table_Rowset $fetchedElements */
1194             $fetchedElements = $this->fetchAll($statement);
1195             $statement->reset('limitcount')->reset('limitoffset');
1196             $statement->reset('columns')->columns(array('count' => new Zend_Db_Expr('count(*)')));
1197             $countElements = $this->fetchRow($statement);
1198             $returnValue = array('elements' => $fetchedElements, 'total_count' => $countElements->count);
1199             $cache->save($returnValue, $cacheName, array(), 120);
1200         }
1201        
1202         return $returnValue;
1203     }
1204 
1205     /**
1206      * @param array    $inputFilterParams
1207      * @param int|null $limit
1208      * @param int|null $offset
1209      *
1210      * @return Zend_Db_Select
1211      * @throws Zend_Cache_Exception
1212      * @throws Zend_Db_Statement_Exception
1213      */
1214     protected function generateStatement($inputFilterParams, $limit = null, $offset = null)
1215     {
1216         $statement = $this->generateBaseStatement();
1217         $statement = $this->generateCategoryFilter($statement, $inputFilterParams);
1218         $statement = $this->generateOrderFilter($statement, $inputFilterParams);
1219         $statement = $this->generateTagFilter($statement, $inputFilterParams);
1220         // $statement = $this->generateOriginalFilter($statement, $inputFilterParams);
1221         $statement = $this->generateFavoriteFilter($statement, $inputFilterParams);
1222         $statement = $this->generateReportedSpamFilter($statement);
1223 
1224         $statement->limit($limit, $offset);
1225 
1226         return $statement;
1227     }
1228 
1229     /**
1230      * @return Zend_Db_Select
1231      */
1232     protected function generateBaseStatement()
1233     {
1234         $statement = $this->select()->setIntegrityCheck(false);
1235         //$statement->from(array('project' => $this->_name), array(
1236         $statement->from(array('project' => 'stat_projects'), array(
1237             '*'
1238         ));
1239         $statement->where('project.status = ?', self::PROJECT_ACTIVE)->where('project.type_id IN (?)', array(self::PROJECT_TYPE_STANDARD, self::PROJECT_TYPE_COLLECTION));
1240 
1241         return $statement;
1242     }
1243 
1244     /**
1245      * @param Zend_Db_Select $statement
1246      * @param array          $filterArrayValue
1247      *
1248      * @return Zend_Db_Select
1249      * @throws Zend_Cache_Exception
1250      * @throws Zend_Db_Statement_Exception
1251      */
1252     protected function generateCategoryFilter(Zend_Db_Select $statement, $filterArrayValue)
1253     {
1254         if (false == isset($filterArrayValue[self::FILTER_NAME_CATEGORY])) {
1255             return $statement;
1256         }
1257 
1258         $filter = $filterArrayValue[self::FILTER_NAME_CATEGORY];
1259 
1260         if (false === is_array($filter)) {
1261             $filter = array($filter);
1262         }
1263 
1264         // fetch child elements for each category
1265         $modelProjectCategories = new Default_Model_DbTable_ProjectCategory();
1266         $childElements = $modelProjectCategories->fetchChildIds($filter);
1267         $allCategories = array_unique(array_merge($filter, $childElements));
1268         $stringCategories = implode(',', $allCategories);
1269 
1270         $statement->where("(
1271             project.project_category_id IN ({$stringCategories})
1272             )");
1273 
1274         return $statement;
1275     }
1276 
1277     /**
1278      * @param Zend_Db_Select $statement
1279      * @param array          $filterArrayValue
1280      *
1281      * @return Zend_Db_Select
1282      */
1283     protected function generateOrderFilter(Zend_Db_Select $statement, $filterArrayValue)
1284     {
1285         if (!isset($filterArrayValue[self::FILTER_NAME_ORDER])) {
1286             $filterValue = '';
1287         } else {
1288             $filterValue = $filterArrayValue[self::FILTER_NAME_ORDER];
1289         }
1290         switch ($filterValue) {
1291             case 'latest':
1292                 $statement->order('project.major_updated_at DESC');
1293                 //$statement->order('project.changed_at DESC');
1294                 break;
1295 
1296             case 'rating':
1297                 //$statement->order(array('amount_received DESC', 'count_plings DESC', 'latest_pling DESC', 'project.created_at DESC'));
1298                 //$statement->order(array(new Zend_Db_Expr('(round(((count_likes + 6) / ((count_likes + count_dislikes) + 12)),2) * 100) DESC'),'amount_received DESC', 'count_plings DESC', 'latest_pling DESC', 'project.created_at DESC'));
1299                 /*$statement->order(array(
1300                     new Zend_Db_Expr('(round(((count_likes + 6) / ((count_likes + count_dislikes) + 12)),2) * 100) DESC'),
1301                     'project.created_at DESC'
1302                 ));*/
1303                 $statement->order('project.laplace_score DESC');
1304                 break;
1305             case 'plinged':
1306                 $statement->order('project.count_plings DESC');
1307                 break;
1308             case 'test':
1309                 $statement->order('project.laplace_score_test DESC');
1310                 break;
1311             case 'top':
1312                 $statement->order('project.laplace_score_old DESC');
1313                 break;
1314             case 'download':
1315                 $statement->order('project.count_downloads_hive DESC');
1316                 break;
1317             case 'downloadQuarter':
1318                 $statement->order('project.count_downloads_quarter DESC');
1319                 break;
1320 
1321 
1322             case 'hot':
1323                
1324                 $statement->order(array(
1325                     new Zend_Db_Expr('(round(((count_likes + 6) / ((count_likes + count_dislikes) + 12)),2) * 100) DESC'),                    
1326                     'count_plings DESC',                    
1327                     'project.created_at DESC'
1328                 ));
1329                 $statement->where(' project.created_at >= (NOW()- INTERVAL 14 DAY)');
1330                 break;
1331 
1332             case 'alpha':
1333             default:
1334                 $statement->order('project.title');
1335         }
1336 
1337         return $statement;
1338     }
1339 
1340     /**
1341      * @param Zend_Db_Select $statement
1342      * @param array          $filterArrayValue
1343      *
1344      * @return Zend_Db_Select
1345      */
1346     /*protected function generateOriginalFilter(Zend_Db_Select $statement, $filterArrayValue)
1347     {
1348         if (false == isset($filterArrayValue[self::FILTER_NAME_ORIGINAL])) {
1349             return $statement;
1350         }
1351 
1352         $filter = $filterArrayValue[self::FILTER_NAME_ORIGINAL];
1353 
1354         if (is_array($filter)) {
1355             // todo maybe for other tags filter
1356         } else {
1357             $statement->where('find_in_set(?, tags)', $filter);
1358         }
1359 
1360         return $statement;
1361     }*/
1362     
1363     /**
1364      * @param Zend_Db_Select $statement
1365      * @param array          $filterArrayValue
1366      *
1367      * @return Zend_Db_Select
1368      */
1369     protected function generateFavoriteFilter(Zend_Db_Select $statement, $filterArrayValue)
1370     {
1371         if (false == isset($filterArrayValue[self::FILTER_NAME_FAVORITE])) {
1372             return $statement;
1373         }
1374 
1375         $filterMemberId = $filterArrayValue[self::FILTER_NAME_FAVORITE];
1376 
1377         if ( null != $filterMemberId) {
1378             $statement->where('project_follower.member_id = ?', $filterMemberId);
1379             $statement->setIntegrityCheck(false)->join('project_follower', 'project.project_id = project_follower.project_id', array('project_follower_id'));
1380         }
1381 
1382         return $statement;
1383     }
1384 
1385     /**
1386      * @param Zend_Db_Select $statement
1387      *
1388      * @return Zend_Db_Select
1389      */
1390     protected function generateReportedSpamFilter(Zend_Db_Select $statement)
1391     {
1392         return $statement->where('(amount_reports is null)');
1393     }
1394 
1395     /**
1396      * @param int    $member_id
1397      * @param array  $values
1398      * @param string $username
1399      *
1400      * @return Zend_Db_Table_Row_Abstract
1401      * @throws Exception
1402      * @throws Zend_Db_Table_Exception
1403      */
1404     public function createProject($member_id, $values, $username)
1405     {
1406         $values = (array)$values;
1407         if (empty($member_id)) {
1408             throw new Zend_Db_Table_Exception('member_id is not set');
1409         }
1410         if (empty($username)) {
1411             throw new Zend_Db_Table_Exception('username is not set');
1412         }
1413         // check important values for a new project
1414         $values['uuid'] = (!array_key_exists('uuid', $values)) ? Local_Tools_UUID::generateUUID() : $values['uuid'];
1415         $values['member_id'] = (!array_key_exists('member_id', $values)) ? $member_id : $values['member_id'];
1416         $values['status'] = (!array_key_exists('status', $values)) ? self::PROJECT_INACTIVE : $values['status'];
1417         $values['type_id'] = (!array_key_exists('type_id', $values)) ? self::ITEM_TYPE_PRODUCT : $values['type_id'];
1418         $values['created_at'] = (!array_key_exists('created_at', $values)) ? new Zend_Db_Expr('NOW()') : $values['created_at'];
1419         $values['start_date'] = (!array_key_exists('start_date', $values)) ? new Zend_Db_Expr('NULL') : $values['start_date'];
1420         $values['creator_id'] = (!array_key_exists('creator_id', $values)) ? $member_id : $values['creator_id'];
1421         $values['gitlab_project_id'] = (empty($values['gitlab_project_id'])) ? new Zend_Db_Expr('NULL') : $values['gitlab_project_id'];
1422 
1423         if ($username == 'pling editor') {
1424             $values['claimable'] = (!array_key_exists('claimable', $values)) ? self::PROJECT_CLAIMABLE : $values['claimable'];
1425         }
1426 
1427         $savedRow = $this->save($values);
1428 
1429         return $savedRow;
1430     }
1431 
1432     /**
1433      * @param int   $project_id
1434      * @param array $values
1435      *
1436      * @return Zend_Db_Table_Row_Abstract
1437      * @throws Exception
1438      * @throws Zend_Db_Table_Exception
1439      */
1440     public function updateProject($project_id, $values)
1441     {
1442         $values = (array)$values;
1443         $projectData = $this->find($project_id)->current();
1444         if (empty($projectData)) {
1445             throw new Zend_Db_Table_Exception('project_id not found');
1446         }
1447 
1448         $values['gitlab_project_id'] = (empty($values['gitlab_project_id'])) ? new Zend_Db_Expr('NULL') : $values['gitlab_project_id'];
1449 
1450         $projectData->setFromArray($values)->save();
1451 
1452         return $projectData;
1453     }
1454 
1455     /**
1456      * @param int $member_id
1457      *
1458      * @return array|mixed
1459      */
1460     public function fetchMainProject($member_id)
1461     {
1462         $sql = "SELECT * FROM {$this->_name} WHERE type_id = :type AND member_id = :member";
1463 
1464         //        $this->_db->getProfiler()->setEnabled(true);
1465         $result = $this->_db->fetchRow($sql, array('type' => self::PROJECT_TYPE_PERSONAL, 'member' => (int)$member_id));
1466         //        $dummy = $this->_db->getProfiler()->getLastQueryProfile()->getQuery();
1467         //        $this->_db->getProfiler()->setEnabled(true);
1468 
1469         if (count($result) > 0) {
1470             return $result;
1471         } else {
1472             return array();
1473         }
1474     }
1475 
1476     /**
1477      * @param $project_id
1478      *
1479      * @return Zend_Db_Table_Row_Abstract
1480      * @throws Zend_Db_Statement_Exception
1481      */
1482     public function fetchProductDataFromMV($project_id)
1483     {
1484         $sql = "SELECT * FROM `stat_projects` WHERE `project_id` = :project_id";
1485         $resultSet = $this->_db->query($sql, array('project_id' => $project_id))->fetch();
1486         if (false === $resultSet) {
1487             return $this->generateRowClass(array());
1488         }
1489 
1490         return $this->generateRowClass($resultSet);
1491     }
1492 
1493 
1494     /**
1495      * @return array
1496      */
1497     public function fetchGhnsExcludedProjects()
1498     {
1499         $sql = "
1500           SELECT `p`.`project_id`, `p`.`title`, `l`.`member_id` AS `exclude_member_id`, `l`.`time` AS `exclude_time`, `m`.`username` AS `exclude_member_name` FROM `project` `p`
1501                 JOIN `activity_log` `l` ON `l`.`project_id` = `p`.`project_id` AND `l`.`activity_type_id` = 314
1502                 INNER JOIN `member` `m` ON `m`.`member_id` = `l`.`member_id`
1503                 WHERE `p`.`ghns_excluded` = 1
1504 
1505         ";
1506 
1507         $list = $this->_db->fetchAll($sql);
1508 
1509         return $list;
1510     }
1511 
1512     public function getUserCreatingCategorys($member_id)
1513     {
1514         $sql = "
1515                     select
1516                        c.title as category1,
1517                        count(1) as cnt
1518                       from project p
1519                       join project_category c on p.project_category_id = c.project_category_id
1520                       where p.status = 100
1521                       and p.member_id =:member_id
1522                       and p.type_id = 1
1523                       group by c.title
1524                       order by cnt desc, c.title asc
1525                   ";
1526         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1527         return $result;
1528     }
1529 
1530     /**
1531      * @return array
1532      */
1533     public function getUserActiveProjects($member_id, $limit = null, $offset = null)
1534     {
1535         // for member me page
1536         $sql = "
1537                         SELECT
1538                         `p`.`project_id`,
1539                         `p`.`title`,
1540                         `p`.`created_at`  AS `project_created_at`,
1541                         `p`.`changed_at` AS `project_changed_at`,
1542                         `pr`.`likes` AS count_likes,
1543                         `pr`.`dislikes`AS count_dislikes,
1544                         IFNULL(pr.score_with_pling, 500) AS laplace_score,
1545                         `p`.`member_id`,
1546                         `cat`.`title` AS `catTitle`,
1547                         `p`.`project_category_id`,
1548                         `p`.`image_small`,
1549                         (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`,
1550                         c.cnt cntCategory
1551                         FROM `project` `p`
1552                         join project_category cat on p.project_category_id = cat.project_category_id
1553                         LEFT join  stat_rating_project AS pr  ON p.project_id = pr.project_id
1554                         left join stat_cnt_projects_catid_memberid c on p.project_category_id = c.project_category_id and p.member_id = c.member_id
1555                         WHERE `p`.`status` =100
1556                         and `p`.`type_id` = 1
1557                         AND `p`.`member_id` = :member_id
1558                         ORDER BY cntCategory desc,catTitle asc, `p`.`changed_at` DESC
1559 
1560         ";
1561 
1562         if (isset($limit)) {
1563             $sql = $sql . ' limit ' . $limit;
1564         }
1565 
1566         if (isset($offset)) {
1567             $sql = $sql . ' offset ' . $offset;
1568         }
1569 
1570         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1571         if ($result) {
1572             return $this->generateRowClass($result);
1573         } else {
1574             return null;
1575         }
1576     }
1577 
1578     /**
1579      * @return array
1580      */
1581     public function getUserActiveProjectsDuplicatedSourceurl($member_id, $limit = null, $offset = null)
1582     {
1583         // for member me page
1584         $sql = "
1585                       select * from
1586                       (
1587                       SELECT
1588                             `p`.`project_id`,
1589                             `p`.`title`,
1590                             `p`.`created_at`  AS `project_created_at`,
1591                             `p`.`changed_at` AS `project_changed_at`,
1592                             `pr`.`likes` AS count_likes,
1593                             `pr`.`dislikes`AS count_dislikes,
1594                              IFNULL(pr.score_with_pling, 500) AS laplace_score,
1595                             `p`.`member_id`,
1596                             `cat`.`title` AS `catTitle`,
1597                             `p`.`project_category_id`,
1598                             `p`.`image_small`,
1599                             (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`,
1600                             c.cnt cntCategory,
1601                               (select count(1) from stat_projects_source_url s where TRIM(TRAILING '/' FROM p.source_url)  = s.source_url) as cntDuplicates
1602                             FROM `project` `p`
1603                             join project_category cat on p.project_category_id = cat.project_category_id
1604                             left join stat_cnt_projects_catid_memberid c on p.project_category_id = c.project_category_id and p.member_id = c.member_id
1605                             LEFT join  stat_rating_project AS pr  ON p.project_id = pr.project_id
1606                             WHERE `p`.`status` =100
1607                             and `p`.`type_id` = 1
1608                             AND `p`.`member_id` = :member_id
1609                             ORDER BY cntCategory desc,catTitle asc, `p`.`changed_at` DESC
1610                             ) t where t.cntDuplicates >1
1611 
1612         ";
1613 
1614         if (isset($limit)) {
1615             $sql = $sql . ' limit ' . $limit;
1616         }
1617 
1618         if (isset($offset)) {
1619             $sql = $sql . ' offset ' . $offset;
1620         }
1621 
1622         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1623         if ($result) {
1624             return $this->generateRowClass($result);
1625         } else {
1626             return null;
1627         }
1628     }
1629 
1630     /**
1631      * @return cnt
1632      */
1633     public function getOriginalProjectsForMemberCnt($member_id)
1634     {        
1635         $sql = "
1636             SELECT
1637             count(1) as cnt
1638             FROM stat_projects p
1639             inner join tag_object t on tag_id = 2451  and tag_group_id=11 and tag_type_id = 1 and is_deleted = 0
1640             and t.tag_object_id = p.project_id
1641             WHERE member_id = :member_id             
1642         ";
1643         $result = $this->_db->fetchRow($sql, array('member_id' => $member_id));
1644         if ($result) {
1645             return $result['cnt'];
1646         } else {
1647             return 0;
1648         }
1649     }
1650 
1651     /**
1652      * @return cnt
1653      */
1654     public function getOriginalProjectsForMember($member_id, $limit=null, $offset=null)
1655     {        
1656         $sql = "
1657             SELECT
1658             *
1659             FROM stat_projects p
1660             inner join tag_object t on tag_id = 2451  and tag_group_id=11 and tag_type_id = 1 and is_deleted = 0
1661             and t.tag_object_id = p.project_id
1662             WHERE member_id = :member_id                       
1663         ";
1664 
1665         if (isset($limit)) {
1666             $sql = $sql . ' limit ' . $limit;
1667         }
1668 
1669         if (isset($offset)) {
1670             $sql = $sql . ' offset ' . $offset;
1671         }
1672 
1673         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1674         if ($result) {
1675             return $this->generateRowClass($result);
1676         } else {
1677             return null;
1678         }
1679      
1680     }
1681 
1682      /**
1683      * @return int
1684      */
1685     public function getUnpublishedProjectsForMemberCnt($member_id)
1686     {
1687         // for member me page
1688         $sql = "
1689                         SELECT
1690                         count(1) as cnt
1691                         FROM `project` `p`                        
1692                         WHERE `p`.`status` = 40
1693                         and `p`.`type_id` = 1
1694                         AND `p`.`member_id` = :member_id                        
1695         ";
1696         $result = $this->_db->fetchRow($sql, array('member_id' => $member_id));
1697         if ($result) {
1698             return $result['cnt'];
1699         } else {
1700             return 0;
1701         }
1702     }
1703     
1704 
1705     /**
1706      * @return array
1707      */
1708     public function getUnpublishedProjectsForMember($member_id, $limit = null, $offset = null)
1709     {
1710         // for member me page
1711         $sql = "
1712                         SELECT
1713                         `p`.`project_id`,
1714                         `p`.`title`,
1715                         `p`.`created_at`  AS `project_created_at`,
1716                         `p`.`changed_at` AS `project_changed_at`,
1717                         `pr`.`likes` AS count_likes,
1718                         `pr`.`dislikes`AS count_dislikes,
1719                         IFNULL(pr.score_with_pling, 500) AS laplace_score,
1720                         `p`.`member_id`,
1721                         `cat`.`title` AS `catTitle`,
1722                         `p`.`project_category_id`,
1723                         `p`.`image_small`,
1724                         (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`
1725                         FROM `project` `p`
1726                         join project_category cat on p.project_category_id = cat.project_category_id
1727                         LEFT join  stat_rating_project AS pr  ON p.project_id = pr.project_id
1728                         WHERE `p`.`status` = 40
1729                         and `p`.`type_id` = 1
1730                         AND `p`.`member_id` = :member_id 
1731                         ORDER BY catTitle asc, `p`.`changed_at` DESC
1732 
1733         ";
1734 
1735         if (isset($limit)) {
1736             $sql = $sql . ' limit ' . $limit;
1737         }
1738 
1739         if (isset($offset)) {
1740             $sql = $sql . ' offset ' . $offset;
1741         }
1742 
1743         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1744         if ($result) {
1745             return $this->generateRowClass($result);
1746         } else {
1747             return null;
1748         }
1749     }
1750 
1751     
1752      /**
1753      * @return int
1754      */
1755     public function getDeletedProjectsForMemberCnt($member_id)
1756     {
1757         // for member me page
1758         $sql = "
1759                         SELECT
1760                         count(1) as cnt
1761                         FROM `project` `p`                        
1762                         WHERE `p`.`status` = 30
1763                         and `p`.`type_id` = 1
1764                         AND `p`.`member_id` = :member_id                        
1765         ";
1766         $result = $this->_db->fetchRow($sql, array('member_id' => $member_id));
1767         if ($result) {
1768             return $result['cnt'];
1769         } else {
1770             return 0;
1771         }
1772     }
1773     
1774 
1775     /**
1776      * @return array
1777      */
1778     public function getDeletedProjectsForMember($member_id, $limit = null, $offset = null)
1779     {
1780         // for member me page
1781         $sql = "
1782                         SELECT
1783                         `p`.`project_id`,
1784                         `p`.`title`,
1785                         `p`.`created_at`  AS `project_created_at`,
1786                         `p`.`changed_at` AS `project_changed_at`,
1787                         `pr`.`likes` AS count_likes,
1788                         `pr`.`dislikes`AS count_dislikes,
1789                         IFNULL(pr.score_with_pling, 500) AS laplace_score,
1790                         `p`.`member_id`,
1791                         `cat`.`title` AS `catTitle`,
1792                         `p`.`project_category_id`,
1793                         `p`.`image_small`,
1794                         (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`
1795                         FROM `project` `p`
1796                         join project_category cat on p.project_category_id = cat.project_category_id
1797                         LEFT join  stat_rating_project AS pr  ON p.project_id = pr.project_id
1798                         WHERE `p`.`status` = 30
1799                         and `p`.`type_id` = 1
1800                         AND `p`.`member_id` = :member_id 
1801                         ORDER BY catTitle asc, `p`.`changed_at` DESC
1802 
1803         ";
1804 
1805         if (isset($limit)) {
1806             $sql = $sql . ' limit ' . $limit;
1807         }
1808 
1809         if (isset($offset)) {
1810             $sql = $sql . ' offset ' . $offset;
1811         }
1812 
1813         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1814         if ($result) {
1815             return $this->generateRowClass($result);
1816         } else {
1817             return null;
1818         }
1819     }
1820     
1821     public function fetchFilesForProjects($projects)
1822     {
1823 
1824         $ids=[];
1825         foreach ($projects as $p) {
1826             $ids[] = $p->project_id;
1827         }        
1828         $sql = "
1829                 select 
1830                 p.project_id
1831                 ,f.id
1832                 ,f.name
1833                 ,f.type
1834                 ,f.size
1835                 ,f.title
1836                 ,f.collection_id
1837                 from stat_projects p, ppload.ppload_files f
1838                 where p.ppload_collection_id = f.collection_id
1839                 and f.active = 1 
1840                 and p.project_id in ( ".implode(',', $ids).")
1841         ";      
1842         $result = $this->_db->fetchAll($sql);
1843         return $result;
1844     }
1845     public function fetchFilesForProject($project_id)
1846     {
1847    
1848         $sql = "
1849                 select 
1850                 f.id
1851                 ,f.name
1852                 ,f.type
1853                 ,f.size
1854                 ,f.title
1855                 ,f.collection_id
1856                 from stat_projects p, ppload.ppload_files f
1857                 where p.ppload_collection_id = f.collection_id
1858                 and f.active = 1 
1859                 and p.project_id = :project_id
1860         ";      
1861         $result = $this->_db->fetchAll($sql,array("project_id"=>$project_id));
1862         return $result;
1863     }
1864     /**
1865      * @param int      $member_id
1866      * @param int|null $limit
1867      * @param int|null $offset
1868      *
1869      * @return null|Zend_Db_Table_Row_Abstract
1870      */
1871     public function fetchAllFeaturedProjectsForMember($member_id, $limit = null, $offset = null)
1872     {
1873         // for member me page
1874         $sql = "
1875                           SELECT
1876                           `p`.`project_id`,
1877                           `p`.`title`,
1878                           `p`.`created_at`  AS `project_created_at`,
1879                           `p`.`changed_at` AS `project_changed_at`,
1880                           `p`.`count_likes`,
1881                           `p`.`count_dislikes`,
1882                           `p`.`laplace_score`,
1883                           `p`.`member_id`,
1884                           `p`.`cat_title` AS `catTitle`,
1885                           `p`.`image_small`,
1886                           (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`
1887                           FROM `stat_projects` `p`
1888                           WHERE `p`.`status` =100
1889                           AND `p`.`type_id` = 1
1890                           AND `featured` = 1
1891                           AND `p`.`member_id` = :member_id
1892                           ORDER BY `p`.`changed_at` DESC
1893           ";
1894 
1895         if (isset($limit)) {
1896             $sql = $sql . ' limit ' . $limit;
1897         }
1898 
1899         if (isset($offset)) {
1900             $sql = $sql . ' offset ' . $offset;
1901         }
1902 
1903         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1904         if ($result) {
1905             return $this->generateRowClass($result);
1906         } else {
1907             return null;
1908         }
1909     }
1910 
1911 
1912     /**
1913      * @param int      $member_id
1914      * @param int|null $limit
1915      * @param int|null $offset
1916      *
1917      * @return null|Zend_Db_Table_Row_Abstract
1918      */
1919     public function fetchAllCollectionsForMember($member_id, $limit = null, $offset = null)
1920     {
1921         // for member me page
1922         $sql = "
1923                           SELECT
1924                           `p`.`project_id`,
1925                           `p`.`title`,
1926                           `p`.`created_at`  AS `project_created_at`,
1927                           `p`.`changed_at` AS `project_changed_at`,
1928                           `p`.`count_likes`,
1929                           `p`.`count_dislikes`,
1930                           `p`.`laplace_score`,
1931                           `p`.`member_id`,
1932                           `p`.`cat_title` AS `catTitle`,
1933                           `p`.`image_small`,
1934                           (SELECT count(1) FROM `project_plings` `l` WHERE `p`.`project_id` = `l`.`project_id` AND `l`.`is_deleted` = 0 AND `l`.`is_active` = 1 ) `countplings`
1935                           FROM `stat_projects` `p`
1936                           WHERE `p`.`status` =100
1937                           AND `p`.`type_id` = 3
1938                           AND `p`.`member_id` = :member_id
1939                           ORDER BY `p`.`changed_at` DESC
1940           ";
1941 
1942         if (isset($limit)) {
1943             $sql = $sql . ' limit ' . $limit;
1944         }
1945 
1946         if (isset($offset)) {
1947             $sql = $sql . ' offset ' . $offset;
1948         }
1949 
1950         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
1951         if ($result) {
1952             return $this->generateRowClass($result);
1953         } else {
1954             return null;
1955         }
1956     }
1957 
1958     /**
1959      * @param string   $orderby
1960      * @param int|null $limit
1961      * @param int|null $offset
1962      *
1963      * @return array
1964      */
1965     public function fetchDuplicatedSourceProjects($orderby = 'source_url asc', $limit = null, $offset = null)
1966     {
1967         $sql = "
1968             SELECT
1969             `source_url`
1970             ,count(1) AS `cnt`,
1971             GROUP_CONCAT(`p`.`project_id` ORDER BY `p`.`created_at`) `pids`
1972             FROM `stat_projects_source_url` `p`
1973             GROUP BY `source_url`
1974             HAVING count(1)>1
1975        ";
1976         if (isset($orderby)) {
1977             $sql = $sql . '  order by ' . $orderby;
1978         }
1979 
1980         if (isset($limit)) {
1981             $sql .= ' limit ' . (int)$limit;
1982         }
1983 
1984         if (isset($offset)) {
1985             $sql .= ' offset ' . (int)$offset;
1986         }
1987         $result = $this->_db->fetchAll($sql);
1988 
1989         return $result;
1990     }
1991 
1992     /**
1993      * @return mixed
1994      */
1995     public function getTotalCountDuplicates()
1996     {
1997 
1998         $sql = "
1999           SELECT count(1) AS `cnt` FROM
2000           (
2001                       SELECT
2002                        `source_url`
2003                        ,count(1) AS `cnt`,
2004                        GROUP_CONCAT(`p`.`project_id` ORDER BY `p`.`created_at`) `pids`
2005                        FROM `stat_projects_source_url` `p`
2006                        GROUP BY `p`.`source_url`
2007                        HAVING count(1)>1
2008           ) `a`
2009       ";
2010         $result = $this->_db->fetchAll($sql);
2011 
2012         return $result[0]['cnt'];;
2013     }
2014 
2015     /**
2016      * @param string $source_url
2017      *
2018      * @return mixed
2019      */
2020     public function getCountSourceUrl($source_url)
2021     {
2022         $last = substr($source_url, -1);
2023         if ($last == '/') {
2024             $source_url = substr($source_url, 0, -1);
2025         }
2026         $sql = "
2027             SELECT count(1) AS `cnt` FROM
2028             `stat_projects_source_url` `p`
2029             WHERE `p`.`source_url`= :source_url
2030       ";
2031         $result = $this->_db->fetchAll($sql, array('source_url' => $source_url));
2032 
2033         return $result[0]['cnt'];
2034     }
2035 
2036 
2037     public function getSourceUrlProjects($source_url)
2038     {
2039         $last = substr($source_url, -1);
2040         if ($last == '/') {
2041             $source_url = substr($source_url, 0, -1);
2042         }
2043         $sql = "
2044             SELECT
2045                 p.project_id,
2046                 pj.title,
2047                 pj.member_id,
2048                 pj.created_at,
2049                 pj.changed_at,
2050                 m.username
2051                 FROM stat_projects_source_url p
2052                 inner join project pj on p.project_id = pj.project_id and pj.status=100
2053                 inner join member m on pj.member_id = m.member_id
2054             WHERE p.source_url= :source_url
2055       ";
2056         $result = $this->_db->fetchAll($sql, array('source_url' => $source_url));
2057 
2058         return $result;
2059     }
2060 
2061     /**
2062      * @param int $member_id
2063      *
2064      * @return mixed
2065      */
2066     public function getCountProjectsDuplicateSourceurl($member_id)
2067     {
2068 
2069         $sql = "
2070            SELECT count(1) AS `cnt`
2071            FROM
2072            (
2073               SELECT  `p`.`source_url`
2074               ,(SELECT count(1) FROM `stat_projects_source_url` `pp` WHERE `pp`.`source_url`=`p`.`source_url`) `cnt`
2075               FROM `stat_projects_source_url` `p`
2076               WHERE `p`.`member_id` = :member_id
2077            ) `t` WHERE `t`.`cnt`>1
2078       ";
2079         $result = $this->_db->fetchAll($sql, array('member_id' => $member_id));
2080 
2081         return $result[0]['cnt'];
2082     }
2083 
2084     /**
2085      * @param $ids
2086      *
2087      * @return Zend_Db_Table_Row_Abstract
2088      * @throws Zend_Db_Statement_Exception
2089      */
2090     public function fetchProjects($ids)
2091     {
2092         $sql = "SELECT * FROM stat_projects WHERE project_id in (" . $ids . ") order by project_id";
2093         $resultSet = $this->_db->fetchAll($sql);
2094 
2095         return $this->generateRowSet($resultSet);
2096     }
2097 
2098     /**
2099      * @param $project_id
2100      * @return true/false
2101      * @throws Zend_Db_Statement_Exception
2102      */
2103     public function validateDeleteProjectFromSpam($project_id)
2104     {
2105       //produkt ist ueber 6 monate alt oder produkt hat ueber 5 kommentare oder produkt hat minimum 1 pling
2106       // darf nicht gelöscht werden
2107       $sql ='select count_comments
2108             ,created_at
2109             , (created_at+ INTERVAL 6 MONTH < NOW()) is_old
2110             ,(select count(1) from project_plings f where f.project_id = p.project_id and f.is_deleted = 0) plings
2111             FROM project p where project_id =:project_id';
2112       $result = $this->_db->fetchRow($sql, array(
2113                             'project_id'     => $project_id,
2114             ));
2115 
2116       if($result['count_comments'] >5 || $result['is_old'] ==1 || $result['plings']>0)
2117       {
2118         return false;
2119       }
2120       return true;
2121     }
2122 
2123     
2124 
2125 }