Element.php 37.8 KB
Newer Older
1 2 3
<?php

/**
Sebastian Castro's avatar
Sebastian Castro committed
4
 * This file is part of the GoGoCarto project.
5 6 7 8 9
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Copyright (c) 2016 Sebastian Castro - 90scastro@gmail.com
 * @license    MIT License
10
 * @Last Modified time: 2018-06-17 16:48:39
11 12
 */
 
13
namespace Biopen\GeoDirectoryBundle\Document;
14

15
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
16
use JMS\Serializer\Annotation\Expose;
17
use Gedmo\Mapping\Annotation as Gedmo;
18
use Vich\UploaderBundle\Mapping\Annotation as Vich;
19
use Biopen\CoreBundle\Document\EmbeddedImage;
20

21 22
abstract class ElementStatus
{
23
    const DynamicImportTemp = -7; // Temporary status used while importing  
Sebastian Castro's avatar
Sebastian Castro committed
24
    const Duplicate = -6;
25
    const ModifiedPendingVersion = -5;
26
    const Deleted = -4;
27 28
    const CollaborativeRefused = -3;
    const AdminRefused = -2;    
29 30
    const PendingModification = -1;
    const PendingAdd = 0;
31
    const AdminValidate = 1;
32 33
    const CollaborativeValidate = 2;
    const AddedByAdmin = 3; 
34
    const ModifiedByAdmin = 4; 
35
    const ModifiedByOwner = 5; 
36 37
    const ModifiedFromHash = 6; // in the emails we provide a link to edit the element with a hash validation
    const DynamicImport = 7; // Element imported from an ExternalSource, they cannot be edited        
38 39
}

40 41
abstract class ModerationState
{
42 43
    const GeolocError = -2;
    const NoOptionProvided = -1;     
44 45
    const NotNeeded = 0;
    const ReportsSubmitted = 1;
46
    const VotesConflicts = 2; 
47
    const PendingForTooLong = 3;
48
    const PotentialDuplicate = 4;         
49 50
}

Sebastian Castro's avatar
Sebastian Castro committed
51 52 53 54
/** 
* @MongoDB\EmbeddedDocument 
* @Vich\Uploadable
*/
55
class ElementImage extends EmbeddedImage
Sebastian Castro's avatar
Sebastian Castro committed
56 57 58 59
{
    protected $vichUploadFileKey = "element_image";
}

60 61 62
/**
 * Element
 *
63
 * @MongoDB\Document(repositoryClass="Biopen\GeoDirectoryBundle\Repository\ElementRepository")
64
 * @MongoDB\HasLifecycleCallbacks 
65
 * @Vich\Uploadable
66 67
 * @MongoDB\Indexes({
 *   @MongoDB\Index(keys={"geo"="2d"}),
Sebastian Castro's avatar
Sebastian Castro committed
68
 *   @MongoDB\Index(keys={"name"="text"})
69
 * })
70 71 72 73 74
 */
class Element
{
    /**
     * @var int
75
     *  
76
     * @MongoDB\Id(strategy="ALNUM")
77
     */
78
    public $id;
79

80
    /** 
81
     * See ElementStatus
Sebastian Castro's avatar
Sebastian Castro committed
82
     * @MongoDB\Field(type="int") @MongoDB\Index
83
     */
84
    private $status;
85

86
    /** 
87 88
     * If element need moderation we write here the type of modification needed
     * @MongoDB\Field(type="int")
89
     */
90
    private $moderationState = 0;
91

92 93 94
    /**
     * @var \stdClass
     *
Sebastian Castro's avatar
Sebastian Castro committed
95
     * Users can report some problem related to the Element (no more existing, wrong informations...)
96
     *
97
     * @MongoDB\ReferenceMany(targetDocument="Biopen\GeoDirectoryBundle\Document\UserInteractionReport", cascade={"all"})
98
     */
Sebastian Castro's avatar
Sebastian Castro committed
99
    private $reports;
100

101 102 103
    /**
     * @var \stdClass
     *
Sebastian Castro's avatar
Sebastian Castro committed
104
     * Hisotry of users contributions (add, edit, by whom, how many votes etc...)
105
     *
106
     * @MongoDB\ReferenceMany(targetDocument="Biopen\GeoDirectoryBundle\Document\UserInteractionContribution", cascade={"all"})
107
     */
108
    private $contributions;
109

110 111 112
    /**
     * @var \stdClass
     *
113 114 115
     * When a user propose a modification to an element, the modified element in saved in this attributes,
     * so we keep recording both versions (the old one and the new one) and so we can display the diff
     *
116
     * @MongoDB\ReferenceOne(targetDocument="Biopen\GeoDirectoryBundle\Document\Element", cascade={"all"})
117 118 119
     */
    private $modifiedElement;

120 121 122 123 124 125 126
    /**
     * Labels/Tags added to an element by specific organisations/people
     *
     * @MongoDB\ReferenceMany(targetDocument="Biopen\GeoDirectoryBundle\Document\Stamp", cascade={"all"})
     */
    private $stamps;

127 128
    /**
     * @var string
129
     * @MongoDB\Field(type="string")
130
     */
131
    public $name;
132

133 134 135
    /** 
    * @MongoDB\EmbedOne(targetDocument="Biopen\GeoDirectoryBundle\Document\Coordinates") 
    */
136
    public $geo;
137 138 139

