ManiphestTransactionEditor.php 35.5 KB
Newer Older
epriestley's avatar
epriestley committed
1 2
<?php

3 4
final class ManiphestTransactionEditor
  extends PhabricatorApplicationTransactionEditor {
epriestley's avatar
epriestley committed
5

6
  private $oldProjectPHIDs;
7 8
  private $moreValidationErrors = array();

epriestley's avatar
epriestley committed
9 10 11 12 13 14 15 16
  public function getEditorApplicationClass() {
    return 'PhabricatorManiphestApplication';
  }

  public function getEditorObjectsDescription() {
    return pht('Maniphest Tasks');
  }

17 18
  public function getTransactionTypes() {
    $types = parent::getTransactionTypes();
19

20
    $types[] = PhabricatorTransactions::TYPE_COMMENT;
21
    $types[] = PhabricatorTransactions::TYPE_EDGE;
22
    $types[] = PhabricatorTransactions::TYPE_COLUMNS;
23 24 25 26 27 28
    $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
    $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;

    return $types;
  }

29 30 31 32 33 34 35 36
  public function getCreateObjectTitle($author, $object) {
    return pht('%s created this task.', $author);
  }

  public function getCreateObjectTitleForFeed($author, $object) {
    return pht('%s created %s.', $author, $object);
  }

37 38 39 40 41
  protected function getCustomTransactionOldValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
42
      case PhabricatorTransactions::TYPE_COLUMNS:
43
        return null;
44 45 46 47 48 49 50 51
    }
  }

  protected function getCustomTransactionNewValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
52
      case PhabricatorTransactions::TYPE_COLUMNS:
53
        return $xaction->getNewValue();
54 55 56 57 58 59 60 61 62 63 64
    }
  }

  protected function transactionHasEffect(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    $old = $xaction->getOldValue();
    $new = $xaction->getNewValue();

    switch ($xaction->getTransactionType()) {
65 66
      case PhabricatorTransactions::TYPE_COLUMNS:
        return (bool)$new;
67 68 69 70 71 72 73 74 75 76
    }

    return parent::transactionHasEffect($object, $xaction);
  }

  protected function applyCustomInternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
77
      case PhabricatorTransactions::TYPE_COLUMNS:
78
        return;
79 80 81 82 83 84
    }
  }

  protected function applyCustomExternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {
85 86

    switch ($xaction->getTransactionType()) {
87 88 89
      case PhabricatorTransactions::TYPE_COLUMNS:
        foreach ($xaction->getNewValue() as $move) {
          $this->applyBoardMove($object, $move);
90 91 92
        }
        break;
    }
93 94
  }

95 96 97 98 99 100 101 102 103
  protected function applyFinalEffects(
    PhabricatorLiskDAO $object,
    array $xactions) {

    // When we change the status of a task, update tasks this tasks blocks
    // with a message to the effect of "alincoln resolved blocking task Txxx."
    $unblock_xaction = null;
    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
104
        case ManiphestTaskStatusTransaction::TRANSACTIONTYPE:
105 106 107 108 109 110 111 112
          $unblock_xaction = $xaction;
          break;
      }
    }

    if ($unblock_xaction !== null) {
      $blocked_phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
        $object->getPHID(),
113
        ManiphestTaskDependedOnByTaskEdgeType::EDGECONST);
114 115 116 117 118 119
      if ($blocked_phids) {
        // In theory we could apply these through policies, but that seems a
        // little bit surprising. For now, use the actor's vision.
        $blocked_tasks = id(new ManiphestTaskQuery())
          ->setViewer($this->getActor())
          ->withPHIDs($blocked_phids)
120
          ->needSubscriberPHIDs(true)
121
          ->needProjectPHIDs(true)
122 123 124 125
          ->execute();

        $old = $unblock_xaction->getOldValue();
        $new = $unblock_xaction->getNewValue();
126
        $date = $unblock_xaction->getDateCreated();
127 128

        foreach ($blocked_tasks as $blocked_task) {
129
          $parent_xaction = id(new ManiphestTransaction())
130 131
            ->setTransactionType(
              ManiphestTaskUnblockTransaction::TRANSACTIONTYPE)
132
            ->setOldValue(array($object->getPHID() => $old))
133 134
            ->setNewValue(array($object->getPHID() => $new))
            ->setDateCreated($date);
135

136 137 138 139
          if ($this->getIsNewObject()) {
            $parent_xaction->setMetadataValue('blocker.new', true);
          }

140
          $this->newSubEditor()
141 142
            ->setContinueOnNoEffect(true)
            ->setContinueOnMissingFields(true)
143
            ->setIsSilent($this->getIsSilent())
144
            ->applyTransactions($blocked_task, array($parent_xaction));
145 146 147 148 149 150 151
        }
      }
    }

    return $xactions;
  }

