ManiphestTransactionEditor.php 30.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
7
  private $moreValidationErrors = array();

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

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

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

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

    return $types;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

94
95
96
97
98
99
100
101
102
  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()) {
103
        case ManiphestTaskStatusTransaction::TRANSACTIONTYPE:
104
105
106
107
108
109
110
111
          $unblock_xaction = $xaction;
          break;
      }
    }

    if ($unblock_xaction !== null) {
      $blocked_phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
        $object->getPHID(),
112
        ManiphestTaskDependedOnByTaskEdgeType::EDGECONST);
113
114
115
116
117
118
      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)
119
          ->needSubscriberPHIDs(true)
120
          ->needProjectPHIDs(true)
121
122
123
124
125
126
          ->execute();

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

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

133
134
135
136
          if ($this->getIsNewObject()) {
            $parent_xaction->setMetadataValue('blocker.new', true);
          }

137
138
          id(new ManiphestTransactionEditor())
            ->setActor($this->getActor())
139
            ->setActingAsPHID($this->getActingAsPHID())
140
141
142
            ->setContentSource($this->getContentSource())
            ->setContinueOnNoEffect(true)
            ->setContinueOnMissingFields(true)
143
            ->applyTransactions($blocked_task, array($parent_xaction));
144
145
146
147
148
149
150
        }
      }
    }

    return $xactions;
  }

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

157
158
159
160
161
162
163
164
165
  protected function getMailSubjectPrefix() {
    return PhabricatorEnv::getEnvConfig('metamta.maniphest.subject-prefix');
  }

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

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

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

    return $phids;
174
175
  }

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

199
200
201
202
203
204
205
206
207
208
  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())
209
      ->setSubject("T{$id}: {$title}");
210
211
212
213
214
215
216
217
218
  }

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

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

    if ($this->getIsNewObject()) {
Joshua Spence's avatar
Joshua Spence committed
219
      $body->addRemarkupSection(
220
221
222
223
        pht('TASK DESCRIPTION'),
        $object->getDescription());
    }

224
    $body->addLinkSection(
225
226
227
      pht('TASK DETAIL'),
      PhabricatorEnv::getProductionURI('/T'.$object->getID()));

228
229

    $board_phids = array();
230
    $type_columns = PhabricatorTransactions::TYPE_COLUMNS;
231
    foreach ($xactions as $xaction) {
232
233
234
235
      if ($xaction->getTransactionType() == $type_columns) {
        $moves = $xaction->getNewValue();
        foreach ($moves as $move) {
          $board_phids[] = $move['boardPHID'];
236
237
238
239
240
241
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'),
          PhabricatorEnv::getProductionURI(
            '/project/board/'.$project->getID().'/'));
      }
    }


255
256
257
    return $body;
  }

258
259
260
  protected function shouldPublishFeedStory(
    PhabricatorLiskDAO $object,
    array $xactions) {
261
    return true;
262
263
264
265
266
267
  }

  protected function supportsSearch() {
    return true;
  }

268
269
270
  protected function shouldApplyHeraldRules(
    PhabricatorLiskDAO $object,
    array $xactions) {
271
272
273
274
275
276
277
278
279
280
281
    return true;
  }

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

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