    /**
     * @var string
140
     *
141
     * Complete address
142
     *    
143
     * @MongoDB\EmbedOne(targetDocument="Biopen\GeoDirectoryBundle\Document\PostalAddress") 
144
     */
145
    private $address;
146
    
147
    /**
148
     * @var \stdClass
149 150 151
     *
     * The options filled by the element, with maaybe some description attached to them
     *
152
     * @MongoDB\EmbedMany(targetDocument="Biopen\GeoDirectoryBundle\Document\OptionValue")
153
     */
154
    private $optionValues;
155

156 157 158 159 160 161
    /**
     * @var string
     * @MongoDB\Field(type="string")
     */
    private $optionsString;

162 163
    /** 
     * @var string 
Sebastian Castro's avatar
Sebastian Castro committed
164
     * @MongoDB\Field(type="string") @MongoDB\Index
165 166 167
     */ 
    private $email; 

168 169
    /**
     * @var \stdClass
170 171 172
     *
     * Structured OpenHours
     *
Sebastian Castro's avatar
Sebastian Castro committed
173
     * @MongoDB\EmbedOne(targetDocument="Biopen\GeoDirectoryBundle\Document\OpenHours")
174
     */
175
    private $openHours;
176

177 178 179
    /**
     * Images, photos, logos, linked to an element
     * 
Sebastian Castro's avatar
Sebastian Castro committed
180
     * @MongoDB\EmbedMany(targetDocument="Biopen\GeoDirectoryBundle\Document\ElementImage") 
181
     */
182 183 184 185 186 187 188 189 190
    private $images;   

    /**
     * @var string
     *
     * All the custom attributes belonging to the Element
     *
     * @MongoDB\Field(type="hash")
     */
Sebastian Castro's avatar
Sebastian Castro committed
191
    private $data = []; 
192

193 194 195 196 197 198 199 200 201
    /**
     * @var string
     *
     * All the custom attributes belonging to the Element that we want to keep private (not available in public api)
     *
     * @MongoDB\Field(type="hash")
     */
    private $privateData = []; 

Sebastian Castro's avatar
Sebastian Castro committed
202 203 204 205 206 207
    /**
     * @var string
     *
     * A key to clarify the source of the information, i.e. from wich organization/source the
     * element has been imported
     *
Sebastian Castro's avatar
Sebastian Castro committed
208
     * @MongoDB\Field(type="string") @MongoDB\Index
Sebastian Castro's avatar
Sebastian Castro committed
209
     */
210
    public $sourceKey = '';
211

212 213 214
    /**
     * The source from where the element has been imported or created
     *
215
     * @MongoDB\ReferenceOne(targetDocument="Biopen\GeoDirectoryBundle\Document\Import")
216 217 218
     */
    private $source;

219 220 221 222 223
    /**
     * @var string
     *
     * If element has been imported, this is the Id of the element in the previous database
     *
Sebastian Castro's avatar
Sebastian Castro committed
224
     * @MongoDB\Field(type="string") @MongoDB\Index
225 226
     */
    private $oldId;
Sebastian Castro's avatar
Sebastian Castro committed
227

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    /**
     * potential duplicates stored by detect duplicate bulk action
     *
     * @MongoDB\ReferenceMany(targetDocument="Biopen\GeoDirectoryBundle\Document\Element")
     */
    private $potentialDuplicates;

    /** 
    * To simlifu duplicates process, we store the element which have been treated in the duplicates detection
    * Because if we check duplicates for element A, and element B and C are detected as potential duplicates, then
    * we do not detect duplicates for B and C
    * @MongoDB\Field(type="bool", nullable=true) 
    */
    private $isDuplicateNode = false;

    /**
     * Mark some element as Non duplicates, so if we run again the duplicate detection they will not be detected
     *
     * @MongoDB\ReferenceMany(targetDocument="Biopen\GeoDirectoryBundle\Document\Element")
     */
    private $nonDuplicates;

250 251
    /** 
     * @var string 
252 253 254 255
     *
     * The Compact Json representation of the Element. We save it so we don't have to serialize the element
     * each time.
     * The compact json is a small array with the basic informations of the element : id, name, coordinates, optionsValues
256 257 258
     * 
     * @MongoDB\Field(type="string") 
     */ 
259 260 261 262 263
    private $compactJson; 