epriestley's avatar
epriestley committed
152 153 154 155 156 157
  protected function shouldSendMail(
    PhabricatorLiskDAO $object,
    array $xactions) {
    return true;
  }

158
  protected function getMailSubjectPrefix() {
159
    return pht('[Maniphest]');
160 161 162 163 164 165 166
  }

  protected function getMailThreadID(PhabricatorLiskDAO $object) {
    return 'maniphest-task-'.$object->getPHID();
  }

  protected function getMailTo(PhabricatorLiskDAO $object) {
167 168 169 170 171 172 173 174
    $phids = array();

    if ($object->getOwnerPHID()) {
      $phids[] = $object->getOwnerPHID();
    }
    $phids[] = $this->getActingAsPHID();

    return $phids;
175 176
  }

epriestley's avatar
epriestley committed
177 178
  public function getMailTagsMap() {
    return array(
179
      ManiphestTransaction::MAILTAG_STATUS =>
epriestley's avatar
epriestley committed
180
        pht("A task's status changes."),
181
      ManiphestTransaction::MAILTAG_OWNER =>
epriestley's avatar
epriestley committed
182
        pht("A task's owner changes."),
183
      ManiphestTransaction::MAILTAG_PRIORITY =>
epriestley's avatar
epriestley committed
184
        pht("A task's priority changes."),
185 186 187
      ManiphestTransaction::MAILTAG_CC =>
        pht("A task's subscribers change."),
      ManiphestTransaction::MAILTAG_PROJECTS =>
epriestley's avatar
epriestley committed
188
        pht("A task's associated projects change."),
189
      ManiphestTransaction::MAILTAG_UNBLOCK =>
190
        pht("One of a task's subtasks changes status."),
191 192 193
      ManiphestTransaction::MAILTAG_COLUMN =>
        pht('A task is moved between columns on a workboard.'),
      ManiphestTransaction::MAILTAG_COMMENT =>
epriestley's avatar
epriestley committed
194
        pht('Someone comments on a task.'),
195
      ManiphestTransaction::MAILTAG_OTHER =>
epriestley's avatar
epriestley committed
196 197 198 199
        pht('Other task activity not listed above occurs.'),
    );
  }

200 201 202 203 204 205 206 207 208 209
  protected function buildReplyHandler(PhabricatorLiskDAO $object) {
    return id(new ManiphestReplyHandler())
      ->setMailReceiver($object);
  }

  protected function buildMailTemplate(PhabricatorLiskDAO $object) {
    $id = $object->getID();
    $title = $object->getTitle();

    return id(new PhabricatorMetaMTAMail())
210
      ->setSubject("T{$id}: {$title}");
211 212
  }

213 214
  protected function getObjectLinkButtonLabelForMail(
    PhabricatorLiskDAO $object) {
215 216 217
    return pht('View Task');
  }

218 219 220 221 222 223 224
  protected function buildMailBody(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $body = parent::buildMailBody($object, $xactions);

    if ($this->getIsNewObject()) {
Joshua Spence's avatar
Joshua Spence committed
225
      $body->addRemarkupSection(
226 227 228 229
        pht('TASK DESCRIPTION'),
        $object->getDescription());
    }

230
    $body->addLinkSection(
231
      pht('TASK DETAIL'),
232
      $this->getObjectLinkButtonURIForMail($object));
233

234 235

    $board_phids = array();
236
    $type_columns = PhabricatorTransactions::TYPE_COLUMNS;
237
    foreach ($xactions as $xaction) {
238 239 240 241
      if ($xaction->getTransactionType() == $type_columns) {
        $moves = $xaction->getNewValue();
        foreach ($moves as $move) {
          $board_phids[] = $move['boardPHID'];
242 243 244 245 246 247 248 249 250 251 252 253 254
        }
      }
    }

    if ($board_phids) {
      $projects = id(new PhabricatorProjectQuery())
        ->setViewer($this->requireActor())
        ->withPHIDs($board_phids)
        ->execute();

      foreach ($projects as $project) {
        $body->addLinkSection(
          pht('WORKBOARD'),
255
          PhabricatorEnv::getProductionURI($project->getWorkboardURI()));
256 257 258 259
      }
    }


260 261 262
    return $body;
  }

263 264 265
  protected function shouldPublishFeedStory(
    PhabricatorLiskDAO $object,
    array $xactions) {
266
    return true;
267 268 269 270 271 272
  }

  protected function supportsSearch() {
    return true;
  }

273 274 275
  protected function shouldApplyHeraldRules(
    PhabricatorLiskDAO $object,
    array $xactions) {
276 277 278 279 280 281 282 283 284 285 286
    return true;
  }

  protected function buildHeraldAdapter(
    PhabricatorLiskDAO $object,
    array $xactions) {

    return id(new HeraldManiphestTaskAdapter())
      ->setTask($object);
  }