282
283
284
285
286
287
288
  protected function requireCapabilities(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    parent::requireCapabilities($object, $xaction);

    $app_capability_map = array(
289
      ManiphestTaskPriorityTransaction::TRANSACTIONTYPE =>
Joshua Spence's avatar
Joshua Spence committed
290
        ManiphestEditPriorityCapability::CAPABILITY,
291
      ManiphestTaskStatusTransaction::TRANSACTIONTYPE =>
Joshua Spence's avatar
Joshua Spence committed
292
        ManiphestEditStatusCapability::CAPABILITY,
293
      ManiphestTaskOwnerTransaction::TRANSACTIONTYPE =>
Joshua Spence's avatar
Joshua Spence committed
294
        ManiphestEditAssignCapability::CAPABILITY,
295
      PhabricatorTransactions::TYPE_EDIT_POLICY =>
Joshua Spence's avatar
Joshua Spence committed
296
        ManiphestEditPoliciesCapability::CAPABILITY,
297
      PhabricatorTransactions::TYPE_VIEW_POLICY =>
Joshua Spence's avatar
Joshua Spence committed
298
        ManiphestEditPoliciesCapability::CAPABILITY,
299
300
    );

301

302
    $transaction_type = $xaction->getTransactionType();
303
304
305
306
307

    $app_capability = null;
    if ($transaction_type == PhabricatorTransactions::TYPE_EDGE) {
      switch ($xaction->getMetadataValue('edge:type')) {
        case PhabricatorProjectObjectHasProjectEdgeType::EDGECONST:
Joshua Spence's avatar
Joshua Spence committed
308
          $app_capability = ManiphestEditProjectsCapability::CAPABILITY;
309
310
311
312
313
          break;
      }
    } else {
      $app_capability = idx($app_capability_map, $transaction_type);
    }
314
315
316
317

    if ($app_capability) {
      $app = id(new PhabricatorApplicationQuery())
        ->setViewer($this->getActor())
318
        ->withClasses(array('PhabricatorManiphestApplication'))
319
320
321
322
323
324
325
326
        ->executeOne();
      PhabricatorPolicyFilter::requireCapability(
        $this->getActor(),
        $app,
        $app_capability);
    }
  }

327
328
329
330
331
332
333
  protected function adjustObjectForPolicyChecks(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $copy = parent::adjustObjectForPolicyChecks($object, $xactions);
    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
334
        case ManiphestTaskOwnerTransaction::TRANSACTIONTYPE:
335
336
337
338
339
340
341
342
343
          $copy->setOwnerPHID($xaction->getNewValue());
          break;
        default:
          continue;
      }
    }

    return $copy;
  }
344

345
346
347
348
349
350
351
352
353
354
355
356
357
  /**
   * Get priorities for moving a task to a new priority.
   */
  public static function getEdgeSubpriority(
    $priority,
    $is_end) {

    $query = id(new ManiphestTaskQuery())
      ->setViewer(PhabricatorUser::getOmnipotentUser())
      ->withPriorities(array($priority))
      ->setLimit(1);

    if ($is_end) {
358
359
360
      $query->setOrderVector(array('-priority', '-subpriority', '-id'));
    } else {
      $query->setOrderVector(array('priority', 'subpriority', 'id'));
361
362
    }

363
364
365
366
367
368
369
370
371
372
    $result = $query->executeOne();
    $step = (double)(2 << 32);

    if ($result) {
      $base = $result->getSubpriority();
      if ($is_end) {
        $sub = ($base - $step);
      } else {
        $sub = ($base + $step);
      }
373
    } else {
374
      $sub = 0;
375
    }
376

377
378
379
380
381
382
383
384
385
    return array($priority, $sub);
  }


  /**
   * Get priorities for moving a task before or after another task.
   */
  public static function getAdjacentSubpriority(
    ManiphestTask $dst,
386
    $is_after) {
387
388
389

    $query = id(new ManiphestTaskQuery())
      ->setViewer(PhabricatorUser::getOmnipotentUser())
390
      ->setOrder(ManiphestTaskQuery::ORDER_PRIORITY)
391
392
393
394
395
      ->withPriorities(array($dst->getPriority()))
      ->setLimit(1);

    if ($is_after) {
      $query->setAfterID($dst->getID());
396
    } else {
397
      $query->setBeforeID($dst->getID());
398
399
    }

400
401
402
403
404
405
406
407
    $adjacent = $query->executeOne();

    $base = $dst->getSubpriority();
    $step = (double)(2 << 32);

    // If we find an adjacent task, we average the two subpriorities and
    // return the result.
    if ($adjacent) {
408
      $epsilon = 1.0;
409

410
      // If the adjacent task has a subpriority that is identical or very
411
412
413
414
415
416
417
418
419
420
      // close to the task we're looking at, we're going to spread out all
      // the nearby tasks.

      $adjacent_sub = $adjacent->getSubpriority();
      if ((abs($adjacent_sub - $base) < $epsilon)) {
        $base = self::disperseBlock(
          $dst,
          $epsilon * 2);
        if ($is_after) {
          $sub = $base - $epsilon;
421
        } else {
422
          $sub = $base + $epsilon;
423
        }
424
425
      } else {
        $sub = ($adjacent_sub + $base) / 2;
426
      }
427
    } else {
428
429
430
431
432
433
434
      // Otherwise, we take a step away from the target's subpriority and
      // use that.
      if ($is_after) {
        $sub = ($base - $step);
      } else {
        $sub = ($base + $step);
      }
435
    }
436
437

    return array($dst->getPriority(), $sub);
438
439
  }