    /** 
     * @var string 
     * 
264 265 266
     * The complete Json representation of the Element. We save it so we don't have to serialize the element
     * each time
     *
267 268
     * @MongoDB\Field(type="string") 
     */ 
269
    private $baseJson; 
270

271 272 273
    /** 
     * @var string 
     * 
274 275 276 277 278 279 280 281 282 283
     * Somes special field returned only for trusted people. this privateJson is concatenated to the baseJson
     *
     * @MongoDB\Field(type="string") 
     */ 
    private $privateJson; 

    /** 
     * @var string 
     * 
     * Somes special field returned only for admins. this adminJson is concatenated to the baseJson
284 285 286 287 288
     *
     * @MongoDB\Field(type="string") 
     */ 
    private $adminJson; 

289
    /**
290
     * @var date $createdAt
291
     *
Sebastian Castro's avatar
Sebastian Castro committed
292
     * @MongoDB\Field(type="date") @MongoDB\Index
293 294
     * @Gedmo\Timestampable(on="create")
     */
295
    private $createdAt;
296 297

    /**
298
     * @var date $updatedAt
299
     *
Sebastian Castro's avatar
Sebastian Castro committed
300
     * @MongoDB\Field(type="date") @MongoDB\Index
301
     */
302
    private $updatedAt;
303

304 305 306 307 308 309 310 311 312 313
    /**
    * @MongoDB\Field(type="string") 
    */ 
    private $randomHash;

    /**
    * @MongoDB\Field(type="string") 
    */ 
    private $userOwnerEmail;

314
    /**
315 316
     * When actions are made by many person (like moderation, duplicates check...) we lock the elements currently proceed by someone
     * so noone else make action on the same element 
317 318
     * @MongoDB\Field(type="int")
     */
319
    private $lockUntil = 0;    
320

321 322 323 324 325
    /**
     * Constructor
     */
    public function __construct()
    {
326
        if (!$this->getRandomHash()) $this->updateRandomHash();
327 328
        $this->potentialDuplicates = new \Doctrine\Common\Collections\ArrayCollection();
        $this->nonDuplicates = new \Doctrine\Common\Collections\ArrayCollection();
329 330
    }

331 332 333 334 335
    public function getShowUrlFromController($controller)
    {
        return str_replace('%23', '#', $controller->generateUrl('biopen_directory_showElement', array('id'=>$this->getId())));
    }

336 337 338 339 340 341 342 343
    public function updateRandomHash()
    {
        $this->setRandomHash(uniqid());
    }

    public function updateTimestamp()
    {
        $this->setUpdatedAt(time());
344 345
    }

346 347
    public function resetOptionsValues()
    {
348
        $this->optionValues = [];
349
    }
Sebastian Castro's avatar
Sebastian Castro committed
350

351 352 353 354 355 356 357 358 359 360 361 362
    public function resetContributions()
    {
        $this->contributions = [];
    }

    public function resetReports()
    {
        $this->reports = [];
    }

    public function getUnresolvedReports()
    {
363 364 365
       if ($this->getReports() == null) return;
       $reports = $this->getArrayFromCollection($this->getReports());
       $result = array_filter($reports, function($e) { return !$e->getIsResolved(); });
366 367 368 369 370
       return $result;
    }

    public function getContributionsAndResolvedReports()
    {
371 372 373 374
        if ($this->getReports() == null || $this->getContributions() == null) return;
        $reports = $this->getArrayFromCollection($this->getReports());
        $contributions = $this->getArrayFromCollection($this->getContributions());
        $resolvedReports = array_filter($reports, function($e) { return $e->getIsResolved(); });
375
        $contributions = array_filter($contributions, function($e) { return $e->getStatus() ? $e->getStatus() > ElementStatus::ModifiedPendingVersion : false; });
376 377 378 379 380
        $result = array_merge($resolvedReports, $contributions);
        usort( $result, function ($a, $b) { return $b->getTimestamp() - $a->getTimestamp(); });
        return $result;
    }

381 382 383 384 385 386 387 388
    public function hasValidContributionMadeBy($userEmail)
    {
        $contribs = $this->getArrayFromCollection($this->getContributions());
        $userValidContributionsOnElement = array_filter($contribs, function($contribution) use ($userEmail) { 
            return $contribution->countAsValidContributionFrom($userEmail);
        });
        return count($userValidContributionsOnElement) > 0;
    }
389 390 391 392 393 394 395