287 288 289 290 291 292 293
  protected function adjustObjectForPolicyChecks(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $copy = parent::adjustObjectForPolicyChecks($object, $xactions);
    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
294
        case ManiphestTaskOwnerTransaction::TRANSACTIONTYPE:
295 296 297
          $copy->setOwnerPHID($xaction->getNewValue());
          break;
        default:
298
          break;
299 300 301 302 303
      }
    }

    return $copy;
  }
304

305 306 307 308 309 310 311 312 313 314
  protected function validateAllTransactions(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $errors = parent::validateAllTransactions($object, $xactions);

    if ($this->moreValidationErrors) {
      $errors = array_merge($errors, $this->moreValidationErrors);
    }

315 316 317 318
    foreach ($this->getLockValidationErrors($object, $xactions) as $error) {
      $errors[] = $error;
    }

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    if (!$this->getIsNewObject()) {
      $projects = PhabricatorEdgeQuery::loadDestinationPHIDs(
        $object->getPHID(),
        PhabricatorProjectObjectHasProjectEdgeType::EDGECONST);
      $projects = array_fuse($projects);
    } else {
      $projects = array();
    }

    foreach ($xactions as $xaction) {
      $xaction_type = $xaction->getTransactionType();
      $edge_type = $xaction->getMetadataValue('edge:type');
      if ($xaction_type != PhabricatorTransactions::TYPE_EDGE ||
          $edge_type != PhabricatorProjectObjectHasProjectEdgeType::EDGECONST) {
        continue;
      }

      $new = $xaction->getNewValue();
      $new_add = idx($new, '+', array());
      $new_rem = idx($new, '-', array());
      $new_set = idx($new, '=', null);

      foreach ($new_add as $phid => $edge) {
        $projects[$phid] = $phid;
      }
      foreach ($new_rem as $phid => $edge) {
        unset($projects[$phid]);
      }
      if ($new_set) {
        $projects = $new_set;
      }
    }

    if (empty($projects)) {
      $errors[] = new PhabricatorApplicationTransactionValidationError(
        PhabricatorTransactions::TYPE_EDGE,
        pht('Required'),
        pht('You must specify at least one project tag for a task.'),
        null
      );
    }

361 362 363
    return $errors;
  }

364 365 366
  protected function expandTransactions(
    PhabricatorLiskDAO $object,
    array $xactions) {
367

368
    $this->setContinueOnNoEffect(true);
369
    $snipe_api = new SnipeItHelper();
370

371 372 373
    $actor = $this->getActor();
    $actor_phid = $actor->getPHID();

374 375 376 377 378 379
    $results = parent::expandTransactions($object, $xactions);

    $is_unassigned = ($object->getOwnerPHID() === null);

    $any_assign = false;
    foreach ($xactions as $xaction) {
380
      if ($xaction->getTransactionType() ==
381 382
        ManiphestTaskOwnerTransaction::TRANSACTIONTYPE &&
	  !empty($xaction->getNewValue())) {
383 384 385 386 387 388 389
        $any_assign = true;
        break;
      }
    }

    $is_open = !$object->isClosed();

390
    $asset_id = null;
391 392 393
    $new_status = null;
    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
394
        case ManiphestTaskStatusTransaction::TRANSACTIONTYPE:
395
          $new_status = $xaction->getNewValue();
396 397 398 399

          // CCU: create Item in the inventory system if it's a Purchase request and
          // its status was changed to "to release"
          if (!$this->getIsNewObject()) {
400 401 402 403 404
            try {
              $asset_id = $snipe_api->createAssetItem($new_status, $object, $xactions);
            } catch (Exception $e) {
              $asset_id = null;
            }
405
          }
406 407 408 409 410 411 412 413 414 415 416 417 418
          break;
      }
    }

    if ($new_status === null) {
      $is_closing = false;
    } else {
      $is_closing = ManiphestTaskStatus::isClosedStatus($new_status);
    }

    // If the task is not assigned, not being assigned, currently open, and
    // being closed, try to assign the actor as the owner.
    if ($is_unassigned && !$any_assign && $is_open && $is_closing) {
419 420
      $is_claim = ManiphestTaskStatus::isClaimStatus($new_status);

421
      // Don't assign the actor if they aren't a real user.
422 423
      // Don't claim the task if the status is configured to not claim.
      if ($actor_phid && $is_claim) {
424
        $results[] = id(new ManiphestTransaction())
425
          ->setTransactionType(ManiphestTaskOwnerTransaction::TRANSACTIONTYPE)
426 427 428 429
          ->setNewValue($actor_phid);
      }
    }