440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
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
545
546
547
548
549
550
551
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
  /**
   * Distribute a cluster of tasks with similar subpriorities.
   */
  private static function disperseBlock(
    ManiphestTask $task,
    $spacing) {

    $conn = $task->establishConnection('w');

    // Find a block of subpriority space which is, on average, sparse enough
    // to hold all the tasks that are inside it with a reasonable level of
    // separation between them.

    // We'll start by looking near the target task for a range of numbers
    // which has more space available than tasks. For example, if the target
    // task has subpriority 33 and we want to separate each task by at least 1,
    // we might start by looking in the range [23, 43].

    // If we find fewer than 20 tasks there, we have room to reassign them
    // with the desired level of separation. We space them out, then we're
    // done.

    // However: if we find more than 20 tasks, we don't have enough room to
    // distribute them. We'll widen our search and look in a bigger range,
    // maybe [13, 53]. This range has more space, so if we find fewer than
    // 40 tasks in this range we can spread them out. If we still find too
    // many tasks, we keep widening the search.

    $base = $task->getSubpriority();

    $scale = 4.0;
    while (true) {
      $range = ($spacing * $scale) / 2.0;
      $min = ($base - $range);
      $max = ($base + $range);

      $result = queryfx_one(
        $conn,
        'SELECT COUNT(*) N FROM %T WHERE priority = %d AND
          subpriority BETWEEN %f AND %f',
        $task->getTableName(),
        $task->getPriority(),
        $min,
        $max);

      $count = $result['N'];
      if ($count < $scale) {
        // We have found a block which we can make sparse enough, so bail and
        // continue below with our selection.
        break;
      }

      // This block had too many tasks for its size, so try again with a
      // bigger block.
      $scale *= 2.0;
    }

    $rows = queryfx_all(
      $conn,
      'SELECT id FROM %T WHERE priority = %d AND
        subpriority BETWEEN %f AND %f
        ORDER BY priority, subpriority, id',
      $task->getTableName(),
      $task->getPriority(),
      $min,
      $max);

    $task_id = $task->getID();
    $result = null;

    // NOTE: In strict mode (which we encourage enabling) we can't structure
    // this bulk update as an "INSERT ... ON DUPLICATE KEY UPDATE" unless we
    // provide default values for ALL of the columns that don't have defaults.

    // This is gross, but we may be moving enough rows that individual
    // queries are unreasonably slow. An alternate construction which might
    // be worth evaluating is to use "CASE". Another approach is to disable
    // strict mode for this query.

    $extra_columns = array(
      'phid' => '""',
      'authorPHID' => '""',
      'status' => '""',
      'priority' => 0,
      'title' => '""',
      'originalTitle' => '""',
      'description' => '""',
      'dateCreated' => 0,
      'dateModified' => 0,
      'mailKey' => '""',
      'viewPolicy' => '""',
      'editPolicy' => '""',
      'ownerOrdering' => '""',
      'spacePHID' => '""',
      'bridgedObjectPHID' => '""',
      'properties' => '""',
      'points' => 0,
      'subtype' => '""',
    );

    $defaults = implode(', ', $extra_columns);

    $sql = array();
    $offset = 0;

    // Often, we'll have more room than we need in the range. Distribute the
    // tasks evenly over the whole range so that we're less likely to end up
    // with tasks spaced exactly the minimum distance apart, which may
    // get shifted again later. We have one fewer space to distribute than we
    // have tasks.
    $divisor = (double)(count($rows) - 1.0);
    if ($divisor > 0) {
      $available_distance = (($max - $min) / $divisor);
    } else {
      $available_distance = 0.0;
    }

    foreach ($rows as $row) {
      $subpriority = $min + ($offset * $available_distance);

      // If this is the task that we're spreading out relative to, keep track
      // of where it is ending up so we can return the new subpriority.
      $id = $row['id'];
      if ($id == $task_id) {
        $result = $subpriority;
      }

      $sql[] = qsprintf(
        $conn,
        '(%d, %Q, %f)',
        $id,
        $defaults,
        $subpriority);

      $offset++;
    }

    foreach (PhabricatorLiskDAO::chunkSQL($sql) as $chunk) {
      queryfx(
        $conn,
        'INSERT INTO %T (id, %Q, subpriority) VALUES %Q
          ON DUPLICATE KEY UPDATE subpriority = VALUES(subpriority)',
        $task->getTableName(),
        implode(', ', array_keys($extra_columns)),
        $chunk);
    }

    return $result;
  }