    public function countOptionsValues()
    {
        if (!$this->getOptionValues()) return 0;
        if (is_array($this->getOptionValues())) return count($this->getOptionValues());
        return $this->getOptionValues()->count();
    }
396

397 398 399 400 401 402 403 404 405 406 407
    public function getSortedOptionsValues()
    {
        $sortedOptionsValues = [];
        if ($this->optionValues)
        {
            $sortedOptionsValues = is_array($this->optionValues) ? $this->optionValues : $this->optionValues->toArray();
            usort( $sortedOptionsValues , function ($a, $b) { return $a->getIndex() - $b->getIndex(); });
        } 
        return $sortedOptionsValues;
    }

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    public function getNonDuplicatesIds()
    {
        $result = [];
        if ($this->nonDuplicates) 
            $result = array_map(function($nonDuplicate) {
                return $nonDuplicate->getId();
            }, $this->nonDuplicates->toArray());
        if ($this->getId()) $result[] = $this->getId();
        return $result;
    }

    public function isPotentialDuplicate() { return $this->moderationState == ModerationState::PotentialDuplicate; }

    public function getSortedDuplicates($duplicates = null)
    {
        if (!$duplicates) $duplicates = $this->getPotentialDuplicates() ? $this->getPotentialDuplicates()->toArray() : null;
        if (!$duplicates) return [];
        $duplicates[] = $this;
        usort($duplicates, function ($a, $b) 
        { 
            $diffDays = (float) date_diff($a->getUpdatedAt(), $b->getUpdatedAt())->format('%d');
            if ($diffDays != 0) return $diffDays;
            $diffComitment = strlen($b->getCommitment()) - strlen($a->getCommitment());
            if ($diffComitment != 0) return $diffComitment;
            return $b->countOptionsValues() - $a->countOptionsValues();
        }); 
        return $duplicates;
    }  
436

437
    /** @MongoDB\PreFlush */
438 439 440 441 442 443
    public function onPreFlush()
    {
        $this->checkForModerationNeeded();
        $this->updateJsonRepresentation();
    }

444
    // automatically resolve moderation error
445 446 447 448 449 450 451 452 453 454 455 456
    public function checkForModerationNeeded()
    { 
        if ($this->getModerationState() == ModerationState::NotNeeded) return;

        $needed = true;

        switch ($this->getModerationState()) {
            case ModerationState::VotesConflicts:
            case ModerationState::PendingForTooLong:
                if (!$this->isPending()) $needed = false;
                break;
            case ModerationState::NoOptionProvided:
457
                if ($this->countOptionsValues() > 0)
458
                    $needed = false;
459 460
                break;
            case ModerationState::GeolocError:
461
                if ($this->getGeo()->getLatitude() != 0 && $this->getGeo()->getLongitude() != 0) 
462
                    $needed = false;
463 464 465 466 467 468 469
                break;
        }

        if (!$needed) $this->setModerationState(ModerationState::NotNeeded);
    }


470
    public function updateJsonRepresentation()
471
    {
472
        if (!$this->geo) { return; }
473

474
        // -------------------- FULL JSON ----------------
475 476
        
        // BASIC FIELDS
477
        $baseJson = json_encode($this);
478
        $baseJson = substr($baseJson , 0, -1); // remove last '}'
479
        if ($this->address)   $baseJson .= ', "address":'    . $this->address->toJson();         
480 481
        if ($this->openHours) $baseJson .= ', "openHours": ' . $this->openHours->toJson(); 
        
482
        // CREATED AT, UPDATED AT
483
        $baseJson .= ', "createdAt":"'    . date_format($this->createdAt,"d/m/Y") . '"';
484 485 486
        $updatedAt = $this->updatedAt ? $this->updatedAt : $this->createdAt;
        $updatedAtFormated = gettype($updatedAt) == "integer" ? date("d/m/Y", $updatedAt) : date_format($updatedAt,"d/m/Y");
        $baseJson .= ', "updatedAt":"'    . $updatedAtFormated . '"';
487

488
        // OPTIONS VALUES (= TAXONOMY)
489
        $sortedOptionsValues = $this->getSortedOptionsValues();
490
        $optValuesLength = count($sortedOptionsValues);
491
        // Options values ids
492
        $baseJson .= ', "categories": [';
493 494 495
        if ($sortedOptionsValues)
        {            
            for ($i=0; $i < $optValuesLength; $i++) { 
Sebastian Castro's avatar
Sebastian Castro committed
496
                $baseJson .= $sortedOptionsValues[$i]->getOptionId() . ',';
497
            }
498
        }
499
        $baseJson = rtrim($baseJson, ',');
500
        $baseJson .= '],';
501
        // Options values with descriptionO      
502 503 504 505 506 507 508
        $optionDescriptionsJson = [];
        if ($sortedOptionsValues)
        {            
            for ($i=0; $i < $optValuesLength; $i++) {
                if ($sortedOptionsValues[$i]->getDescription()) $optionDescriptionsJson[] =  $sortedOptionsValues[$i]->toJson();
            }
        }
509
        if (count($optionDescriptionsJson)) $baseJson .= '"categoriesDescriptions": [' . implode(",", $optionDescriptionsJson) . '],';
510

511 512 513 514 515 516 517 518 519 520 521
        // CUSTOM DATA
        foreach ($this->getData() as $key => $value) {
            $baseJson .= '"'. $key .'": ' . json_encode($value) . ',';
        }
        
        // SPECIFIC DATA
        $baseJson .= $this->encodeArrayObjectToJson("stamps", $this->stamps);
        $baseJson .= $this->encodeArrayObjectToJson("images", $this->images);
        $baseJson = rtrim($baseJson, ',');         

        // MODIFIED ELEMENT (for pending modification)
522 523 524 525 526
        if ($this->getModifiedElement()) {
            $baseJson .= ', "modifiedElement": ' . $this->getModifiedElement()->getJson(true, false);
        }
        $baseJson .= '}';

527 528
        $this->setBaseJson($baseJson);

529

530
        // -------------------- PRIVATE JSON -------------------------
531 532 533 534
        $privateJson = '{';        
        // status
        $privateJson .= '"status": ' . $this->getStatus() . ',';
        $privateJson .= '"moderationState": ' . $this->getModerationState() . ',';
535 536 537 538
        // CUSTOM PRIVATE DATA
        foreach ($this->getPrivateData() as $key => $value) {
            $privateJson .= '"'. $key .'": ' . json_encode($value) . ',';
        }
539 540 541
        $privateJson = rtrim($privateJson, ',');
        $privateJson .= '}';
        $this->setPrivateJson($privateJson);
542 543


544
        // ---------------- ADMIN JSON = REPORTS & CONTRIBUTIONS ---------------------
545
        $adminJson = '{';
546 547
        if ($this->status != ElementStatus::ModifiedPendingVersion)
        {
548 549
            $adminJson .= $this->encodeArrayObjectToJson('reports', $this->getUnresolvedReports());
            $adminJson .= $this->encodeArrayObjectToJson('contributions', $this->getContributionsAndResolvedReports());
550 551
            if ($this->isPending()) {
                $adminJson .= $this->encodeArrayObjectToJson('votes', $this->getVotesArray());
552
                if ($this->getCurrContribution()) $adminJson .= '"pendingContribution":' . $this->getCurrContribution()->toJson();
553
            }
554
            $adminJson = rtrim($adminJson, ',');
555
        }
556
        $adminJson .= '}';
557 558
        $this->setAdminJson($adminJson);    

559

560
        // -------------------- COMPACT JSON ----------------
561
        $compactJson = '["'.$this->id . '",' . json_encode($this->name) . ',';
562 563
        $compactJson.= $this->geo->getLatitude() .','. $this->geo->getLongitude() .', [';
        if ($sortedOptionsValues)
564
        {
565 566 567
            for ($i=0; $i < $optValuesLength; $i++) { 
                $value = $sortedOptionsValues[$i];
                $compactJson .= $value->getOptionId();
Sebastian Castro's avatar
Sebastian Castro committed
568
                $compactJson .= ',';
569
            }
Sebastian Castro's avatar
Sebastian Castro committed
570
            $compactJson = rtrim($compactJson, ',');
571
        }
572 573 574 575
        $compactJson .= ']';
        if ($this->status <= 0 || $this->moderationState != 0) $compactJson .= ','. $this->status;
        if ($this->moderationState != 0) $compactJson .= ','. $this->moderationState;
        $compactJson .= ']';
576
        $this->setCompactJson($compactJson);
577 578
    }

579
    public function getJson($includePrivateJson, $includeAdminJson)
580
    {
581
        $result = $this->baseJson;
582
        if ($includePrivateJson && $this->privateJson && $this->privateJson != '{}')
583
           $result = substr($result , 0, -1) . ',' . substr($this->privateJson,1);
584
        if ($includeAdminJson && $this->adminJson && $this->adminJson != '{}')
585 586
           $result = substr($result , 0, -1) . ',' . substr($this->adminJson,1);
        return $result;
587 588
    }

589 590
    private function encodeArrayObjectToJson($propertyName, $array)
    {
591 592 593
        if (!$array) return "";
        $array = is_array($array) ? $array : $array->toArray();
        if (count($array) == 0) return '';
594
        $result = '"'. $propertyName .'": [';
595 596
        foreach ($array as $key => $value) {
            $result .= $value->toJson();
Sebastian Castro's avatar
Sebastian Castro committed
597
            $result .= ',';
598
        }
Sebastian Castro's avatar
Sebastian Castro committed
599
        $result = rtrim($result, ',');
600
        $result .= '],';
601
        return $result;
602 603
    }

604 605
    public function isPending()
    {
Sebastian Castro's avatar
Sebastian Castro committed
606 607 608 609 610 611 612 613 614 615 616
        return $this->isPendingAdd() || $this->isPendingModification();
    }

