<commit_before><?php

/**
 * This file is part of the MonVoisinFaitDuBio project.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Copyright (c) 2016 <NAME> - <EMAIL>
 * @license    MIT License
 * @Last Modified time: 2017-12-13 07:59:45
 */
 

namespace Biopen\GeoDirectoryBundle\Services;

use Doctrine\ODM\MongoDB\DocumentManager;
use Biopen\GeoDirectoryBundle\Document\ElementStatus;
use Biopen\GeoDirectoryBundle\Document\ModerationState;
use Biopen\GeoDirectoryBundle\Document\UserInteractionVote;
use Biopen\GeoDirectoryBundle\Document\VoteValue;
use Symfony\Component\Security\Core\SecurityContext;
use Biopen\CoreBundle\Services\ConfigurationService;
use Biopen\GeoDirectoryBundle\Services\ElementPendingService;
use Biopen\GeoDirectoryBundle\Services\ValidationType;

class ElementVoteService
{	
	/**
     * Constructor
     */
    public function __construct(DocumentManager $documentManager, SecurityContext $securityContext, ConfigurationService $confService, ElementPendingService $elementPendingService)
    {
        $this->em = $documentManager;
        $this->user = $securityContext->getToken() ? $securityContext->getToken()->getUser() : null;
        $this->confService = $confService; 
        $this->securityContext = $securityContext;
        $this->elementPendingService = $elementPendingService;
    }

    // Handle a vote (positive or negative) for pending elements
    public function voteForElement($element, $voteValue, $comment, $userMail = null)
    {
        // Check user don't vote for his own creation
        if ($element->isLastContributorEqualsTo($this->user, $userMail))
                return "Voyons voyons, vous ne comptiez quand même pas voter pour votre propre contribution si ? Laissez en un peu pour les autres !";  

        $hasAlreadyVoted = false;

        if ($this->confService->isUserAllowed('directModeration'))
        {
            $procedureCompleteMessage = $this->handleVoteProcedureComplete($element, ValidationType::Admin, $voteValue >= 1, $comment);
        }
        else 
        {
            // CHECK USER HASN'T ALREADY VOTED
            $currentVotes = $element->getVotes();            
            // if user is anonymous no need to check
            if ($userMail || $this->user)
            {
                foreach ($currentVotes as $oldVote) 
                {
                    if ($oldVote->isMadeBy($this->user, $userMail)) 
                    {
                        $hasAlreadyVoted = true;
                        $vote = $oldVote;
                    }
                }
            }

            if (!$hasAlreadyVoted) $vote = new UserInteractionVote();       
            
            $vote->setValue($voteValue);
            $vote->setElement($element);
            $vote->updateUserInformation($this->securityContext, $userMail);
            if ($comment) $vote->setComment($comment);

            if (!$hasAlreadyVoted) $element->getCurrContribution()->addVote($vote);

            $procedureCompleteMessage = $this->checkVotes($element);
        }

        $this->em->persist($element);
        $this->em->flush();

        $resultMessage = $hasAlreadyVoted ? 'Merci ' . $this->user . ' : votre vote a bien été modifié !' : 'Merci de votre contribution !';
        if ($procedureCompleteMessage) $resultMessage .= '</br>' . $procedureCompleteMessage;

        return $resultMessage;
    }