430 431 432 433 434 435 436 437 438 439 440 441
    // Automatically subscribe the author when they create a task.
    if ($this->getIsNewObject()) {
      if ($actor_phid) {
        $results[] = id(new ManiphestTransaction())
          ->setTransactionType(PhabricatorTransactions::TYPE_SUBSCRIBERS)
          ->setNewValue(
            array(
              '+' => array($actor_phid => $actor_phid),
            ));
      }
    }

442 443 444 445 446
    $send_notifications = PhabricatorNotificationClient::isEnabled();
    if ($send_notifications) {
      $this->oldProjectPHIDs = $this->loadProjectPHIDs($object);
    }

447 448 449
    // CCU: If this is a purchasing type, then try to assign the task to the
    //      assignee, if empty. It's not overlay pleasant code, since we need
    //      to iterate the transactions, rather than interrogate an object.
450 451 452 453 454 455 456 457 458
    $subtype = null;
    $approver = null;
    $purchasing_project = null;
    $confidential = false;
    $changed_confidentiality = false;

    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
        case PhabricatorTransactions::TYPE_SUBTYPE:
459 460
          $subtype = $xaction->getNewValue();
          break;
461 462

        case PhabricatorTransactions::TYPE_CUSTOMFIELD:
463 464 465 466 467 468 469 470
          switch ($xaction->getMetadataValue('customfield:key')) {
            case 'std:maniphest:purchasing:approver':
              foreach ($xaction->getRequiredHandlePHIDs() as $p) {
                if (!empty($p)) {
                  $approver = $p;
                  break;
                }
              }
471
              break;
472

473 474 475 476 477 478 479
            case 'std:maniphest:purchasing:project':
              foreach ($xaction->getRequiredHandlePHIDs() as $p) {
                if (!empty($p)) {
                  $purchasing_project = $p;
                  break;
                }
              }
480
              break;
481

482 483 484 485 486 487 488 489
            case 'std:maniphest:sysadmin:confidential-request':
              if ($xaction->getNewValue() != $xaction->getOldValue()) {
                $changed_confidentiality = true;
              }
              if ($xaction->getNewValue() == 'Yes' || $xaction->getNewValue() == 'Dunno') {
                $confidential = true;
              }
              break;
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
          }

        break;
      }
    }

    if (!$this->getIsNewObject()) {
      $subtype = $object->getSubtype();
    };
    // We want to change policies only if the confidentiality dropdown was
    // changed or if it's a new request.
    if ($subtype == 'sysadmin' &&
       ($changed_confidentiality || $this->getIsNewObject())) {
      if ($confidential) {
        $sysadmin_project = id(new PhabricatorProjectQuery())
          ->setViewer($actor)
506
          ->withSlugs(array('support_request'))
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
          ->executeOne();

        $confidential_policy = id(new PhabricatorPolicy())
          ->setRules(
            array(
              array(
                'action' => PhabricatorPolicy::ACTION_ALLOW,
                'rule' => 'PhabricatorUsersPolicyRule',
                'value' => array($actor_phid),
              ),
              array(
                'action' => PhabricatorPolicy::ACTION_ALLOW,
                'rule' => 'PhabricatorProjectsPolicyRule',
                'value' => array($sysadmin_project->getPHID()),
              ),
              array(
                'action' => PhabricatorPolicy::ACTION_ALLOW,
                'rule' => 'PhabricatorSubscriptionsSubscribersPolicyRule',
                'value' => array($object->getPHID()),
              ),
            ))
            ->save();

        $results[] = id(new ManiphestTransaction())
          ->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY)
          ->setNewValue($confidential_policy->getPHID());

        $results[] = id(new ManiphestTransaction())
          ->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY)
          ->setNewValue($confidential_policy->getPHID());
      } else {
        $results[] = id(new ManiphestTransaction())
          ->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY)
          ->setNewValue(PhabricatorPolicies::POLICY_USER);

        $results[] = id(new ManiphestTransaction())
          ->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY)
          ->setNewValue(PhabricatorPolicies::POLICY_USER);
545
      }
546
    }
547

