<commit_before><?php

/**
 *  ocs-webserver
 *
 *  Copyright 2016 by pling GmbH.
 *
 *    This file is part of ocs-webserver.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
class ProductController extends Local_Controller_Action_DomainSwitch
{

    const IMAGE_SMALL_UPLOAD = 'image_small_upload';
    const IMAGE_BIG_UPLOAD = 'image_big_upload';
    /**
     * Zend_Controller_Request_Abstract object wrapping the request environment
     *
     * @var Zend_Controller_Request_Http
     */
    protected $_request = null;
    /** @var  int */
    protected $_projectId;
    /** @var  int */
    protected $_collectionId;
    /** @var  Zend_Auth */
    protected $_auth;
    /** @var  string */
    protected $_browserTitlePrepend;

    public function init()
    {
        parent::init();
        $this->_projectId = (int)$this->getParam('project_id');
        $this->_collectionId = (int)$this->getParam('collection_id');
        $this->_auth = Zend_Auth::getInstance();
        $this->_browserTitlePrepend = $this->templateConfigData['head']['browser_title_prepend'];
    }

    public function ratingAction()
    {
        $this->_helper->layout()->disableLayout();
        if (array_key_exists($this->_projectId, $this->_authMember->projects)) {
            return;
        }
        $userRating = (int)$this->getParam('rate', 0);
        $modelRating = new Default_Model_DbTable_ProjectRating();
        $modelRating->rateForProject($this->_projectId, $this->_authMember->member_id, $userRating);
    }

    public function indexAction()
    {
        if (!empty($this->_collectionId)) {
            $modelProduct = new Default_Model_Project();
            $productInfo = $modelProduct->fetchProductForCollectionId($this->_collectionId);
            $this->_projectId = $productInfo->project_id;
        }


        if (empty($this->_projectId)) {
            $this->redirect('/explore');
        }

        $this->view->paramPageId = (int)$this->getParam('page');
        $this->view->member_id = null;
        if(null != $this->_authMember && null != $this->_authMember->member_id) {
            $this->view->member_id = $this->_authMember->member_id;
        }

        //        $this->fetchDataForIndexView();

        $modelProduct = new Default_Model_Project();
        $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
        $this->view->product = $productInfo;
        if (empty($this->view->product)) {
            throw new Zend_Controller_Action_Exception('This page does not exist', 404);
        }
        $this->view->cat_id = $this->view->product->project_category_id;

        //create ppload download hash: secret + collection_id + expire-timestamp
        $salt = PPLOAD_DOWNLOAD_SECRET;
        $collectionID = $this->view->product->ppload_collection_id;
        $timestamp = time() + 3600; // one hour valid
        $hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying

        $this->view->download_hash = $hash;
        $this->view->download_timestamp = $timestamp;

        $helperUserIsOwner = new Default_View_Helper_UserIsOwner();
        $helperIsProjectActive = new Default_View_Helper_IsProjectActive();
        if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status))
            AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id))
        ) {
            throw new Zend_Controller_Action_Exception('This page does not exist', 404);
        }

        if (APPLICATION_ENV != 'searchbotenv') {
            $tablePageViews = new Default_Model_DbTable_StatPageViews();
            $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(),
                $this->_authMember->member_id);
        }
    }

    public function showAction()
    {
        $this->view->authMember = $this->_authMember;
        $this->_helper->viewRenderer('index');
        $this->indexAction();
    }

    public function addAction()
    {
        $form = new Default_Form_Product();

        $this->view->member = $this->_authMember;
        $this->view->form = $form;
        $this->view->mode = 'add';

        if ($this->_request->isGet()) {
            return;
        }

        if (isset($_POST['cancel'])) { // user cancel function
            $this->redirect('/member/' . $this->_authMember->member_id . '/news/');
        }

        if (false === $form->isValid($_POST)) { // form not valid
            $this->view->form = $form;
            $this->view->error = 1;

            return;
        }

        $values = $form->getValues();

        $imageModel = new Default_Model_DbTable_Image();
        try {
            $values['image_small'] = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD));
        } catch (Exception $e) {
            Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true));
        }

        // form was valid, so we can set status to active
        $values['status'] = Default_Model_DbTable_Project::PROJECT_ACTIVE;
        
        // save new project
        $modelProject = new Default_Model_Project();

        Zend_Registry::get('logger')->info(__METHOD__ . ' - $post: ' . print_r($_POST, true));
        Zend_Registry::get('logger')->info(__METHOD__ . ' - $files: ' . print_r($_FILES, true));
        Zend_Registry::get('logger')->info(__METHOD__ . ' _ input values: ' . print_r($values, true));

        $newProject = null;
        try {
            if (isset($values['project_id'])) {
                $newProject = $modelProject->updateProject($values['project_id'], $values);
            } else {
                $newProject = $modelProject->createProject($this->_authMember->member_id, $values, $this->_authMember->username);
            }
        } catch (Exception $exc) {
            Zend_Registry::get('logger')->warn(__METHOD__ . ' - traceString: ' . $exc->getTraceAsString());
        }

        if (!$newProject) {
            $this->_helper->flashMessenger->addMessage('<p class="text-error">You did not choose a Category in the last level.</p>');
            $this->forward('add');

            return;
        }

        //update the gallery pics
        $mediaServerUrls = $this->saveGalleryPics($form->gallery->upload->upload_picture);
        $modelProject->updateGalleryPictures($newProject->project_id, $mediaServerUrls);
        
        $licenseTag = $form->getElement('license_tag_id')->getValue();
        $modelTags->saveLicenseTagForProject($newProject->project_id, $licenseTag);

        //If there is no Logo, we take the 1. gallery pic
        if (!isset($values['image_small']) || $values['image_small'] == '') {
            $values['image_small'] = $mediaServerUrls[0];
            $newProject = $modelProject->updateProject($newProject->project_id, $values);
        }

        //New Project in Session, for AuthValidation (owner)
        $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id);
        //        $this->auth->getStorage()->write($this->auth->getIdentity());

        // if ($values['tags']) {
        //     $modelTags = new Default_Model_Tags();
        //     $modelTags->processTags($newProject->project_id, implode(',',$values['tags']), Default_Model_Tags::TAG_TYPE_PROJECT);
        // }


        $modelTags = new Default_Model_Tags();
        if ($values['tags']){<commit_msg>tag license<commit_after><?php

/**
 *  ocs-webserver
 *
 *  Copyright 2016 by pling GmbH.
 *
 *    This file is part of ocs-webserver.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
class ProductController extends Local_Controller_Action_DomainSwitch
{

    const IMAGE_SMALL_UPLOAD = 'image_small_upload';
    const IMAGE_BIG_UPLOAD = 'image_big_upload';
    /**
     * Zend_Controller_Request_Abstract object wrapping the request environment
     *
     * @var Zend_Controller_Request_Http
     */
    protected $_request = null;
    /** @var  int */
    protected $_projectId;
    /** @var  int */
    protected $_collectionId;
    /** @var  Zend_Auth */
    protected $_auth;
    /** @var  string */
    protected $_browserTitlePrepend;

    public function init()
    {
        parent::init();
        $this->_projectId = (int)$this->getParam('project_id');
        $this->_collectionId = (int)$this->getParam('collection_id');
        $this->_auth = Zend_Auth::getInstance();
        $this->_browserTitlePrepend = $this->templateConfigData['head']['browser_title_prepend'];
    }

    public function ratingAction()
    {
        $this->_helper->layout()->disableLayout();
        if (array_key_exists($this->_projectId, $this->_authMember->projects)) {
            return;
        }
        $userRating = (int)$this->getParam('rate', 0);
        $modelRating = new Default_Model_DbTable_ProjectRating();
        $modelRating->rateForProject($this->_projectId, $this->_authMember->member_id, $userRating);
    }

    public function indexAction()
    {
        if (!empty($this->_collectionId)) {
            $modelProduct = new Default_Model_Project();
            $productInfo = $modelProduct->fetchProductForCollectionId($this->_collectionId);
            $this->_projectId = $productInfo->project_id;
        }


        if (empty($this->_projectId)) {
            $this->redirect('/explore');
        }

        $this->view->paramPageId = (int)$this->getParam('page');
        $this->view->member_id = null;
        if(null != $this->_authMember && null != $this->_authMember->member_id) {
            $this->view->member_id = $this->_authMember->member_id;
        }

        //        $this->fetchDataForIndexView();

        $modelProduct = new Default_Model_Project();
        $productInfo = $modelProduct->fetchProductInfo($this->_projectId);
        $this->view->product = $productInfo;
        if (empty($this->view->product)) {
            throw new Zend_Controller_Action_Exception('This page does not exist', 404);
        }
        $this->view->cat_id = $this->view->product->project_category_id;

        //create ppload download hash: secret + collection_id + expire-timestamp
        $salt = PPLOAD_DOWNLOAD_SECRET;
        $collectionID = $this->view->product->ppload_collection_id;
        $timestamp = time() + 3600; // one hour valid
        $hash = md5($salt . $collectionID . $timestamp); // order isn't important at all... just do the same when verifying

        $this->view->download_hash = $hash;
        $this->view->download_timestamp = $timestamp;

        $helperUserIsOwner = new Default_View_Helper_UserIsOwner();
        $helperIsProjectActive = new Default_View_Helper_IsProjectActive();
        if ((false === $helperIsProjectActive->isProjectActive($this->view->product->project_status))
            AND (false === $helperUserIsOwner->UserIsOwner($this->view->product->member_id))
        ) {
            throw new Zend_Controller_Action_Exception('This page does not exist', 404);
        }

        if (APPLICATION_ENV != 'searchbotenv') {
            $tablePageViews = new Default_Model_DbTable_StatPageViews();
            $tablePageViews->savePageView($this->_projectId, $this->getRequest()->getClientIp(),
                $this->_authMember->member_id);
        }
    }

    public function showAction()
    {
        $this->view->authMember = $this->_authMember;
        $this->_helper->viewRenderer('index');
        $this->indexAction();
    }

    public function addAction()
    {
        $form = new Default_Form_Product();

        $this->view->member = $this->_authMember;
        $this->view->form = $form;
        $this->view->mode = 'add';

        if ($this->_request->isGet()) {
            return;
        }

        if (isset($_POST['cancel'])) { // user cancel function
            $this->redirect('/member/' . $this->_authMember->member_id . '/news/');
        }

        if (false === $form->isValid($_POST)) { // form not valid
            $this->view->form = $form;
            $this->view->error = 1;

            return;
        }

        $values = $form->getValues();

        $imageModel = new Default_Model_DbTable_Image();
        try {
            $values['image_small'] = $imageModel->saveImage($form->getElement(self::IMAGE_SMALL_UPLOAD));
        } catch (Exception $e) {
            Zend_Registry::get('logger')->err(__METHOD__ . ' - ERROR upload productPicture - ' . print_r($e, true));
        }

        // form was valid, so we can set status to active
        $values['status'] = Default_Model_DbTable_Project::PROJECT_ACTIVE;
        
        // save new project
        $modelProject = new Default_Model_Project();

        Zend_Registry::get('logger')->info(__METHOD__ . ' - $post: ' . print_r($_POST, true));
        Zend_Registry::get('logger')->info(__METHOD__ . ' - $files: ' . print_r($_FILES, true));
        Zend_Registry::get('logger')->info(__METHOD__ . ' _ input values: ' . print_r($values, true));

        $newProject = null;
        try {
            if (isset($values['project_id'])) {
                $newProject = $modelProject->updateProject($values['project_id'], $values);
            } else {
                $newProject = $modelProject->createProject($this->_authMember->member_id, $values, $this->_authMember->username);
            }
        } catch (Exception $exc) {
            Zend_Registry::get('logger')->warn(__METHOD__ . ' - traceString: ' . $exc->getTraceAsString());
        }

        if (!$newProject) {
            $this->_helper->flashMessenger->addMessage('<p class="text-error">You did not choose a Category in the last level.</p>');
            $this->forward('add');

            return;
        }

        //update the gallery pics
        $mediaServerUrls = $this->saveGalleryPics($form->gallery->upload->upload_picture);
        $modelProject->updateGalleryPictures($newProject->project_id, $mediaServerUrls);
        
        $modelTags = new Default_Model_Tags();
        
        $licenseTag = $form->getElement('license_tag_id')->getValue();
        $modelTags->saveLicenseTagForProject($newProject->project_id, $licenseTag);

        //If there is no Logo, we take the 1. gallery pic
        if (!isset($values['image_small']) || $values['image_small'] == '') {
            $values['image_small'] = $mediaServerUrls[0];
            $newProject = $modelProject->updateProject($newProject->project_id, $values);
        }

        //New Project in Session, for AuthValidation (owner)
        $this->_auth->getIdentity()->projects[$newProject->project_id] = array('project_id' => $newProject->project_id);
        //        $this->auth->getStorage()->write($this->auth->getIdentity());

        // if ($values['tags']) {
        //     $modelTags = new Default_Model_Tags();
        //     $modelTags->processTags($newProject->project_id, implode(',',$values['tags']), Default_Model_Tags::TAG_TYPE_PROJECT);
        // }


        $modelTags = new Default_Model_Tags();
        if ($values['tags']){
{'fraction_non_alphanumeric': 0.1443873179091688, 'fraction_numerical': 0.0024482800832415228, 'mean_word_length': 2.664274501009195, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 283, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '826792', 'n_tokens_mistral': 4649, 'n_tokens_neox': 4514, 'n_words': 941}