    /*
    * Check vote on PENDING Element
    * Differents conditions :
    *   - Enough votes to change status
    *   - Not too much opposites votes
    *   - Waiting for minimum days after contribution to validate or invalidate
    * 
    * If an element is pending for too long, it's set in Moderation
    *
    * This action is called when user vote, and with a CRON job every days
    */
    public function checkVotes($element)
    {
        $currentVotes = $element->getVotes();
        $nbrePositiveVote = 0;
        $nbreNegativeVote = 0;

        $diffDate = time() - $element->getStatusChangedAt()->getTimestamp();
        $daysFromContribution = floor( $diffDate / (60 * 60 * 24));

        foreach ($currentVotes as $key => $vote) 
        {
           $vote->getValue() >= 0 ? $nbrePositiveVote++ : $nbreNegativeVote++;
        }

        $enoughDays = $daysFromContribution >= $this->confService->getConfig()->getMinDayBetweenContributionAndCollaborativeValidation();
        $maxOppositeVoteTolerated = $this->confService->getConfig()->getMaxOppositeVoteTolerated();
        $minVotesToChangeStatus = $this->confService->getConfig()->getMinVoteToChangeStatus();
        $minVotesToForceChangeStatus = $this->confService->getConfig()->getMinVoteToForceChangeStatus();

        if ($nbrePositiveVote >= $minVotesToChangeStatus)
        {
            if ($nbreNegativeVote <= $maxOppositeVoteTolerated) 
            {
                if ($enoughDays || $nbrePositiveVote >= $minVotesToForceChangeStatus) return $this->handleVoteProcedureComplete($element, ValidationType::Collaborative, true);<commit_msg>Fix getting contribution created At<commit_after><?php

/**
 * This file is part of the MonVoisinFaitDuBio project.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Copyright (c) 2016 <NAME> - <EMAIL>
 * @license    MIT License
 * @Last Modified time: 2017-12-29 20:06:22
 */
 

namespace Biopen\GeoDirectoryBundle\Services;

use Doctrine\ODM\MongoDB\DocumentManager;
use Biopen\GeoDirectoryBundle\Document\ElementStatus;
use Biopen\GeoDirectoryBundle\Document\ModerationState;
use Biopen\GeoDirectoryBundle\Document\UserInteractionVote;
use Biopen\GeoDirectoryBundle\Document\VoteValue;
use Symfony\Component\Security\Core\SecurityContext;
use Biopen\CoreBundle\Services\ConfigurationService;
use Biopen\GeoDirectoryBundle\Services\ElementPendingService;
use Biopen\GeoDirectoryBundle\Services\ValidationType;

class ElementVoteService
{	
	/**
     * Constructor
     */
    public function __construct(DocumentManager $documentManager, SecurityContext $securityContext, ConfigurationService $confService, ElementPendingService $elementPendingService)
    {
        $this->em = $documentManager;
        $this->user = $securityContext->getToken() ? $securityContext->getToken()->getUser() : null;
        $this->confService = $confService; 
        $this->securityContext = $securityContext;
        $this->elementPendingService = $elementPendingService;
    }

    // Handle a vote (positive or negative) for pending elements
    public function voteForElement($element, $voteValue, $comment, $userMail = null)
    {
        // Check user don't vote for his own creation
        if ($element->isLastContributorEqualsTo($this->user, $userMail))
                return "Voyons voyons, vous ne comptiez quand même pas voter pour votre propre contribution si ? Laissez en un peu pour les autres !";  

        $hasAlreadyVoted = false;

        if ($this->confService->isUserAllowed('directModeration'))
        {
            $procedureCompleteMessage = $this->handleVoteProcedureComplete($element, ValidationType::Admin, $voteValue >= 1, $comment);
        }
        else 
        {
            // CHECK USER HASN'T ALREADY VOTED
            $currentVotes = $element->getVotes();            
            // if user is anonymous no need to check
            if ($userMail || $this->user)
            {
                foreach ($currentVotes as $oldVote) 
                {
                    if ($oldVote->isMadeBy($this->user, $userMail)) 
                    {
                        $hasAlreadyVoted = true;
                        $vote = $oldVote;
                    }
                }
            }

            if (!$hasAlreadyVoted) $vote = new UserInteractionVote();       
            
            $vote->setValue($voteValue);
            $vote->setElement($element);
            $vote->updateUserInformation($this->securityContext, $userMail);
            if ($comment) $vote->setComment($comment);

            if (!$hasAlreadyVoted) $element->getCurrContribution()->addVote($vote);

            $procedureCompleteMessage = $this->checkVotes($element);
        }

        $this->em->persist($element);
        $this->em->flush();

        $resultMessage = $hasAlreadyVoted ? 'Merci ' . $this->user . ' : votre vote a bien été modifié !' : 'Merci de votre contribution !';
        if ($procedureCompleteMessage) $resultMessage .= '</br>' . $procedureCompleteMessage;

        return $resultMessage;
    }

    /*
    * Check vote on PENDING Element
    * Differents conditions :
    *   - Enough votes to change status
    *   - Not too much opposites votes
    *   - Waiting for minimum days after contribution to validate or invalidate
    * 
    * If an element is pending for too long, it's set in Moderation
    *
    * This action is called when user vote, and with a CRON job every days
    */
    public function checkVotes($element)
    {
        $currentVotes = $element->getVotes();
        $nbrePositiveVote = 0;
        $nbreNegativeVote = 0;

        $diffDate = time() - $element->getCurrContribution()->getCreatedAt()->getTimestamp();
        $daysFromContribution = floor( $diffDate / (60 * 60 * 24));

        foreach ($currentVotes as $key => $vote) 
        {
           $vote->getValue() >= 0 ? $nbrePositiveVote++ : $nbreNegativeVote++;
        }

        $enoughDays = $daysFromContribution >= $this->confService->getConfig()->getMinDayBetweenContributionAndCollaborativeValidation();
        $maxOppositeVoteTolerated = $this->confService->getConfig()->getMaxOppositeVoteTolerated();
        $minVotesToChangeStatus = $this->confService->getConfig()->getMinVoteToChangeStatus();
        $minVotesToForceChangeStatus = $this->confService->getConfig()->getMinVoteToForceChangeStatus();

        if ($nbrePositiveVote >= $minVotesToChangeStatus)
        {
            if ($nbreNegativeVote <= $maxOppositeVoteTolerated) 
            {
                if ($enoughDays || $nbrePositiveVote >= $minVotesToForceChangeStatus) return $this->handleVoteProcedureComplete($element, ValidationType::Collaborative, true);
{'fraction_non_alphanumeric': 0.11055767164762184, 'fraction_numerical': 0.005469284109776346, 'mean_word_length': 2.7730287398673545, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 116, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2651493', 'n_tokens_mistral': 2939, 'n_tokens_neox': 2753, 'n_words': 641}