548 549 550 551
    // CCU: If this is a purchasing type, then try to assign the task to the
    //      assignee, if empty. It's not overlay pleasant code, since we need
    //      to iterate the transactions, rather than interrogate an object.
    if ($this->getIsNewObject() && !$any_assign) {
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
      if ($subtype == 'purchasing') {
        if ($approver == null && $purchasing_project !== null) {
          $p_proj = id(new PhabricatorProjectQuery())
            ->setViewer($this->getActor())
            ->withPHIDs(array($purchasing_project))
            ->executeOne();

          if ($p_proj) {
            $fields = PhabricatorCustomField::getObjectFields($p_proj,
              PhabricatorCustomField::ROLE_VIEW);
            $fields->readFieldsFromStorage($p_proj);
            $fields->setViewer($this->getActor());
            foreach ($fields->getFields() as $field) {
              if ($field->getFieldKey() == 'std:project:ccu:purchasing-approver') {
                $phids = $field->getRequiredHandlePHIDsForPropertyView();
                foreach ($phids as $k => $a) {
                  if ($a) {
                    $approver = $a;
                  }
                }
              }
            }
          }

          if ($approver !== null) {
            $results[] = id(new ManiphestTransaction())
              ->setTransactionType(PhabricatorTransactions::TYPE_CUSTOMFIELD)
              ->attachObject($object)
              ->attachViewer($this->getActor())
              ->setMetadataValue('customfield:key', 'std:maniphest:purchasing:approver')
              ->setNewValue(array($approver));
          }
        }

        if ($approver !== null) {
          $results[] = id(new ManiphestTransaction())
            ->setTransactionType(ManiphestTaskOwnerTransaction::TRANSACTIONTYPE)
            ->setNewValue($approver);
        }
      }
    }

594 595 596 597 598 599 600 601 602 603 604
    // CCU: if there were an asset created in the process, refer it in the
    // purchase request.
    if ($asset_id) {
      $results[] = id(new ManiphestTransaction())
        ->setTransactionType(PhabricatorTransactions::TYPE_CUSTOMFIELD)
        ->attachObject($object)
        ->attachViewer($this->getActor())
        ->setMetadataValue('customfield:key', 'std:maniphest:purchasing:asset-id')
        ->setNewValue($asset_id);
    }

605 606 607
    // CCU: if it's a Shipping Request, check if it has an asset item
    // in Snipe-IT and automatically fill in some fields.
    if ($subtype == 'shipping') {
608 609 610 611 612
      try {
        $transactions = $snipe_api->fetchAssetItem($object, $xactions);
      } catch (Exception $e) {
        $transactions = [];
      }
613 614 615 616 617
      foreach ($transactions as $transaction) {
        $results[] = $transaction;
      }
    }

618 619 620 621 622 623 624 625 626
    return $results;
  }

  protected function expandTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    $results = parent::expandTransaction($object, $xaction);

627 628 629 630
    $type = $xaction->getTransactionType();
    switch ($type) {
      case PhabricatorTransactions::TYPE_COLUMNS:
        try {
631 632 633
          $more_xactions = $this->buildMoveTransaction($object, $xaction);
          foreach ($more_xactions as $more_xaction) {
            $results[] = $more_xaction;
634 635 636 637 638 639 640 641
          }
        } catch (Exception $ex) {
          $error = new PhabricatorApplicationTransactionValidationError(
            $type,
            pht('Invalid'),
            $ex->getMessage(),
            $xaction);
          $this->moreValidationErrors[] = $error;
642 643
        }
        break;
644
      case ManiphestTaskOwnerTransaction::TRANSACTIONTYPE:
645 646 647 648
        // If this is a no-op update, don't expand it.
        $old_value = $object->getOwnerPHID();
        $new_value = $xaction->getNewValue();
        if ($old_value === $new_value) {
649
          break;
650 651
        }

652 653
        // When a task is reassigned, move the old owner to the subscriber
        // list so they're still in the loop.
654
        if ($old_value) {
655 656 657 658 659
          $results[] = id(new ManiphestTransaction())
            ->setTransactionType(PhabricatorTransactions::TYPE_SUBSCRIBERS)
            ->setIgnoreOnNoEffect(true)
            ->setNewValue(
              array(
660
                '+' => array($old_value => $old_value),
661 662 663 664 665 666 667 668
              ));
        }
        break;
    }

    return $results;
  }