590
591
592
593
594
595
596
597
598
599
600
601
602
  protected function validateAllTransactions(
    PhabricatorLiskDAO $object,
    array $xactions) {

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

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

    return $errors;
  }

603
604
605
  protected function expandTransactions(
    PhabricatorLiskDAO $object,
    array $xactions) {
606
607
608
609

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

610
611
612
613
614
615
    $results = parent::expandTransactions($object, $xactions);

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

    $any_assign = false;
    foreach ($xactions as $xaction) {
616
617
      if ($xaction->getTransactionType() ==
        ManiphestTaskOwnerTransaction::TRANSACTIONTYPE) {
618
619
620
621
622
623
624
625
626
627
        $any_assign = true;
        break;
      }
    }

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

    $new_status = null;
    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
628
        case ManiphestTaskStatusTransaction::TRANSACTIONTYPE:
629
630
631
632
633
634
635
636
637
638
639
640
641
642
          $new_status = $xaction->getNewValue();
          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) {
643
644
      $is_claim = ManiphestTaskStatus::isClaimStatus($new_status);

645
      // Don't assign the actor if they aren't a real user.
646
647
      // Don't claim the task if the status is configured to not claim.
      if ($actor_phid && $is_claim) {
648
        $results[] = id(new ManiphestTransaction())
649
          ->setTransactionType(ManiphestTaskOwnerTransaction::TRANSACTIONTYPE)
650
651
652
653
          ->setNewValue($actor_phid);
      }
    }

654
655
656
657
658
659
660
661
662
663
664
665
    // 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),
            ));
      }
    }

666
667
668
669
670
671
672
673
674
    return $results;
  }

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

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