    public function isPendingAdd()
    {
        return $this->status == ElementStatus::PendingAdd;
    }

    public function isPendingModification()
    {
        return $this->status == ElementStatus::PendingModification;
617
    }
618

619 620 621 622 623
    public function isVisible()
    {
        return $this->status >= -1;
    }

624 625 626 627 628
    public function isValid()
    {
        return $this->status > 0;
    }

629 630 631 632 633
    public function havePendingReports()
    {
        return $this->moderationState == ModerationState::ReportsSubmitted;
    }

634 635
    public function getCurrContribution()
    {
636
        $contributions = $this->getContributions();
637
        if (is_array($contributions))   
638
        {
Sebastian Castro's avatar
Sebastian Castro committed
639 640 641 642 643
            if (count($contributions) > 0) {
                $currContrib = array_slice($contributions, -1);
                return array_pop($currContrib);
            }
            return null;
644 645
        } 
        else 
646
            return $contributions ? $contributions->last() : null;
647 648 649 650 651 652 653
    }

    public function getVotes()
    {
        return $this->getCurrContribution() ? $this->getCurrContribution()->getVotes() : [];
    }

654 655
    public function getVotesArray()
    {
Sebastian Castro's avatar
Sebastian Castro committed
656 657 658
        if  (!$this->getCurrContribution() ||  is_array($this->getCurrContribution()->getVotes()))
            return [];
        return $this->getCurrContribution()->getVotes()->toArray();
659 660
    }

661
    public function isLastContributorEqualsTo($user, $userEmail)
662
    {
663
        return $this->getCurrContribution() ? $this->getCurrContribution()->isMadeBy($user, $userEmail) : false;
664 665
    }

Sebastian Castro's avatar
Sebastian Castro committed
666 667
    public function getFormatedAddress()
    {
668
        return $this->address ? $this->address->getFormatedAddress() : '';
Sebastian Castro's avatar
Sebastian Castro committed
669 670
    }

671 672 673
    public function getOptionIds()
    {
        $result = [];
Sebastian Castro's avatar
Sebastian Castro committed
674 675 676 677
        if ($this->getOptionValues())
            foreach ($this->getOptionValues() as $optionsValue) {
                $result[] = (string) $optionsValue->getOptionId();
            }
678 679 680
        return $result;
    }

681 682 683 684 685 686
    public function reset()
    {             
        $this->name = null;
        $this->address = null;
        $this->resetOptionsValues();
        $this->openHours = null;
687
        $this->data = null;
688
        $this->privateData = null;
689 690
    }

691 692
    public function setCustomData($data, $privateProps)
    {
Sebastian Castro's avatar
Sebastian Castro committed
693 694 695
        if (array_key_exists('email', $data)) {
            $this->setEmail($data['email']);
        }
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
        $privateData = [];
        foreach ($privateProps as $key => $prop) {
            if (array_key_exists($prop, $data)) {
                $privateData[$prop] = $data[$prop];
                unset($data[$prop]);
            }
        }

        if ($this->getData()) $data = array_merge($this->getData(), $data); // keeping also old data
        $this->setData($data);
        
        if ($this->getPrivateData()) $privateData = array_merge($this->getPrivateData(), $privateData); // keeping also old data
        $this->setPrivateData($privateData);
    }

711 712 713 714 715 716 717
    /**
     * Set status
     *
     * @param int $status
     * @return $this
     */
    public function setStatus($newStatus)
718
    {         
719 720 721 722
        $this->status = $newStatus;
        return $this;
    }

723 724
    public function __toString() 
    {
Sebastian Castro's avatar
Sebastian Castro committed
725
        return $this->getName() ? $this->getName() : "";
726 727
    }

728 729 730
    /**
     * Get id
     *
Sebastian Castro's avatar
Sebastian Castro committed
731
     * @return custom_id $id
732 733 734 735 736 737
     */
    public function getId()
    {
        return $this->id;
    }

738 739 740 741 742 743 744 745 746 747 748
    /**
     * Get id
     *
     * @return custom_id $id
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

749 750 751
    /**
     * Set name
     *
Sebastian Castro's avatar
Sebastian Castro committed
752
     * @param string $name
Sebastian Castro's avatar
Sebastian Castro committed
753
     * @return $this
754
     */
Sebastian Castro's avatar
Sebastian Castro committed
755
    public function setName($name)
756
    {
Sebastian Castro's avatar
Sebastian Castro committed
757
        $this->name = $name;
758 759 760 761
        return $this;
    }