669 670 671
  private function buildMoveTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {
672
    $actor = $this->getActor();
673 674 675 676 677 678 679

    $new = $xaction->getNewValue();
    if (!is_array($new)) {
      $this->validateColumnPHID($new);
      $new = array($new);
    }

680
    $relative_phids = array();
681 682 683 684 685 686 687 688 689 690 691 692
    foreach ($new as $key => $value) {
      if (!is_array($value)) {
        $this->validateColumnPHID($value);
        $value = array(
          'columnPHID' => $value,
        );
      }

      PhutilTypeSpec::checkMap(
        $value,
        array(
          'columnPHID' => 'string',
693 694 695 696
          'beforePHIDs' => 'optional list<string>',
          'afterPHIDs' => 'optional list<string>',

          // Deprecated older variations of "beforePHIDs" and "afterPHIDs".
697 698 699 700
          'beforePHID' => 'optional string',
          'afterPHID' => 'optional string',
        ));

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
      $value = $value + array(
        'beforePHIDs' => array(),
        'afterPHIDs' => array(),
      );

      // Normalize the legacy keys "beforePHID" and "afterPHID" keys to the
      // modern format.
      if (!empty($value['afterPHID'])) {
        if ($value['afterPHIDs']) {
          throw new Exception(
            pht(
              'Transaction specifies both "afterPHID" and "afterPHIDs". '.
              'Specify only "afterPHIDs".'));
        }
        $value['afterPHIDs'] = array($value['afterPHID']);
        unset($value['afterPHID']);
      }

      if (isset($value['beforePHID'])) {
        if ($value['beforePHIDs']) {
          throw new Exception(
            pht(
              'Transaction specifies both "beforePHID" and "beforePHIDs". '.
              'Specify only "beforePHIDs".'));
        }
        $value['beforePHIDs'] = array($value['beforePHID']);
        unset($value['beforePHID']);
      }
729

730 731
      foreach ($value['beforePHIDs'] as $phid) {
        $relative_phids[] = $phid;
732 733
      }

734 735
      foreach ($value['afterPHIDs'] as $phid) {
        $relative_phids[] = $phid;
736
      }
737 738

      $new[$key] = $value;
739 740
    }

741 742 743 744 745 746 747 748
    // We require that objects you specify in "beforePHIDs" or "afterPHIDs"
    // are real objects which exist and which you have permission to view.
    // If you provide other objects, we remove them from the specification.

    if ($relative_phids) {
      $objects = id(new PhabricatorObjectQuery())
        ->setViewer($actor)
        ->withPHIDs($relative_phids)
749
        ->execute();
750
      $objects = mpull($objects, null, 'getPHID');
751
    } else {
752 753 754 755 756 757 758 759 760 761 762 763
      $objects = array();
    }

    foreach ($new as $key => $value) {
      $value['afterPHIDs'] = $this->filterValidPHIDs(
        $value['afterPHIDs'],
        $objects);
      $value['beforePHIDs'] = $this->filterValidPHIDs(
        $value['beforePHIDs'],
        $objects);

      $new[$key] = $value;
764 765 766 767 768
    }

    $column_phids = ipull($new, 'columnPHID');
    if ($column_phids) {
      $columns = id(new PhabricatorProjectColumnQuery())
769
        ->setViewer($actor)
770 771 772 773 774 775 776 777 778 779 780 781
        ->withPHIDs($column_phids)
        ->execute();
      $columns = mpull($columns, null, 'getPHID');
    } else {
      $columns = array();
    }

    $board_phids = mpull($columns, 'getProjectPHID');
    $object_phid = $object->getPHID();

    // Note that we may not have an object PHID if we're creating a new
    // object.
782
    $object_phids = array();
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    if ($object_phid) {
      $object_phids[] = $object_phid;
    }

    if ($object_phids) {
      $layout_engine = id(new PhabricatorBoardLayoutEngine())
        ->setViewer($this->getActor())
        ->setBoardPHIDs($board_phids)
        ->setObjectPHIDs($object_phids)
        ->setFetchAllBoards(true)
        ->executeLayout();
    }

    foreach ($new as $key => $spec) {
      $column_phid = $spec['columnPHID'];
      $column = idx($columns, $column_phid);
      if (!$column) {
        throw new Exception(
          pht(
            'Column move transaction specifies column PHID "%s", but there '.
            'is no corresponding column with this PHID.',
            $column_phid));
      }

      $board_phid = $column->getProjectPHID();

      if ($object_phid) {
        $old_columns = $layout_engine->getObjectColumns(
          $board_phid,
          $object_phid);
        $old_column_phids = mpull($old_columns, 'getPHID');
      } else {
        $old_column_phids = array();
      }

      $spec += array(
        'boardPHID' => $board_phid,
        'fromColumnPHIDs' => $old_column_phids,
      );

      // Check if the object is already in this column, and isn't being moved.
      // We can just drop this column change if it has no effect.
      $from_map = array_fuse($spec['fromColumnPHIDs']);
      $already_here = isset($from_map[$column_phid]);

828
      $is_reordering = ($spec['afterPHIDs'] || $spec['beforePHIDs']);
829 830 831 832 833 834 835 836 837
      if ($already_here && !$is_reordering) {
        unset($new[$key]);
      } else {
        $new[$key] = $spec;
      }
    }

    $new = array_values($new);
    $xaction->setNewValue($new);
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920


    $more = array();

    // If we're moving the object into a column and it does not already belong
    // in the column, add the appropriate board. For normal columns, this
    // is the board PHID. For proxy columns, it is the proxy PHID, unless the
    // object is already a member of some descendant of the proxy PHID.

    // The major case where this can happen is moves via the API, but it also
    // happens when a user drags a task from the "Backlog" to a milestone
    // column.

    if ($object_phid) {
      $current_phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
        $object_phid,
        PhabricatorProjectObjectHasProjectEdgeType::EDGECONST);
      $current_phids = array_fuse($current_phids);
    } else {
      $current_phids = array();
    }

    $add_boards = array();
    foreach ($new as $move) {
      $column_phid = $move['columnPHID'];
      $board_phid = $move['boardPHID'];
      $column = $columns[$column_phid];
      $proxy_phid = $column->getProxyPHID();

      // If this is a normal column, add the board if the object isn't already
      // associated.
      if (!$proxy_phid) {
        if (!isset($current_phids[$board_phid])) {
          $add_boards[] = $board_phid;
        }
        continue;
      }

      // If this is a proxy column but the object is already associated with
      // the proxy board, we don't need to do anything.
      if (isset($current_phids[$proxy_phid])) {
        continue;
      }

      // If this a proxy column and the object is already associated with some
      // descendant of the proxy board, we also don't need to do anything.
      $descendants = id(new PhabricatorProjectQuery())
        ->setViewer(PhabricatorUser::getOmnipotentUser())
        ->withAncestorProjectPHIDs(array($proxy_phid))
        ->execute();

      $found_descendant = false;
      foreach ($descendants as $descendant) {
        if (isset($current_phids[$descendant->getPHID()])) {
          $found_descendant = true;
          break;
        }
      }

      if ($found_descendant) {
        continue;
      }

      // Otherwise, we're moving the object to a proxy column which it is not
      // a member of yet, so add an association to the column's proxy board.

      $add_boards[] = $proxy_phid;
    }

    if ($add_boards) {
      $more[] = id(new ManiphestTransaction())
        ->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
        ->setMetadataValue(
          'edge:type',
          PhabricatorProjectObjectHasProjectEdgeType::EDGECONST)
        ->setIgnoreOnNoEffect(true)
        ->setNewValue(
          array(
            '+' => array_fuse($add_boards),
          ));
    }

    return $more;