675
676
677
678
    $type = $xaction->getTransactionType();
    switch ($type) {
      case PhabricatorTransactions::TYPE_COLUMNS:
        try {
679
680
681
          $more_xactions = $this->buildMoveTransaction($object, $xaction);
          foreach ($more_xactions as $more_xaction) {
            $results[] = $more_xaction;
682
683
684
685
686
687
688
689
          }
        } catch (Exception $ex) {
          $error = new PhabricatorApplicationTransactionValidationError(
            $type,
            pht('Invalid'),
            $ex->getMessage(),
            $xaction);
          $this->moreValidationErrors[] = $error;
690
691
        }
        break;
692
      case ManiphestTaskOwnerTransaction::TRANSACTIONTYPE:
693
694
695
696
697
698
699
        // If this is a no-op update, don't expand it.
        $old_value = $object->getOwnerPHID();
        $new_value = $xaction->getNewValue();
        if ($old_value === $new_value) {
          continue;
        }

700
701
        // When a task is reassigned, move the old owner to the subscriber
        // list so they're still in the loop.
702
        if ($old_value) {
703
704
705
706
707
          $results[] = id(new ManiphestTransaction())
            ->setTransactionType(PhabricatorTransactions::TYPE_SUBSCRIBERS)
            ->setIgnoreOnNoEffect(true)
            ->setNewValue(
              array(
708
                '+' => array($old_value => $old_value),
709
710
711
712
713
714
715
716
              ));
        }
        break;
    }

    return $results;
  }

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
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
828
829
830
831
832
833
834
835
836
837
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
  private function buildMoveTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

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

    $nearby_phids = array();
    foreach ($new as $key => $value) {
      if (!is_array($value)) {
        $this->validateColumnPHID($value);
        $value = array(
          'columnPHID' => $value,
        );
      }

      PhutilTypeSpec::checkMap(
        $value,
        array(
          'columnPHID' => 'string',
          'beforePHID' => 'optional string',
          'afterPHID' => 'optional string',
        ));

      $new[$key] = $value;

      if (!empty($value['beforePHID'])) {
        $nearby_phids[] = $value['beforePHID'];
      }

      if (!empty($value['afterPHID'])) {
        $nearby_phids[] = $value['afterPHID'];
      }
    }

    if ($nearby_phids) {
      $nearby_objects = id(new PhabricatorObjectQuery())
        ->setViewer($this->getActor())
        ->withPHIDs($nearby_phids)
        ->execute();
      $nearby_objects = mpull($nearby_objects, null, 'getPHID');
    } else {
      $nearby_objects = array();
    }

    $column_phids = ipull($new, 'columnPHID');
    if ($column_phids) {
      $columns = id(new PhabricatorProjectColumnQuery())
        ->setViewer($this->getActor())
        ->withPHIDs($column_phids)
        ->execute();
      $columns = mpull($columns, null, 'getPHID');
    } else {
      $columns = array();
    }

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

    $object_phids = $nearby_phids;

    // Note that we may not have an object PHID if we're creating a new
    // object.
    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();

      $nearby = array();

      if (!empty($spec['beforePHID'])) {
        $nearby['beforePHID'] = $spec['beforePHID'];
      }

      if (!empty($spec['afterPHID'])) {
        $nearby['afterPHID'] = $spec['afterPHID'];
      }

      if (count($nearby) > 1) {
        throw new Exception(
          pht(
            'Column move transaction moves object to multiple positions. '.
            'Specify only "beforePHID" or "afterPHID", not both.'));
      }

      foreach ($nearby as $where => $nearby_phid) {
        if (empty($nearby_objects[$nearby_phid])) {
          throw new Exception(
            pht(
              'Column move transaction specifies object "%s" as "%s", but '.
              'there is no corresponding object with this PHID.',
              $object_phid,
              $where));
        }

        $nearby_columns = $layout_engine->getObjectColumns(
          $board_phid,
          $nearby_phid);
        $nearby_columns = mpull($nearby_columns, null, 'getPHID');

        if (empty($nearby_columns[$column_phid])) {
          throw new Exception(
            pht(
              'Column move transaction specifies object "%s" as "%s" in '.
              'column "%s", but this object is not in that column!',
              $nearby_phid,
              $where,
              $column_phid));
        }
      }

      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]);
      $is_reordering = (bool)$nearby;

      if ($already_here && !$is_reordering) {
        unset($new[$key]);
      } else {
        $new[$key] = $spec;
      }
    }

    $new = array_values($new);
    $xaction->setNewValue($new);
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
921
922
923
924
925
926
927
928
929
930
931
932
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


    $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;
964
965
966
967
968
969
970
971
972
973
  }

  private function applyBoardMove($object, array $move) {
    $board_phid = $move['boardPHID'];
    $column_phid = $move['columnPHID'];
    $before_phid = idx($move, 'beforePHID');
    $after_phid = idx($move, 'afterPHID');

    $object_phid = $object->getPHID();

Dmitri Iouchtchenko's avatar
Dmitri Iouchtchenko committed
974
    // We're doing layout with the omnipotent viewer to make sure we don't
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
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
    // 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);
    }

    if ($before_phid) {
      $engine->queueAddPositionBefore(
        $board_phid,
        $column_phid,
        $object_phid,
        $before_phid);
    } else if ($after_phid) {
      $engine->queueAddPositionAfter(
        $board_phid,
        $column_phid,
        $object_phid,
        $after_phid);
    } else {
      $engine->queueAddPosition(
        $board_phid,
        $column_phid,
        $object_phid);
    }

    $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));
  }


1059

epriestley's avatar
epriestley committed
1060
}