    /**
Sebastian Castro's avatar
Sebastian Castro committed
762
     * Get name
763
     *
Sebastian Castro's avatar
Sebastian Castro committed
764
     * @return string $name
765
     */
Sebastian Castro's avatar
Sebastian Castro committed
766
    public function getName()
767
    {
Sebastian Castro's avatar
Sebastian Castro committed
768
        return $this->name;
769 770 771
    }

    /**
Sebastian Castro's avatar
Sebastian Castro committed
772
     * Set openHours
773
     *
774
     * @param object_id $openHours
Sebastian Castro's avatar
Sebastian Castro committed
775
     * @return $this
776
     */
777
    public function setOpenHours($openHours)
778
    {
Sebastian Castro's avatar
Sebastian Castro committed
779
        $this->openHours = $openHours;
780 781 782 783
        return $this;
    }

    /**
Sebastian Castro's avatar
Sebastian Castro committed
784
     * Get openHours
785
     *
786
     * @return object_id $openHours
787
     */
Sebastian Castro's avatar
Sebastian Castro committed
788
    public function getOpenHours()
789
    {
Sebastian Castro's avatar
Sebastian Castro committed
790
        return $this->openHours;
791 792
    }

793 794 795 796 797 798 799 800 801 802
    /**
     * Add optionValue
     *
     * @param Biopen\GeoDirectoryBundle\Document\OptionValue $optionValue
     */
    public function addOptionValue(\Biopen\GeoDirectoryBundle\Document\OptionValue $optionValue)
    {
        $this->optionValues[] = $optionValue;
    }

803
    /**
804
     * Remove optionValue
805
     *
806
     * @param Biopen\GeoDirectoryBundle\Document\OptionValue $optionValue
807
     */
808
    public function removeOptionValue(\Biopen\GeoDirectoryBundle\Document\OptionValue $optionValue)
809
    {
810
        $this->optionValues->removeElement($optionValue);
811 812 813
    }