921 922 923 924 925
  }

  private function applyBoardMove($object, array $move) {
    $board_phid = $move['boardPHID'];
    $column_phid = $move['columnPHID'];
926 927 928

    $before_phids = $move['beforePHIDs'];
    $after_phids = $move['afterPHIDs'];
929 930 931

    $object_phid = $object->getPHID();

Dmitri Iouchtchenko's avatar
Dmitri Iouchtchenko committed
932
    // We're doing layout with the omnipotent viewer to make sure we don't
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
    // remove positions in columns that exist, but which the actual actor
    // can't see.
    $omnipotent_viewer = PhabricatorUser::getOmnipotentUser();

    $select_phids = array($board_phid);

    $descendants = id(new PhabricatorProjectQuery())
      ->setViewer($omnipotent_viewer)
      ->withAncestorProjectPHIDs($select_phids)
      ->execute();
    foreach ($descendants as $descendant) {
      $select_phids[] = $descendant->getPHID();
    }

    $board_tasks = id(new ManiphestTaskQuery())
      ->setViewer($omnipotent_viewer)
      ->withEdgeLogicPHIDs(
        PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
        PhabricatorQueryConstraint::OPERATOR_ANCESTOR,
        array($select_phids))
      ->execute();

    $board_tasks = mpull($board_tasks, null, 'getPHID');
    $board_tasks[$object_phid] = $object;

    // Make sure tasks are sorted by ID, so we lay out new positions in
    // a consistent way.
    $board_tasks = msort($board_tasks, 'getID');

    $object_phids = array_keys($board_tasks);

    $engine = id(new PhabricatorBoardLayoutEngine())
      ->setViewer($omnipotent_viewer)
      ->setBoardPHIDs(array($board_phid))
      ->setObjectPHIDs($object_phids)
      ->executeLayout();

    // TODO: This logic needs to be revised when we legitimately support
    // multiple column positions.
    $columns = $engine->getObjectColumns($board_phid, $object_phid);
    foreach ($columns as $column) {
      $engine->queueRemovePosition(
        $board_phid,
        $column->getPHID(),
        $object_phid);
    }

980 981 982 983 984 985
    $engine->queueAddPosition(
      $board_phid,
      $column_phid,
      $object_phid,
      $after_phids,
      $before_phids);
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

    $engine->applyPositionUpdates();
  }


  private function validateColumnPHID($value) {
    if (phid_get_type($value) == PhabricatorProjectColumnPHIDType::TYPECONST) {
      return;
    }

    throw new Exception(
      pht(
        'When moving objects between columns on a board, columns must '.
        'be identified by PHIDs. This transaction uses "%s" to identify '.
        'a column, but that is not a valid column PHID.',
        $value));
  }


