<?php

// Previously, files generated by "View Raw File" were written as permanent
// files with excessively wide view permissions. This destroys these files
// so they are recreated as temporary files with correct permissions when
// next accessed.

$table = new DifferentialChangeset();
$conn = $table->establishConnection('w');
$viewer = PhabricatorUser::getOmnipotentUser();

$iterator = new LiskRawMigrationIterator(
  $conn,
  $table->getTableName());

echo tsprintf(
  "%s\n",
  pht('Purging old raw changeset file caches...'));

$keys = array(
  'raw:new:phid',
  'raw:old:phid',
);

foreach ($iterator as $changeset) {
  try {
    $metadata = phutil_json_decode($changeset['metadata']);

    $phids = array();
    foreach ($keys as $key) {
      if (isset($metadata[$key])) {
        $phids[] = $metadata[$key];
      }
    }

    foreach ($phids as $phid) {
      $file = id(new PhabricatorFileQuery())
        ->setViewer($viewer)
        ->withPHIDs(array($phid))
        ->executeOne();
      if ($file) {
        id(new PhabricatorDestructionEngine())
          ->destroyObject($file);
      }
    }

    // NOTE: We don't bother updating the changeset record itself: we already
    // regenerate the cache properly if the stored value isn't valid.

  } catch (Exception $ex) {
    // Just move on if we run into trouble.
  }
}