    /**
814
     * Get optionValues
815
     *
816
     * @return \Doctrine\Common\Collections\Collection $optionValues
817
     */
818
    public function getOptionValues()
819
    {
820
        return $this->optionValues;
821
    }
822

823 824 825 826 827 828
    public function setOptionValues($optionValues)
    {
        $this->optionValues = $optionValues;
        return $this;
    }

829 830 831 832 833 834 835 836 837 838
    /**
     * Get status
     *
     * @return int $status
     */
    public function getStatus()
    {
        return $this->status;
    }

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    /**
     * Set compactJson
     *
     * @param string $compactJson
     * @return $this
     */
    public function setCompactJson($compactJson)
    {
        $this->compactJson = $compactJson;
        return $this;
    }

    /**
     * Get compactJson
     *
     * @return string $compactJson
     */
    public function getCompactJson()
    {
        return $this->compactJson;
    }

    /**
862
     * Set baseJson
863
     *
864
     * @param string $baseJson
865 866
     * @return $this
     */
867
    public function setBaseJson($baseJson)
868
    {
869
        $this->baseJson = $baseJson;
870 871 872 873
        return $this;
    }

    /**
874
     * Get baseJson
875
     *
876
     * @return string $baseJson
877
     */
878
    public function getBaseJson()
879
    {
880
        return $this->baseJson;
881
    }
882 883 884 885 886 887

    /**
     * Add report
     *
     * @param Biopen\GeoDirectoryBundle\Document\Report $report
     */
Sebastian Castro's avatar
Sebastian Castro committed
888
    public function addReport(\Biopen\GeoDirectoryBundle\Document\UserInteractionReport $report)
889
    {
890
        $report->setElement($this);
891
        $this->reports[] = $report;
892
        $this->setModerationState(ModerationState::ReportsSubmitted);
893 894 895 896 897 898 899
    }

    /**
     * Remove report
     *
     * @param Biopen\GeoDirectoryBundle\Document\Report $report
     */
Sebastian Castro's avatar
Sebastian Castro committed
900
    public function removeReport(\Biopen\GeoDirectoryBundle\Document\UserInteractionReport $report)
901 902 903 904 905 906 907 908 909 910 911 912 913
    {
        $this->reports->removeElement($report);
    }

    /**
     * Get reports
     *
     * @return \Doctrine\Common\Collections\Collection $reports
     */
    public function getReports()
    {
        return $this->reports;
    }
914

915 916 917 918 919 920 921
    private function getArrayFromCollection($collection)
    {
        if ($collection == null) return [];
        else if (is_array($collection)) return [];
        else return $collection->toArray();
    }

922 923 924 925 926 927
    /**
     * Set created
     *
     * @param date $created
     * @return $this
     */
928
    public function setCreatedAt($created)
929
    {
930
        $this->createdAt = $createdAt;
931 932 933 934 935 936 937 938
        return $this;
    }

    /**
     * Get created
     *
     * @return date $created
     */
939
    public function getCreatedAt()
940
    {
941
        return $this->createdAt;
942 943 944 945 946 947 948 949
    }

    /**
     * Set updated
     *
     * @param date $updated
     * @return $this
     */
950
    public function setUpdatedAt($updatedAt)
951
    {
952
        $this->updatedAt = $updatedAt;
953 954 955 956 957 958 959 960
        return $this;
    }