1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  private function getLockValidationErrors($object, array $xactions) {
    $errors = array();

    $old_owner = $object->getOwnerPHID();
    $old_status = $object->getStatus();

    $new_owner = $old_owner;
    $new_status = $old_status;

    $owner_xaction = null;
    $status_xaction = null;

    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
        case ManiphestTaskOwnerTransaction::TRANSACTIONTYPE:
          $new_owner = $xaction->getNewValue();
          $owner_xaction = $xaction;
          break;
        case ManiphestTaskStatusTransaction::TRANSACTIONTYPE:
          $new_status = $xaction->getNewValue();
          $status_xaction = $xaction;
          break;
      }
    }

    $actor_phid = $this->getActingAsPHID();

    $was_locked = ManiphestTaskStatus::areEditsLockedInStatus(
      $old_status);
    $now_locked = ManiphestTaskStatus::areEditsLockedInStatus(
      $new_status);

    if (!$now_locked) {
      // If we're not ending in an edit-locked status, everything is good.
    } else if ($new_owner !== null) {
      // If we ending the edit with some valid owner, this is allowed for
      // now. We might need to revisit this.
    } else {
      // The edits end with the task locked and unowned. No one will be able
      // to edit it, so we forbid this. We try to be specific about what the
      // user did wrong.

      $owner_changed = ($old_owner && !$new_owner);
      $status_changed = ($was_locked !== $now_locked);
      $message = null;

      if ($status_changed && $owner_changed) {
        $message = pht(
          'You can not lock this task and unassign it at the same time '.
          'because no one will be able to edit it anymore. Lock the task '.
          'or remove the owner, but not both.');
        $problem_xaction = $status_xaction;
      } else if ($status_changed) {
        $message = pht(
          'You can not lock this task because it does not have an owner. '.
          'No one would be able to edit the task. Assign the task to an '.
          'owner before locking it.');
        $problem_xaction = $status_xaction;
      } else if ($owner_changed) {
        $message = pht(
          'You can not remove the owner of this task because it is locked '.
          'and no one would be able to edit the task. Reassign the task or '.
          'unlock it before removing the owner.');
        $problem_xaction = $owner_xaction;
      } else {
        // If the task was already broken, we don't have a transaction to
        // complain about so just let it through. In theory, this is
        // impossible since policy rules should kick in before we get here.
      }

      if ($message) {
        $errors[] = new PhabricatorApplicationTransactionValidationError(
          $problem_xaction->getTransactionType(),
          pht('Lock Error'),
          $message,
          $problem_xaction);
      }
    }

    return $errors;
  }
1086

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
  private function filterValidPHIDs($phid_list, array $object_map) {
    foreach ($phid_list as $key => $phid) {
      if (isset($object_map[$phid])) {
        continue;
      }

      unset($phid_list[$key]);
    }

    return array_values($phid_list);
  }

1099
  protected function didApplyTransactions($object, array $xactions) {
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    $send_notifications = PhabricatorNotificationClient::isEnabled();
    if ($send_notifications) {
      $old_phids = $this->oldProjectPHIDs;
      $new_phids = $this->loadProjectPHIDs($object);

      // We want to emit update notifications for all old and new tagged
      // projects, and all parents of those projects. For example, if an
      // edit removes project "A > B" from a task, the "A" workboard should
      // receive an update event.

      $project_phids = array_fuse($old_phids) + array_fuse($new_phids);
      $project_phids = array_keys($project_phids);

1113 1114 1115 1116 1117
      if ($project_phids) {
        $projects = id(new PhabricatorProjectQuery())
          ->setViewer(PhabricatorUser::getOmnipotentUser())
          ->withPHIDs($project_phids)
          ->execute();
1118

1119 1120 1121 1122 1123 1124
        $notify_projects = array();
        foreach ($projects as $project) {
          $notify_projects[$project->getPHID()] = $project;
          foreach ($project->getAncestorProjects() as $ancestor) {
            $notify_projects[$ancestor->getPHID()] = $ancestor;
          }
1125 1126
        }

1127 1128 1129 1130
        foreach ($notify_projects as $key => $project) {
          if (!$project->getHasWorkboard()) {
            unset($notify_projects[$key]);
          }
1131 1132
        }

1133
        $notify_phids = array_keys($notify_projects);
1134

1135 1136 1137 1138 1139
        if ($notify_phids) {
          $data = array(
            'type' => 'workboards',
            'subscribers' => $notify_phids,
          );
1140

1141 1142
          PhabricatorNotificationClient::tryToPostMessage($data);
        }
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
      }
    }

    return $xactions;
  }

  private function loadProjectPHIDs(ManiphestTask $task) {
    if (!$task->getPHID()) {
      return array();
    }
1153 1154

    $edge_query = id(new PhabricatorEdgeQuery())
1155
      ->withSourcePHIDs(array($task->getPHID()))
1156 1157 1158 1159 1160 1161 1162
      ->withEdgeTypes(
        array(
          PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
        ));

    $edge_query->execute();

1163
    return $edge_query->getDestinationPHIDs();
1164 1165
  }

epriestley's avatar
epriestley committed
1166
}