    /**
     * Get updated
     *
     * @return date $updated
     */
961
    public function getUpdatedAt()
962
    {
963
        return $this->updatedAt;
964
    }
965 966 967 968 969 970 971

    /**
     * Set statusMessage
     *
     * @param string $statusMessage
     * @return $this
     */
972
    public function setModerationState($moderationState)
973
    {
974
        $this->moderationState = $moderationState;
975 976 977 978 979 980 981 982
        return $this;
    }

    /**
     * Get statusMessage
     *
     * @return string $statusMessage
     */
983
    public function getModerationState()
984
    {
985
        return $this->moderationState;
986
    }
987 988 989 990 991 992 993

    /**
     * Set modifiedElement
     *
     * @param Biopen\GeoDirectoryBundle\Document\Element $modifiedElement
     * @return $this
     */
994
    public function setModifiedElement($modifiedElement)
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    {
        $this->modifiedElement = $modifiedElement;
        return $this;
    }

    /**
     * Get modifiedElement
     *
     * @return Biopen\GeoDirectoryBundle\Document\Element $modifiedElement
     */
    public function getModifiedElement()
    {
        return $this->modifiedElement;
    }
1009
    
Sebastian Castro's avatar
Sebastian Castro committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    /**
     * Set sourceKey
     *
     * @param string $sourceKey
     * @return $this
     */
    public function setSourceKey($sourceKey)
    {
        $this->sourceKey = $sourceKey;
        return $this;
    }

    /**
     * Get sourceKey
     *
     * @return string $sourceKey
     */
    public function getSourceKey()
    {
        return $this->sourceKey;
    }
Sebastian Castro's avatar
Sebastian Castro committed
1031 1032 1033 1034 1035 1036 1037 1038

    /**
     * Add contribution
     *
     * @param Biopen\GeoDirectoryBundle\Document\UserInteractionContribution $contribution
     */
    public function addContribution(\Biopen\GeoDirectoryBundle\Document\UserInteractionContribution $contribution)
    {
1039
        $contribution->setElement($this);        
Sebastian Castro's avatar
Sebastian Castro committed
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
        $this->contributions[] = $contribution;
    }

    /**
     * Remove contribution
     *
     * @param Biopen\GeoDirectoryBundle\Document\UserInteractionContribution $contribution
     */
    public function removeContribution(\Biopen\GeoDirectoryBundle\Document\UserInteractionContribution $contribution)
    {
        $this->contributions->removeElement($contribution);
    }

    /**
     * Get contributions
     *
     * @return \Doctrine\Common\Collections\Collection $contributions
     */
    public function getContributions()
    {
        return $this->contributions;
    }
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083

    /**
     * Set oldId
     *
     * @param string $oldId
     * @return $this
     */
    public function setOldId($oldId)
    {
        $this->oldId = $oldId;
        return $this;
    }

    /**
     * Get oldId
     *
     * @return string $oldId
     */
    public function getOldId()
    {
        return $this->oldId;
    }
Sebastian Castro's avatar
Sebastian Castro committed
1084 1085

    /**
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
     * Set geo
     *
     * @param Biopen\GeoDirectoryBundle\Document\Coordinates $geo
     * @return $this
     */
    public function setGeo(\Biopen\GeoDirectoryBundle\Document\Coordinates $geo)
    {
        $this->geo = $geo;
        return $this;
    }

    /**
     * Get geo
     *
     * @return Biopen\GeoDirectoryBundle\Document\Coordinates $geo
     */
    public function getGeo()
    {
        return $this->geo;
    }

    /**
     * Set address
     *
     * @param Biopen\GeoDirectoryBundle\Document\PostalAddress $address
     * @return $this
     */
    public function setAddress(\Biopen\GeoDirectoryBundle\Document\PostalAddress $address)
    {
        $this->address = $address;
        return $this;
    }

    /**
     * Get address
     *
     * @return Biopen\GeoDirectoryBundle\Document\PostalAddress $address
     */
    public function getAddress()
    {
        return $this->address;
    }

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    /**
     * Set adminJson
     *
     * @param string $adminJson
     * @return $this
     */
    public function setAdminJson($adminJson)
    {
        $this->adminJson = $adminJson;
        return $this;
    }

    /**
     * Get adminJson
     *
     * @return string $adminJson
     */
    public function getAdminJson()
    {
        return $this->adminJson;
    }
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

    /**
     * Set optionsString
     *
     * @param string $optionsString
     * @return $this
     */
    public function setOptionsString($optionsString)
    {
        $this->optionsString = $optionsString;
        return $this;
    }

    /**
     * Get optionsString
     *
     * @return string $optionsString
     */
    public function getOptionsString()
    {
        return $this->optionsString;
    }
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201