repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/exception/PhabricatorWorkerYieldException.php
src/infrastructure/daemon/workers/exception/PhabricatorWorkerYieldException.php
<?php /** * Allows tasks to yield to other tasks. * * If a worker throws this exception while processing a task, the task will be * pushed toward the back of the queue and tried again later. */ final class PhabricatorWorkerYieldException extends Exception { private $duration; public function __construct($duration) { $this->duration = $duration; parent::__construct(); } public function getDuration() { return $this->duration; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/exception/PhabricatorWorkerPermanentFailureException.php
src/infrastructure/daemon/workers/exception/PhabricatorWorkerPermanentFailureException.php
<?php final class PhabricatorWorkerPermanentFailureException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/__tests__/PhabricatorTestWorker.php
src/infrastructure/daemon/workers/__tests__/PhabricatorTestWorker.php
<?php final class PhabricatorTestWorker extends PhabricatorWorker { public function getRequiredLeaseTime() { return idx( $this->getTaskData(), 'getRequiredLeaseTime', parent::getRequiredLeaseTime()); } public function getMaximumRetryCount() { return idx( $this->getTaskData(), 'getMaximumRetryCount', parent::getMaximumRetryCount()); } public function getWaitBeforeRetry(PhabricatorWorkerTask $task) { return idx( $this->getTaskData(), 'getWaitBeforeRetry', parent::getWaitBeforeRetry($task)); } protected function doWork() { $data = $this->getTaskData(); $duration = idx($data, 'duration'); if ($duration) { usleep($duration * 1000000); } switch (idx($data, 'doWork')) { case 'fail-temporary': throw new Exception(pht('Temporary failure!')); case 'fail-permanent': throw new PhabricatorWorkerPermanentFailureException( pht('Permanent failure!')); default: return; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/__tests__/PhabricatorWorkerBulkJobTestCase.php
src/infrastructure/daemon/workers/__tests__/PhabricatorWorkerBulkJobTestCase.php
<?php final class PhabricatorWorkerBulkJobTestCase extends PhabricatorTestCase { public function testGetAllBulkJobTypes() { PhabricatorWorkerBulkJobType::getAllJobTypes(); $this->assertTrue(true); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/__tests__/PhabricatorWorkerTestCase.php
src/infrastructure/daemon/workers/__tests__/PhabricatorWorkerTestCase.php
<?php final class PhabricatorWorkerTestCase extends PhabricatorTestCase { protected function getPhabricatorTestCaseConfiguration() { return array( self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true, ); } protected function willRunOneTest($test) { parent::willRunOneTest($test); // Before we run these test cases, clear the queue. After D20412, we may // have queued tasks from migrations. $task_table = new PhabricatorWorkerActiveTask(); $conn = $task_table->establishConnection('w'); queryfx( $conn, 'TRUNCATE %R', $task_table); } public function testLeaseTask() { $task = $this->scheduleTask(); $this->expectNextLease($task, pht('Leasing should work.')); } public function testMultipleLease() { $task = $this->scheduleTask(); $this->expectNextLease($task); $this->expectNextLease( null, pht('We should not be able to lease a task multiple times.')); } public function testOldestFirst() { $task1 = $this->scheduleTask(); $task2 = $this->scheduleTask(); $this->expectNextLease( $task1, pht('Older tasks should lease first, all else being equal.')); $this->expectNextLease($task2); } public function testNewBeforeLeased() { $task1 = $this->scheduleTask(); $task2 = $this->scheduleTask(); $task1->setLeaseOwner('test'); $task1->setLeaseExpires(time() - 100000); $task1->forceSaveWithoutLease(); $this->expectNextLease( $task2, pht( 'Tasks not previously leased should lease before previously '. 'leased tasks.')); $this->expectNextLease($task1); } public function testExecuteTask() { $task = $this->scheduleAndExecuteTask(); $this->assertEqual(true, $task->isArchived()); $this->assertEqual( PhabricatorWorkerArchiveTask::RESULT_SUCCESS, $task->getResult()); } public function testPermanentTaskFailure() { $task = $this->scheduleAndExecuteTask( array( 'doWork' => 'fail-permanent', )); $this->assertEqual(true, $task->isArchived()); $this->assertEqual( PhabricatorWorkerArchiveTask::RESULT_FAILURE, $task->getResult()); } public function testTemporaryTaskFailure() { $task = $this->scheduleAndExecuteTask( array( 'doWork' => 'fail-temporary', )); $this->assertFalse($task->isArchived()); $this->assertTrue($task->getExecutionException() instanceof Exception); } public function testTooManyTaskFailures() { // Expect temporary failures, then a permanent failure. $task = $this->scheduleAndExecuteTask( array( 'doWork' => 'fail-temporary', 'getMaximumRetryCount' => 3, 'getWaitBeforeRetry' => -60, )); // Temporary... $this->assertFalse($task->isArchived()); $this->assertTrue($task->getExecutionException() instanceof Exception); $this->assertEqual(1, $task->getFailureCount()); // Temporary... $task = $this->expectNextLease($task); $task = $task->executeTask(); $this->assertFalse($task->isArchived()); $this->assertTrue($task->getExecutionException() instanceof Exception); $this->assertEqual(2, $task->getFailureCount()); // Temporary... $task = $this->expectNextLease($task); $task = $task->executeTask(); $this->assertFalse($task->isArchived()); $this->assertTrue($task->getExecutionException() instanceof Exception); $this->assertEqual(3, $task->getFailureCount()); // Temporary... $task = $this->expectNextLease($task); $task = $task->executeTask(); $this->assertFalse($task->isArchived()); $this->assertTrue($task->getExecutionException() instanceof Exception); $this->assertEqual(4, $task->getFailureCount()); // Permanent. $task = $this->expectNextLease($task); $task = $task->executeTask(); $this->assertTrue($task->isArchived()); $this->assertEqual( PhabricatorWorkerArchiveTask::RESULT_FAILURE, $task->getResult()); } public function testWaitBeforeRetry() { $task = $this->scheduleTask( array( 'doWork' => 'fail-temporary', 'getWaitBeforeRetry' => 1000000, )); $this->expectNextLease($task)->executeTask(); $this->expectNextLease(null); } public function testRequiredLeaseTime() { $task = $this->scheduleAndExecuteTask( array( 'getRequiredLeaseTime' => 1000000, )); $this->assertTrue(($task->getLeaseExpires() - time()) > 1000); } public function testLeasedIsOldestFirst() { $task1 = $this->scheduleTask(); $task2 = $this->scheduleTask(); $task1->setLeaseOwner('test'); $task1->setLeaseExpires(time() - 100000); $task1->forceSaveWithoutLease(); $task2->setLeaseOwner('test'); $task2->setLeaseExpires(time() - 200000); $task2->forceSaveWithoutLease(); $this->expectNextLease( $task2, pht( 'Tasks which expired earlier should lease first, '. 'all else being equal.')); $this->expectNextLease($task1); } public function testLeasedIsLowestPriority() { $task1 = $this->scheduleTask(array(), 2); $task2 = $this->scheduleTask(array(), 2); $task3 = $this->scheduleTask(array(), 1); $this->expectNextLease( $task3, pht('Tasks with a lower priority should be scheduled first.')); $this->expectNextLease( $task1, pht('Tasks with the same priority should be FIFO.')); $this->expectNextLease($task2); } private function expectNextLease($task, $message = null) { $leased = id(new PhabricatorWorkerLeaseQuery()) ->setLimit(1) ->execute(); if ($task === null) { $this->assertEqual(0, count($leased), $message); return null; } else { $this->assertEqual(1, count($leased), $message); $this->assertEqual( (int)head($leased)->getID(), (int)$task->getID(), $message); return head($leased); } } private function scheduleAndExecuteTask( array $data = array(), $priority = null) { $task = $this->scheduleTask($data, $priority); $task = $this->expectNextLease($task); $task = $task->executeTask(); return $task; } private function scheduleTask(array $data = array(), $priority = null) { return PhabricatorWorker::scheduleTask( 'PhabricatorTestWorker', $data, array('priority' => $priority)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/phid/PhabricatorWorkerTriggerPHIDType.php
src/infrastructure/daemon/workers/phid/PhabricatorWorkerTriggerPHIDType.php
<?php final class PhabricatorWorkerTriggerPHIDType extends PhabricatorPHIDType { const TYPECONST = 'TRIG'; public function getTypeName() { return pht('Trigger'); } public function newObject() { return new PhabricatorWorkerTrigger(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorDaemonsApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorWorkerTriggerQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $trigger = $objects[$phid]; $id = $trigger->getID(); $handle->setName(pht('Trigger %d', $id)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/phid/PhabricatorWorkerBulkJobPHIDType.php
src/infrastructure/daemon/workers/phid/PhabricatorWorkerBulkJobPHIDType.php
<?php final class PhabricatorWorkerBulkJobPHIDType extends PhabricatorPHIDType { const TYPECONST = 'BULK'; public function getTypeName() { return pht('Bulk Job'); } public function newObject() { return new PhabricatorWorkerBulkJob(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorDaemonsApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorWorkerBulkJobQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $job = $objects[$phid]; $id = $job->getID(); $handle->setName(pht('Bulk Job %d', $id)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/clock/PhabricatorTriggerClock.php
src/infrastructure/daemon/workers/clock/PhabricatorTriggerClock.php
<?php /** * A trigger clock implements scheduling rules for an event. * * Two examples of triggered events are a subscription which bills on the 12th * of every month, or a meeting reminder which sends an email 15 minutes before * an event. A trigger clock contains the logic to figure out exactly when * those times are. * * For example, it might schedule an event every hour, or every Thursday, or on * the 15th of every month at 3PM, or only at a specific time. */ abstract class PhabricatorTriggerClock extends Phobject { private $properties; public function __construct(array $properties) { $this->validateProperties($properties); $this->properties = $properties; } public function getProperties() { return $this->properties; } public function getProperty($key, $default = null) { return idx($this->properties, $key, $default); } /** * Validate clock configuration. * * @param map<string, wild> Map of clock properties. * @return void */ abstract public function validateProperties(array $properties); /** * Get the next occurrence of this event. * * This method takes two parameters: the last time this event occurred (or * null if it has never triggered before) and a flag distinguishing between * a normal reschedule (after a successful trigger) or an update because of * a trigger change. * * If this event does not occur again, return `null` to stop it from being * rescheduled. For example, a meeting reminder may be sent only once before * the meeting. * * If this event does occur again, return the epoch timestamp of the next * occurrence. * * When performing routine reschedules, the event must move forward in time: * any timestamp you return must be later than the last event. For instance, * if this event triggers an invoice, the next invoice date must be after * the previous invoice date. This prevents an event from looping more than * once per second. * * In contrast, after an update (not a routine reschedule), the next event * may be scheduled at any time. For example, if a meeting is moved from next * week to 3 minutes from now, the clock may reschedule the notification to * occur 12 minutes ago. This will cause it to execute immediately. * * @param int|null Last time the event occurred, or null if it has never * triggered before. * @param bool True if this is a reschedule after a successful trigger. * @return int|null Next event, or null to decline to reschedule. */ abstract public function getNextEventEpoch($last_epoch, $is_reschedule); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/clock/PhabricatorSubscriptionTriggerClock.php
src/infrastructure/daemon/workers/clock/PhabricatorSubscriptionTriggerClock.php
<?php /** * Triggers an event every month on the same day of the month, like the 12th * of the month. * * If a given month does not have such a day (for instance, the clock triggers * on the 30th of each month and the month in question is February, which never * has a 30th day), it will trigger on the last day of the month instead. * * Choosing this strategy for subscriptions is predictable (it's easy to * anticipate when a subscription period will end) and fair (billing * periods always have nearly equal length). It also spreads subscriptions * out evenly. If there are issues with billing, this provides an opportunity * for them to be corrected after only a few customers are affected, instead of * (for example) having every subscription fail all at once on the 1st of the * month. */ final class PhabricatorSubscriptionTriggerClock extends PhabricatorTriggerClock { public function validateProperties(array $properties) { PhutilTypeSpec::checkMap( $properties, array( 'start' => 'int', )); } public function getNextEventEpoch($last_epoch, $is_reschedule) { $start_epoch = $this->getProperty('start'); if (!$last_epoch) { $last_epoch = $start_epoch; } // Constructing DateTime objects like this implies UTC, so we don't need // to set that explicitly. $start = new DateTime('@'.$start_epoch); $last = new DateTime('@'.$last_epoch); $year = (int)$last->format('Y'); $month = (int)$last->format('n'); // Note that we're getting the day of the month from the start date, not // from the last event date. This lets us schedule on March 31 after moving // the date back to Feb 28. $day = (int)$start->format('j'); // We trigger at the same time of day as the original event. Generally, // this means that you should get invoiced at a reasonable local time in // most cases, unless you subscribed at 1AM or something. $hms = $start->format('G:i:s'); // Increment the month by 1. $month = $month + 1; // If we ran off the end of the calendar, set the month back to January // and increment the year by 1. if ($month > 12) { $month = 1; $year = $year + 1; } // Now, move the day backward until it falls in the correct month. If we // pass an invalid date like "2014-2-31", it will internally be parsed // as though we had passed "2014-3-3". while (true) { $next = new DateTime("{$year}-{$month}-{$day} {$hms} UTC"); if ($next->format('n') == $month) { // The month didn't get corrected forward, so we're all set. break; } else { // The month did get corrected forward, so back off a day. $day--; } } return (int)$next->format('U'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/clock/PhabricatorNeverTriggerClock.php
src/infrastructure/daemon/workers/clock/PhabricatorNeverTriggerClock.php
<?php /** * Never triggers an event. * * This clock can be used for testing, or to cancel events. */ final class PhabricatorNeverTriggerClock extends PhabricatorTriggerClock { public function validateProperties(array $properties) { PhutilTypeSpec::checkMap( $properties, array()); } public function getNextEventEpoch($last_epoch, $is_reschedule) { return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/clock/PhabricatorOneTimeTriggerClock.php
src/infrastructure/daemon/workers/clock/PhabricatorOneTimeTriggerClock.php
<?php /** * Triggers an event exactly once, at a specific epoch time. */ final class PhabricatorOneTimeTriggerClock extends PhabricatorTriggerClock { public function validateProperties(array $properties) { PhutilTypeSpec::checkMap( $properties, array( 'epoch' => 'int', )); } public function getNextEventEpoch($last_epoch, $is_reschedule) { if ($last_epoch) { return null; } return $this->getProperty('epoch'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/clock/PhabricatorMetronomicTriggerClock.php
src/infrastructure/daemon/workers/clock/PhabricatorMetronomicTriggerClock.php
<?php /** * Triggers an event repeatedly, delaying a fixed number of seconds between * triggers. * * For example, this clock can trigger an event every 30 seconds. */ final class PhabricatorMetronomicTriggerClock extends PhabricatorTriggerClock { public function validateProperties(array $properties) { PhutilTypeSpec::checkMap( $properties, array( 'period' => 'int', )); } public function getNextEventEpoch($last_epoch, $is_reschedule) { $period = $this->getProperty('period'); if ($last_epoch) { $next = $last_epoch + $period; $next = max($next, $last_epoch + 1); } else { $next = PhabricatorTime::getNow() + $period; } return $next; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/clock/PhabricatorDailyRoutineTriggerClock.php
src/infrastructure/daemon/workers/clock/PhabricatorDailyRoutineTriggerClock.php
<?php /** * Triggers a daily routine, like server backups. * * This clock triggers events every 24 hours, using UTC. It does not use a * locale, and is intended for technical processes like backing up a server * every night. * * Because UTC does not have daylight savings, the local hour when this event * occurs will change over the course of the year. For example, from the * perspective of a user in California, it might run backups at 3AM in the * winter and 2AM in the summer. This is desirable for maintenance processes, * but problematic for some human processes. Use a different clock if you're * triggering a human-oriented event. * * The clock uses the time of day of the `start` epoch to calculate the time * of day of the next event, so you can change the time of day when the event * occurs by adjusting the `start` time of day. */ final class PhabricatorDailyRoutineTriggerClock extends PhabricatorTriggerClock { public function validateProperties(array $properties) { PhutilTypeSpec::checkMap( $properties, array( 'start' => 'int', )); } public function getNextEventEpoch($last_epoch, $is_reschedule) { $start_epoch = $this->getProperty('start'); if (!$last_epoch) { $last_epoch = $start_epoch; } $start = new DateTime('@'.$start_epoch); $last = new DateTime('@'.$last_epoch); // NOTE: We're choosing the date from the last event, but the time of day // from the start event. This allows callers to change when the event // occurs by updating the trigger's start parameter. $ymd = $last->format('Y-m-d'); $hms = $start->format('G:i:s'); $next = new DateTime("{$ymd} {$hms} UTC"); // Add a day. // NOTE: DateInterval doesn't exist until PHP 5.3.0, and we currently // target PHP 5.2.3. $next->modify('+1 day'); return (int)$next->format('U'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/workers/clock/__tests__/PhabricatorTriggerClockTestCase.php
src/infrastructure/daemon/workers/clock/__tests__/PhabricatorTriggerClockTestCase.php
<?php final class PhabricatorTriggerClockTestCase extends PhabricatorTestCase { public function testOneTimeTriggerClock() { $now = PhabricatorTime::getNow(); $clock = new PhabricatorOneTimeTriggerClock( array( 'epoch' => $now, )); $this->assertEqual( $now, $clock->getNextEventEpoch(null, false), pht('Should trigger at specified epoch.')); $this->assertEqual( null, $clock->getNextEventEpoch(1, false), pht('Should trigger only once.')); } public function testNeverTriggerClock() { $clock = new PhabricatorNeverTriggerClock(array()); $this->assertEqual( null, $clock->getNextEventEpoch(null, false), pht('Should never trigger.')); } public function testDailyRoutineTriggerClockDaylightSavings() { // These dates are selected to cross daylight savings in PST; they should // be unaffected. $start = strtotime('2015-03-05 16:17:18 UTC'); $clock = new PhabricatorDailyRoutineTriggerClock( array( 'start' => $start, )); $expect_list = array( '2015-03-06 16:17:18', '2015-03-07 16:17:18', '2015-03-08 16:17:18', '2015-03-09 16:17:18', '2015-03-10 16:17:18', ); $this->expectClock($clock, $expect_list, pht('Daily Routine (PST)')); } public function testDailyRoutineTriggerClockLeapSecond() { // These dates cross the leap second on June 30, 2012. There has never // been a negative leap second, so we can't test that yet. $start = strtotime('2012-06-28 23:59:59 UTC'); $clock = new PhabricatorDailyRoutineTriggerClock( array( 'start' => $start, )); $expect_list = array( '2012-06-29 23:59:59', '2012-06-30 23:59:59', '2012-07-01 23:59:59', '2012-07-02 23:59:59', ); $this->expectClock($clock, $expect_list, pht('Daily Routine (Leap)')); } public function testCDailyRoutineTriggerClockAdjustTimeOfDay() { // In this case, we're going to update the time of day on the clock and // make sure it keeps track of the date but adjusts the time. $start = strtotime('2015-01-15 6:07:08 UTC'); $clock = new PhabricatorDailyRoutineTriggerClock( array( 'start' => $start, )); $expect_list = array( '2015-01-16 6:07:08', '2015-01-17 6:07:08', '2015-01-18 6:07:08', ); $last_epoch = $this->expectClock( $clock, $expect_list, pht('Daily Routine (Pre-Adjust)')); // Now, change the time of day. $new_start = strtotime('2015-01-08 1:23:45 UTC'); $clock = new PhabricatorDailyRoutineTriggerClock( array( 'start' => $new_start, )); $expect_list = array( '2015-01-19 1:23:45', '2015-01-20 1:23:45', '2015-01-21 1:23:45', ); $this->expectClock( $clock, $expect_list, pht('Daily Routine (Post-Adjust)'), $last_epoch); } public function testSubscriptionTriggerClock() { $start = strtotime('2014-01-31 2:34:56 UTC'); $clock = new PhabricatorSubscriptionTriggerClock( array( 'start' => $start, )); $expect_list = array( // This should be moved to the 28th of February. '2014-02-28 2:34:56', // In March, which has 31 days, it should move back to the 31st. '2014-03-31 2:34:56', // On months with only 30 days, it should occur on the 30th. '2014-04-30 2:34:56', '2014-05-31 2:34:56', '2014-06-30 2:34:56', '2014-07-31 2:34:56', '2014-08-31 2:34:56', '2014-09-30 2:34:56', '2014-10-31 2:34:56', '2014-11-30 2:34:56', '2014-12-31 2:34:56', // After billing on Dec 31 2014, it should wrap around to Jan 31 2015. '2015-01-31 2:34:56', '2015-02-28 2:34:56', '2015-03-31 2:34:56', '2015-04-30 2:34:56', '2015-05-31 2:34:56', '2015-06-30 2:34:56', '2015-07-31 2:34:56', '2015-08-31 2:34:56', '2015-09-30 2:34:56', '2015-10-31 2:34:56', '2015-11-30 2:34:56', '2015-12-31 2:34:56', '2016-01-31 2:34:56', // Finally, this should bill on leap day in 2016. '2016-02-29 2:34:56', '2016-03-31 2:34:56', ); $this->expectClock($clock, $expect_list, pht('Billing Cycle')); } private function expectClock( PhabricatorTriggerClock $clock, array $expect_list, $clock_name, $last_epoch = null) { foreach ($expect_list as $cycle => $expect) { $next_epoch = $clock->getNextEventEpoch( $last_epoch, ($last_epoch !== null)); $this->assertEqual( $expect, id(new DateTime('@'.$next_epoch))->format('Y-m-d G:i:s'), pht('%s (%s)', $clock_name, $cycle)); $last_epoch = $next_epoch; } return $last_epoch; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/contentsource/PhabricatorDaemonContentSource.php
src/infrastructure/daemon/contentsource/PhabricatorDaemonContentSource.php
<?php final class PhabricatorDaemonContentSource extends PhabricatorContentSource { const SOURCECONST = 'daemon'; public function getSourceName() { return pht('Daemon'); } public function getSourceDescription() { return pht('Updates from background processing in daemons.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/contentsource/PhabricatorBulkContentSource.php
src/infrastructure/daemon/contentsource/PhabricatorBulkContentSource.php
<?php final class PhabricatorBulkContentSource extends PhabricatorContentSource { const SOURCECONST = 'bulk'; public function getSourceName() { return pht('Bulk Update'); } public function getSourceDescription() { return pht('Changes made by bulk update.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/overseer/PhabricatorDaemonOverseerModule.php
src/infrastructure/daemon/overseer/PhabricatorDaemonOverseerModule.php
<?php /** * Overseer module. * * The primary purpose of this overseer module is to poll for configuration * changes and reload daemons when the configuration changes. */ final class PhabricatorDaemonOverseerModule extends PhutilDaemonOverseerModule { private $configVersion; public function shouldReloadDaemons() { if ($this->shouldThrottle('reload', 10)) { return false; } return $this->updateConfigVersion(); } /** * Calculate a version number for the current Phabricator configuration. * * The version number has no real meaning and does not provide any real * indication of whether a configuration entry has been changed. The config * version is intended to be a rough indicator that "something has changed", * which indicates to the overseer that the daemons should be reloaded. * * @return int */ private function loadConfigVersion() { $conn_r = id(new PhabricatorConfigEntry())->establishConnection('r'); return head(queryfx_one( $conn_r, 'SELECT MAX(id) FROM %T', id(new PhabricatorConfigTransaction())->getTableName())); } /** * Check and update the configuration version. * * @return bool True if the daemons should restart, otherwise false. */ private function updateConfigVersion() { $old_version = $this->configVersion; $new_version = $this->loadConfigVersion(); $this->configVersion = $new_version; // Don't trigger a reload if we're loading the config for the very // first time. if ($old_version === null) { return false; } return ($old_version != $new_version); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php
src/infrastructure/daemon/garbagecollector/PhabricatorGarbageCollector.php
<?php /** * @task info Getting Collector Information * @task collect Collecting Garbage */ abstract class PhabricatorGarbageCollector extends Phobject { /* -( Getting Collector Information )-------------------------------------- */ /** * Get a human readable name for what this collector cleans up, like * "User Activity Logs". * * @return string Human-readable collector name. * @task info */ abstract public function getCollectorName(); /** * Specify that the collector has an automatic retention policy and * is not configurable. * * @return bool True if the collector has an automatic retention policy. * @task info */ public function hasAutomaticPolicy() { return false; } /** * Get the default retention policy for this collector. * * Return the age (in seconds) when resources start getting collected, or * `null` to retain resources indefinitely. * * @return int|null Lifetime, or `null` for indefinite retention. * @task info */ public function getDefaultRetentionPolicy() { throw new PhutilMethodNotImplementedException(); } /** * Get the effective retention policy. * * @return int|null Lifetime, or `null` for indefinite retention. * @task info */ public function getRetentionPolicy() { if ($this->hasAutomaticPolicy()) { throw new Exception( pht( 'Can not get retention policy of collector with automatic '. 'policy.')); } $config = PhabricatorEnv::getEnvConfig('phd.garbage-collection'); $const = $this->getCollectorConstant(); return idx($config, $const, $this->getDefaultRetentionPolicy()); } /** * Get a unique string constant identifying this collector. * * @return string Collector constant. * @task info */ final public function getCollectorConstant() { return $this->getPhobjectClassConstant('COLLECTORCONST', 64); } /* -( Collecting Garbage )------------------------------------------------- */ /** * Run the collector. * * @return bool True if there is more garbage to collect. * @task collect */ final public function runCollector() { // Don't do anything if this collector is configured with an indefinite // retention policy. if (!$this->hasAutomaticPolicy()) { $policy = $this->getRetentionPolicy(); if (!$policy) { return false; } } // Hold a lock while performing collection to avoid racing other daemons // running the same collectors. $params = array( 'collector' => $this->getCollectorConstant(), ); $lock = PhabricatorGlobalLock::newLock('gc', $params); try { $lock->lock(5); } catch (PhutilLockException $ex) { return false; } try { $result = $this->collectGarbage(); } catch (Exception $ex) { $lock->unlock(); throw $ex; } $lock->unlock(); return $result; } /** * Collect garbage from whatever source this GC handles. * * @return bool True if there is more garbage to collect. * @task collect */ abstract protected function collectGarbage(); /** * Get the most recent epoch timestamp that is considered garbage. * * Records older than this should be collected. * * @return int Most recent garbage timestamp. * @task collect */ final protected function getGarbageEpoch() { if ($this->hasAutomaticPolicy()) { throw new Exception( pht( 'Can not get garbage epoch for a collector with an automatic '. 'collection policy.')); } $ttl = $this->getRetentionPolicy(); if (!$ttl) { throw new Exception( pht( 'Can not get garbage epoch for a collector with an indefinite '. 'retention policy.')); } return (PhabricatorTime::getNow() - $ttl); } /** * Load all of the available garbage collectors. * * @return list<PhabricatorGarbageCollector> Garbage collectors. * @task collect */ final public static function getAllCollectors() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getCollectorConstant') ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementCollectWorkflow.php
src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementCollectWorkflow.php
<?php final class PhabricatorGarbageCollectorManagementCollectWorkflow extends PhabricatorGarbageCollectorManagementWorkflow { protected function didConstruct() { $this ->setName('collect') ->setExamples('**collect** --collector __collector__') ->setSynopsis( pht('Run a garbage collector in the foreground.')) ->setArguments( array( array( 'name' => 'collector', 'param' => 'const', 'help' => pht( 'Constant identifying the garbage collector to run.'), ), )); } public function execute(PhutilArgumentParser $args) { $collector = $this->getCollector($args->getArg('collector')); echo tsprintf( "%s\n", pht('Collecting "%s" garbage...', $collector->getCollectorName())); $any = false; while (true) { $more = $collector->runCollector(); if ($more) { $any = true; } else { break; } } if ($any) { $message = pht('Finished collecting all the garbage.'); } else { $message = pht('Could not find any garbage to collect.'); } echo tsprintf("\n%s\n", $message); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementSetPolicyWorkflow.php
src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementSetPolicyWorkflow.php
<?php final class PhabricatorGarbageCollectorManagementSetPolicyWorkflow extends PhabricatorGarbageCollectorManagementWorkflow { protected function didConstruct() { $this ->setName('set-policy') ->setExamples( "**set-policy** --collector __collector__ --days 30\n". "**set-policy** --collector __collector__ --indefinite\n". "**set-policy** --collector __collector__ --default") ->setSynopsis( pht( 'Change retention policies for a garbage collector.')) ->setArguments( array( array( 'name' => 'collector', 'param' => 'const', 'help' => pht( 'Constant identifying the garbage collector.'), ), array( 'name' => 'indefinite', 'help' => pht( 'Set an indefinite retention policy.'), ), array( 'name' => 'default', 'help' => pht( 'Use the default retention policy.'), ), array( 'name' => 'days', 'param' => 'count', 'help' => pht( 'Retain data for the specified number of days.'), ), )); } public function execute(PhutilArgumentParser $args) { $config_key = 'phd.garbage-collection'; $collector = $this->getCollector($args->getArg('collector')); $days = $args->getArg('days'); $indefinite = $args->getArg('indefinite'); $default = $args->getArg('default'); $count = 0; if ($days !== null) { $count++; } if ($indefinite) { $count++; } if ($default) { $count++; } if (!$count) { throw new PhutilArgumentUsageException( pht( 'Choose a policy with "%s", "%s" or "%s".', '--days', '--indefinite', '--default')); } if ($count > 1) { throw new PhutilArgumentUsageException( pht( 'Options "%s", "%s" and "%s" represent mutually exclusive ways '. 'to choose a policy. Specify only one.', '--days', '--indefinite', '--default')); } if ($days !== null) { $days = (int)$days; if ($days < 1) { throw new PhutilArgumentUsageException( pht( 'Specify a positive number of days to retain data for.')); } } $collector_const = $collector->getCollectorConstant(); $value = PhabricatorEnv::getEnvConfig($config_key); if ($days !== null) { echo tsprintf( "%s\n", pht( 'Setting retention policy for "%s" to %s day(s).', $collector->getCollectorName(), new PhutilNumber($days))); $value[$collector_const] = phutil_units($days.' days in seconds'); } else if ($indefinite) { echo tsprintf( "%s\n", pht( 'Setting "%s" to be retained indefinitely.', $collector->getCollectorName())); $value[$collector_const] = null; } else { echo tsprintf( "%s\n", pht( 'Restoring "%s" to the default retention policy.', $collector->getCollectorName())); unset($value[$collector_const]); } id(new PhabricatorConfigLocalSource()) ->setKeys( array( $config_key => $value, )); echo tsprintf( "%s\n", pht( 'Wrote new policy to local configuration.')); echo tsprintf( "%s\n", pht( 'This change will take effect the next time the daemons are '. 'restarted.')); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementCompactEdgesWorkflow.php
src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementCompactEdgesWorkflow.php
<?php final class PhabricatorGarbageCollectorManagementCompactEdgesWorkflow extends PhabricatorGarbageCollectorManagementWorkflow { protected function didConstruct() { $this ->setName('compact-edges') ->setExamples('**compact-edges**') ->setSynopsis( pht( 'Rebuild old edge transactions storage to use a more compact '. 'format.')) ->setArguments(array()); } public function execute(PhutilArgumentParser $args) { $tables = id(new PhutilClassMapQuery()) ->setAncestorClass('PhabricatorApplicationTransaction') ->execute(); foreach ($tables as $table) { $this->compactEdges($table); } return 0; } private function compactEdges(PhabricatorApplicationTransaction $table) { $conn = $table->establishConnection('w'); $class = get_class($table); echo tsprintf( "%s\n", pht( 'Rebuilding transactions for "%s"...', $class)); $cursor = 0; $updated = 0; while (true) { $rows = $table->loadAllWhere( 'transactionType = %s AND id > %d AND (oldValue LIKE %> OR newValue LIKE %>) ORDER BY id ASC LIMIT 100', PhabricatorTransactions::TYPE_EDGE, $cursor, // We're looking for transactions with JSON objects in their value // fields: the new style transactions have JSON lists instead and // start with "[" rather than "{". '{', '{'); if (!$rows) { break; } foreach ($rows as $row) { $id = $row->getID(); $old = $row->getOldValue(); $new = $row->getNewValue(); if (!is_array($old) || !is_array($new)) { echo tsprintf( "%s\n", pht( 'Transaction %s (of type %s) has unexpected data, skipping.', $id, $class)); } $record = PhabricatorEdgeChangeRecord::newFromTransaction($row); $old_data = $record->getModernOldEdgeTransactionData(); $old_json = phutil_json_encode($old_data); $new_data = $record->getModernNewEdgeTransactionData(); $new_json = phutil_json_encode($new_data); queryfx( $conn, 'UPDATE %T SET oldValue = %s, newValue = %s WHERE id = %d', $table->getTableName(), $old_json, $new_json, $id); $updated++; $cursor = $row->getID(); } } echo tsprintf( "%s\n", pht( 'Done, compacted %s edge transactions.', new PhutilNumber($updated))); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementWorkflow.php
src/infrastructure/daemon/garbagecollector/management/PhabricatorGarbageCollectorManagementWorkflow.php
<?php abstract class PhabricatorGarbageCollectorManagementWorkflow extends PhabricatorManagementWorkflow { protected function getCollector($const) { $collectors = PhabricatorGarbageCollector::getAllCollectors(); $collector_list = array_keys($collectors); sort($collector_list); $collector_list = implode(', ', $collector_list); if (!$const) { throw new PhutilArgumentUsageException( pht( 'Specify a collector with "%s". Valid collectors are: %s.', '--collector', $collector_list)); } if (empty($collectors[$const])) { throw new PhutilArgumentUsageException( pht( 'No such collector "%s". Choose a valid collector: %s.', $const, $collector_list)); } return $collectors[$const]; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/daemon/control/PhabricatorDaemonReference.php
src/infrastructure/daemon/control/PhabricatorDaemonReference.php
<?php // TODO: See T13321. After the removal of daemon PID files this class // no longer makes as much sense as it once did. final class PhabricatorDaemonReference extends Phobject { public static function isProcessRunning($pid) { if (!$pid) { return false; } if (function_exists('posix_kill')) { // This may fail if we can't signal the process because we are running as // a different user (for example, we are 'apache' and the process is some // other user's, or we are a normal user and the process is root's), but // we can check the error code to figure out if the process exists. $is_running = posix_kill($pid, 0); if (posix_get_last_error() == 1) { // "Operation Not Permitted", indicates that the PID exists. If it // doesn't, we'll get an error 3 ("No such process") instead. $is_running = true; } } else { // If we don't have the posix extension, just exec. list($err) = exec_manual('ps %s', $pid); $is_running = ($err == 0); } return $is_running; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/javelin/markup.php
src/infrastructure/javelin/markup.php
<?php function javelin_tag( $tag, array $attributes = array(), $content = null) { if (isset($attributes['sigil']) || isset($attributes['meta']) || isset($attributes['mustcapture'])) { foreach ($attributes as $k => $v) { switch ($k) { case 'sigil': if ($v !== null) { $attributes['data-sigil'] = $v; } unset($attributes[$k]); break; case 'meta': if ($v !== null) { $response = CelerityAPI::getStaticResourceResponse(); $id = $response->addMetadata($v); $attributes['data-meta'] = $id; } unset($attributes[$k]); break; case 'mustcapture': if ($v) { $attributes['data-mustcapture'] = '1'; } else { unset($attributes['data-mustcapture']); } unset($attributes[$k]); break; } } } if (isset($attributes['aural'])) { if ($attributes['aural']) { $class = idx($attributes, 'class', ''); $class = rtrim('aural-only '.$class); $attributes['class'] = $class; } else { $class = idx($attributes, 'class', ''); $class = rtrim('visual-only '.$class); $attributes['class'] = $class; $attributes['aria-hidden'] = 'true'; } unset($attributes['aural']); } if (isset($attributes['print'])) { if ($attributes['print']) { $class = idx($attributes, 'class', ''); $class = rtrim('print-only '.$class); $attributes['class'] = $class; // NOTE: Alternative print content is hidden from screen readers. $attributes['aria-hidden'] = 'true'; } else { $class = idx($attributes, 'class', ''); $class = rtrim('screen-only '.$class); $attributes['class'] = $class; } unset($attributes['print']); } return phutil_tag($tag, $attributes, $content); } function phabricator_form(PhabricatorUser $user, $attributes, $content) { $body = array(); $http_method = idx($attributes, 'method'); $is_post = (strcasecmp($http_method, 'POST') === 0); $http_action = idx($attributes, 'action'); $is_absolute_uri = false; if ($http_action != null) { $is_absolute_uri = preg_match('#^(https?:|//)#', $http_action); } if ($is_post) { // NOTE: We only include CSRF tokens if a URI is a local URI on the same // domain. This is an important security feature and prevents forms which // submit to foreign sites from leaking CSRF tokens. // In some cases, we may construct a fully-qualified local URI. For example, // we can construct these for download links, depending on configuration. // These forms do not receive CSRF tokens, even though they safely could. // This can be confusing, if you're developing for Phabricator and // manage to construct a local form with a fully-qualified URI, since it // won't get CSRF tokens and you'll get an exception at the other end of // the request which is a bit disconnected from the actual root cause. // However, this is rare, and there are reasonable cases where this // construction occurs legitimately, and the simplest fix is to omit CSRF // tokens for these URIs in all cases. The error message you receive also // gives you some hints as to this potential source of error. if (!$is_absolute_uri) { $body[] = phutil_tag( 'input', array( 'type' => 'hidden', 'name' => AphrontRequest::getCSRFTokenName(), 'value' => $user->getCSRFToken(), )); $body[] = phutil_tag( 'input', array( 'type' => 'hidden', 'name' => '__form__', 'value' => true, )); // If the profiler was active for this request, keep it active for any // forms submitted from this page. if (DarkConsoleXHProfPluginAPI::isProfilerRequested()) { $body[] = phutil_tag( 'input', array( 'type' => 'hidden', 'name' => '__profile__', 'value' => true, )); } } } if (is_array($content)) { $body = array_merge($body, $content); } else { $body[] = $content; } return javelin_tag('form', $attributes, $body); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/javelin/Javelin.php
src/infrastructure/javelin/Javelin.php
<?php final class Javelin extends Phobject { public static function initBehavior( $behavior, array $config = array(), $source_name = 'phabricator') { $response = CelerityAPI::getStaticResourceResponse(); $response->initBehavior($behavior, $config, $source_name); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/parser/PhutilPygmentizeParser.php
src/infrastructure/parser/PhutilPygmentizeParser.php
<?php /** * Parser that converts `pygmetize` output or similar HTML blocks from "class" * attributes to "style" attributes. */ final class PhutilPygmentizeParser extends Phobject { private $map = array(); public function setMap(array $map) { $this->map = $map; return $this; } public function getMap() { return $this->map; } public function parse($block) { $class_look = 'class="'; $class_len = strlen($class_look); $class_start = null; $map = $this->map; $len = strlen($block); $out = ''; $mode = 'text'; for ($ii = 0; $ii < $len; $ii++) { $c = $block[$ii]; switch ($mode) { case 'text': // We're in general text between tags, and just passing characers // through unmodified. if ($c == '<') { $mode = 'tag'; } $out .= $c; break; case 'tag': // We're inside a tag, and looking for `class="` so we can rewrite // it. if ($c == '>') { $mode = 'text'; } if ($c == 'c') { if (!substr_compare($block, $class_look, $ii, $class_len)) { $mode = 'class'; $ii += $class_len; $class_start = $ii; } } if ($mode != 'class') { $out .= $c; } break; case 'class': // We're inside a `class="..."` tag, and looking for the ending quote // so we can replace it. if ($c == '"') { $class = substr($block, $class_start, $ii - $class_start); // If this class is present in the map, rewrite it into an inline // style attribute. if (isset($map[$class])) { $out .= 'style="'.phutil_escape_html($map[$class]).'"'; } else { $out .= 'class="'.$class.'"'; } $mode = 'tag'; } break; } } return $out; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/parser/__tests__/PhutilPygmentizeParserTestCase.php
src/infrastructure/parser/__tests__/PhutilPygmentizeParserTestCase.php
<?php final class PhutilPygmentizeParserTestCase extends PhutilTestCase { public function testPygmentizeParser() { $this->tryParser( '', '', array(), pht('Empty')); $this->tryParser( '<span class="mi">1</span>', '<span style="color: #ff0000">1</span>', array( 'mi' => 'color: #ff0000', ), pht('Simple')); $this->tryParser( '<span class="mi">1</span>', '<span class="mi">1</span>', array(), pht('Missing Class')); $this->tryParser( '<span data-symbol-name="X" class="nc">X</span>', '<span data-symbol-name="X" style="color: #ff0000">X</span>', array( 'nc' => 'color: #ff0000', ), pht('Extra Attribute')); } private function tryParser($input, $expect, array $map, $label) { $actual = id(new PhutilPygmentizeParser()) ->setMap($map) ->parse($input); $this->assertEqual($expect, $actual, pht('Pygmentize Parser: %s', $label)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/render.php
src/infrastructure/markup/render.php
<?php /** * Render an HTML tag in a way that treats user content as unsafe by default. * * Tag rendering has some special logic which implements security features: * * - When rendering `<a>` tags, if the `rel` attribute is not specified, it * is interpreted as `rel="noreferrer"`. * - When rendering `<a>` tags, the `href` attribute may not begin with * `javascript:`. * * These special cases can not be disabled. * * IMPORTANT: The `$tag` attribute and the keys of the `$attributes` array are * trusted blindly, and not escaped. You should not pass user data in these * parameters. * * @param string The name of the tag, like `a` or `div`. * @param map<string, string> A map of tag attributes. * @param wild Content to put in the tag. * @return PhutilSafeHTML Tag object. */ function phutil_tag($tag, array $attributes = array(), $content = null) { // If the `href` attribute is present, make sure it is not a "javascript:" // URI. We never permit these. if (!empty($attributes['href'])) { // This might be a URI object, so cast it to a string. $href = (string)$attributes['href']; if (isset($href[0])) { // Block 'javascript:' hrefs at the tag level: no well-designed // application should ever use them, and they are a potent attack vector. // This function is deep in the core and performance sensitive, so we're // doing a cheap version of this test first to avoid calling preg_match() // on URIs which begin with '/' or `#`. These cover essentially all URIs // in Phabricator. if (($href[0] !== '/') && ($href[0] !== '#')) { // Chrome 33 and IE 11 both interpret "javascript\n:" as a Javascript // URI, and all browsers interpret " javascript:" as a Javascript URI, // so be aggressive about looking for "javascript:" in the initial // section of the string. $normalized_href = preg_replace('([^a-z0-9/:]+)i', '', $href); if (preg_match('/^javascript:/i', $normalized_href)) { throw new Exception( pht( "Attempting to render a tag with an '%s' attribute that begins ". "with '%s'. This is either a serious security concern or a ". "serious architecture concern. Seek urgent remedy.", 'href', 'javascript:')); } } } } // For tags which can't self-close, treat null as the empty string -- for // example, always render `<div></div>`, never `<div />`. static $self_closing_tags = array( 'area' => true, 'base' => true, 'br' => true, 'col' => true, 'command' => true, 'embed' => true, 'frame' => true, 'hr' => true, 'img' => true, 'input' => true, 'keygen' => true, 'link' => true, 'meta' => true, 'param' => true, 'source' => true, 'track' => true, 'wbr' => true, ); $attr_string = ''; foreach ($attributes as $k => $v) { if ($v === null) { continue; } $v = phutil_escape_html($v); $attr_string .= ' '.$k.'="'.$v.'"'; } if ($content === null) { if (isset($self_closing_tags[$tag])) { return new PhutilSafeHTML('<'.$tag.$attr_string.' />'); } else { $content = ''; } } else { $content = phutil_escape_html($content); } return new PhutilSafeHTML('<'.$tag.$attr_string.'>'.$content.'</'.$tag.'>'); } function phutil_tag_div($class, $content = null) { return phutil_tag('div', array('class' => $class), $content); } function phutil_escape_html($string) { if ($string === null) { return ''; } if ($string instanceof PhutilSafeHTML) { return $string; } else if ($string instanceof PhutilSafeHTMLProducerInterface) { $result = $string->producePhutilSafeHTML(); if ($result instanceof PhutilSafeHTML) { return phutil_escape_html($result); } else if (is_array($result)) { return phutil_escape_html($result); } else if ($result instanceof PhutilSafeHTMLProducerInterface) { return phutil_escape_html($result); } else { try { assert_stringlike($result); return phutil_escape_html((string)$result); } catch (Exception $ex) { throw new Exception( pht( "Object (of class '%s') implements %s but did not return anything ". "renderable from %s.", get_class($string), 'PhutilSafeHTMLProducerInterface', 'producePhutilSafeHTML()')); } } } else if (is_array($string)) { $result = ''; foreach ($string as $item) { $result .= phutil_escape_html($item); } return $result; } return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); } function phutil_escape_html_newlines($string) { return PhutilSafeHTML::applyFunction('nl2br', $string); } /** * Mark string as safe for use in HTML. */ function phutil_safe_html($string) { if ($string == '') { return $string; } else if ($string instanceof PhutilSafeHTML) { return $string; } else { return new PhutilSafeHTML($string); } } /** * HTML safe version of `implode()`. */ function phutil_implode_html($glue, array $pieces) { $glue = phutil_escape_html($glue); foreach ($pieces as $k => $piece) { $pieces[$k] = phutil_escape_html($piece); } return phutil_safe_html(implode($glue, $pieces)); } /** * Format a HTML code. This function behaves like `sprintf()`, except that all * the normal conversions (like %s) will be properly escaped. */ function hsprintf($html /* , ... */) { $args = func_get_args(); array_shift($args); return new PhutilSafeHTML( vsprintf($html, array_map('phutil_escape_html', $args))); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhutilRemarkupBlockStorage.php
src/infrastructure/markup/PhutilRemarkupBlockStorage.php
<?php /** * Remarkup prevents several classes of text-processing problems by replacing * tokens in the text as they are marked up. For example, if you write something * like this: * * //D12// * * It is processed in several stages. First the "D12" matches and is replaced * with a token, in the form of "<0x01><ID number><literal "Z">". The first * byte, "<0x01>" is a single byte with value 1 that marks a token. If this is * token ID "444", the text may now look like this: * * //<0x01>444Z// * * Now the italics match and are replaced, using the next token ID: * * <0x01>445Z * * When processing completes, all the tokens are replaced with their final * equivalents. For example, token 444 is evaluated to: * * <a href="http://...">...</a> * * Then token 445 is evaluated: * * <em><0x01>444Z</em> * * ...and all tokens it contains are replaced: * * <em><a href="http://...">...</a></em> * * If we didn't do this, the italics rule could match the "//" in "http://", * or any other number of processing mistakes could occur, some of which create * security risks. * * This class generates keys, and stores the map of keys to replacement text. */ final class PhutilRemarkupBlockStorage extends Phobject { const MAGIC_BYTE = "\1"; private $map = array(); private $index = 0; public function store($text) { $key = self::MAGIC_BYTE.(++$this->index).'Z'; $this->map[$key] = $text; return $key; } public function restore($corpus, $text_mode = false) { $map = $this->map; if (!$text_mode) { foreach ($map as $key => $content) { $map[$key] = phutil_escape_html($content); } $corpus = phutil_escape_html($corpus); } // NOTE: Tokens may contain other tokens: for example, a table may have // links inside it. So we can't do a single simple find/replace, because // we need to find and replace child tokens inside the content of parent // tokens. // However, we know that rules which have child tokens must always store // all their child tokens first, before they store their parent token: you // have to pass the "store(text)" API a block of text with tokens already // in it, so you must have created child tokens already. // Thus, all child tokens will appear in the list before parent tokens, so // if we start at the beginning of the list and replace all the tokens we // find in each piece of content, we'll end up expanding all subtokens // correctly. $map[] = $corpus; $seen = array(); foreach ($map as $key => $content) { $seen[$key] = true; // If the content contains no token magic, we don't need to replace // anything. if (strpos($content, self::MAGIC_BYTE) === false) { continue; } $matches = null; preg_match_all( '/'.self::MAGIC_BYTE.'\d+Z/', $content, $matches, PREG_OFFSET_CAPTURE); $matches = $matches[0]; // See PHI1114. We're replacing all the matches in one pass because this // is significantly faster than doing "substr_replace()" in a loop if the // corpus is large and we have a large number of matches. // Build a list of string pieces in "$parts" by interleaving the // plain strings between each token and the replacement token text, then // implode the whole thing when we're done. $parts = array(); $pos = 0; foreach ($matches as $next) { $subkey = $next[0]; // If we've matched a token pattern but don't actually have any // corresponding token, just skip this match. This should not be // possible, and should perhaps be an error. if (!isset($seen[$subkey])) { if (!isset($map[$subkey])) { throw new Exception( pht( 'Matched token key "%s" while processing remarkup block, but '. 'this token does not exist in the token map.', $subkey)); } else { throw new Exception( pht( 'Matched token key "%s" while processing remarkup block, but '. 'this token appears later in the list than the key being '. 'processed ("%s").', $subkey, $key)); } } $subpos = $next[1]; // If there were any non-token bytes since the last token, add them. if ($subpos > $pos) { $parts[] = substr($content, $pos, $subpos - $pos); } // Add the token replacement text. $parts[] = $map[$subkey]; // Move the non-token cursor forward over the token. $pos = $subpos + strlen($subkey); } // Add any leftover non-token bytes after the last token. $parts[] = substr($content, $pos); $content = implode('', $parts); $map[$key] = $content; } $corpus = last($map); if (!$text_mode) { $corpus = phutil_safe_html($corpus); } return $corpus; } public function overwrite($key, $new_text) { $this->map[$key] = $new_text; return $this; } public function getMap() { return $this->map; } public function setMap(array $map) { $this->map = $map; return $this; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhabricatorMarkupOneOff.php
src/infrastructure/markup/PhabricatorMarkupOneOff.php
<?php /** * DEPRECATED. Use @{class:PHUIRemarkupView}. */ final class PhabricatorMarkupOneOff extends Phobject implements PhabricatorMarkupInterface { private $content; private $preserveLinebreaks; private $engineRuleset; private $engine; private $disableCache; private $contentCacheFragment; private $generateTableOfContents; private $tableOfContents; public function setEngineRuleset($engine_ruleset) { $this->engineRuleset = $engine_ruleset; return $this; } public function getEngineRuleset() { return $this->engineRuleset; } public function setPreserveLinebreaks($preserve_linebreaks) { $this->preserveLinebreaks = $preserve_linebreaks; return $this; } public function setContent($content) { $this->content = $content; return $this; } public function getContent() { return $this->content; } public function setEngine(PhutilMarkupEngine $engine) { $this->engine = $engine; return $this; } public function getEngine() { return $this->engine; } public function setDisableCache($disable_cache) { $this->disableCache = $disable_cache; return $this; } public function getDisableCache() { return $this->disableCache; } public function setGenerateTableOfContents($generate) { $this->generateTableOfContents = $generate; return $this; } public function getGenerateTableOfContents() { return $this->generateTableOfContents; } public function getTableOfContents() { return $this->tableOfContents; } public function setContentCacheFragment($fragment) { $this->contentCacheFragment = $fragment; return $this; } public function getContentCacheFragment() { return $this->contentCacheFragment; } public function getMarkupFieldKey($field) { $fragment = $this->getContentCacheFragment(); if ($fragment !== null) { return $fragment; } return PhabricatorHash::digestForIndex($this->getContent()).':oneoff'; } public function newMarkupEngine($field) { if ($this->engine) { return $this->engine; } if ($this->engineRuleset) { return PhabricatorMarkupEngine::getEngine($this->engineRuleset); } else if ($this->preserveLinebreaks) { return PhabricatorMarkupEngine::getEngine(); } else { return PhabricatorMarkupEngine::getEngine('nolinebreaks'); } } public function getMarkupText($field) { return $this->getContent(); } public function didMarkupText( $field, $output, PhutilMarkupEngine $engine) { if ($this->getGenerateTableOfContents()) { $toc = PhutilRemarkupHeaderBlockRule::renderTableOfContents($engine); $this->tableOfContents = $toc; } require_celerity_resource('phabricator-remarkup-css'); return phutil_tag( 'div', array( 'class' => 'phabricator-remarkup', ), $output); } public function shouldUseMarkupCache($field) { if ($this->getDisableCache()) { return false; } return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhutilSafeHTMLProducerInterface.php
src/infrastructure/markup/PhutilSafeHTMLProducerInterface.php
<?php /** * Implement this interface to mark an object as capable of producing a * PhutilSafeHTML representation. This is primarily useful for building * renderable HTML views. */ interface PhutilSafeHTMLProducerInterface { public function producePhutilSafeHTML(); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhabricatorMarkupInterface.php
src/infrastructure/markup/PhabricatorMarkupInterface.php
<?php /** * An object which has one or more fields containing markup that can be * rendered into a display format. Commonly, the fields contain Remarkup and * are rendered into HTML. Implementing this interface allows you to render * objects through @{class:PhabricatorMarkupEngine} and benefit from caching * and pipelining infrastructure. * * An object may have several "fields" of markup. For example, Differential * revisions have a "summary" and a "test plan". In these cases, the `$field` * parameter is used to identify which field is being operated on. For simple * objects like comments, you might only have one field (say, "body"). In * these cases, the implementation can largely ignore the `$field` parameter. * * @task markup Markup Interface */ interface PhabricatorMarkupInterface { /* -( Markup Interface )--------------------------------------------------- */ /** * Get a key to identify this field. This should uniquely identify the block * of text to be rendered and be usable as a cache key. If the object has a * PHID, using the PHID and the field name is likely reasonable: * * "{$phid}:{$field}" * * @param string Field name. * @return string Cache key up to 125 characters. * * @task markup */ public function getMarkupFieldKey($field); /** * Build the engine the field should use. * * @param string Field name. * @return PhutilRemarkupEngine Markup engine to use. * @task markup */ public function newMarkupEngine($field); /** * Return the contents of the specified field. * * @param string Field name. * @return string The raw markup contained in the field. * @task markup */ public function getMarkupText($field); /** * Callback for final postprocessing of output. Normally, you can return * the output unmodified. * * @param string Field name. * @param string The finalized output of the engine. * @param string The engine which generated the output. * @return string Final output. * @task markup */ public function didMarkupText( $field, $output, PhutilMarkupEngine $engine); /** * Determine if the engine should try to use the markup cache or not. * Generally you should use the cache for durable/permanent content but * should not use the cache for temporary/draft content. * * @return bool True to use the markup cache. * @task markup */ public function shouldUseMarkupCache($field); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhabricatorSyntaxHighlighter.php
src/infrastructure/markup/PhabricatorSyntaxHighlighter.php
<?php final class PhabricatorSyntaxHighlighter extends Phobject { public static function newEngine() { $engine = PhabricatorEnv::newObjectFromConfig('syntax-highlighter.engine'); $config = array( 'pygments.enabled' => PhabricatorEnv::getEnvConfig('pygments.enabled'), 'filename.map' => PhabricatorEnv::getEnvConfig('syntax.filemap'), ); foreach ($config as $key => $value) { $engine->setConfig($key, $value); } return $engine; } public static function highlightWithFilename($filename, $source) { $engine = self::newEngine(); $language = $engine->getLanguageFromFilename($filename); return $engine->highlightSource($language, $source); } public static function highlightWithLanguage($language, $source) { $engine = self::newEngine(); return $engine->highlightSource($language, $source); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhutilSafeHTML.php
src/infrastructure/markup/PhutilSafeHTML.php
<?php final class PhutilSafeHTML extends Phobject { private $content; public function __construct($content) { $this->content = (string)$content; } public function __toString() { return $this->content; } public function getHTMLContent() { return $this->content; } public function appendHTML($html /* , ... */) { foreach (func_get_args() as $html) { $this->content .= phutil_escape_html($html); } return $this; } public static function applyFunction($function, $string /* , ... */) { $args = func_get_args(); array_shift($args); $args = array_map('phutil_escape_html', $args); return new PhutilSafeHTML(call_user_func_array($function, $args)); } // Requires http://pecl.php.net/operator. public function __concat($html) { $clone = clone $this; return $clone->appendHTML($html); } public function __assign_concat($html) { return $this->appendHTML($html); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhabricatorMarkupEngine.php
src/infrastructure/markup/PhabricatorMarkupEngine.php
<?php /** * Manages markup engine selection, configuration, application, caching and * pipelining. * * @{class:PhabricatorMarkupEngine} can be used to render objects which * implement @{interface:PhabricatorMarkupInterface} in a batched, cache-aware * way. For example, if you have a list of comments written in remarkup (and * the objects implement the correct interface) you can render them by first * building an engine and adding the fields with @{method:addObject}. * * $field = 'field:body'; // Field you want to render. Each object exposes * // one or more fields of markup. * * $engine = new PhabricatorMarkupEngine(); * foreach ($comments as $comment) { * $engine->addObject($comment, $field); * } * * Now, call @{method:process} to perform the actual cache/rendering * step. This is a heavyweight call which does batched data access and * transforms the markup into output. * * $engine->process(); * * Finally, do something with the results: * * $results = array(); * foreach ($comments as $comment) { * $results[] = $engine->getOutput($comment, $field); * } * * If you have a single object to render, you can use the convenience method * @{method:renderOneObject}. * * @task markup Markup Pipeline * @task engine Engine Construction */ final class PhabricatorMarkupEngine extends Phobject { private $objects = array(); private $viewer; private $contextObject; private $version = 21; private $engineCaches = array(); private $auxiliaryConfig = array(); private static $engineStack = array(); /* -( Markup Pipeline )---------------------------------------------------- */ /** * Convenience method for pushing a single object through the markup * pipeline. * * @param PhabricatorMarkupInterface The object to render. * @param string The field to render. * @param PhabricatorUser User viewing the markup. * @param object A context object for policy checks * @return string Marked up output. * @task markup */ public static function renderOneObject( PhabricatorMarkupInterface $object, $field, PhabricatorUser $viewer, $context_object = null) { return id(new PhabricatorMarkupEngine()) ->setViewer($viewer) ->setContextObject($context_object) ->addObject($object, $field) ->process() ->getOutput($object, $field); } /** * Queue an object for markup generation when @{method:process} is * called. You can retrieve the output later with @{method:getOutput}. * * @param PhabricatorMarkupInterface The object to render. * @param string The field to render. * @return this * @task markup */ public function addObject(PhabricatorMarkupInterface $object, $field) { $key = $this->getMarkupFieldKey($object, $field); $this->objects[$key] = array( 'object' => $object, 'field' => $field, ); return $this; } /** * Process objects queued with @{method:addObject}. You can then retrieve * the output with @{method:getOutput}. * * @return this * @task markup */ public function process() { self::$engineStack[] = $this; try { $result = $this->execute(); } finally { array_pop(self::$engineStack); } return $result; } public static function isRenderingEmbeddedContent() { // See T13678. This prevents cycles when rendering embedded content that // itself has remarkup fields. return (count(self::$engineStack) > 1); } private function execute() { $keys = array(); foreach ($this->objects as $key => $info) { if (!isset($info['markup'])) { $keys[] = $key; } } if (!$keys) { return $this; } $objects = array_select_keys($this->objects, $keys); // Build all the markup engines. We need an engine for each field whether // we have a cache or not, since we still need to postprocess the cache. $engines = array(); foreach ($objects as $key => $info) { $engines[$key] = $info['object']->newMarkupEngine($info['field']); $engines[$key]->setConfig('viewer', $this->viewer); $engines[$key]->setConfig('contextObject', $this->contextObject); foreach ($this->auxiliaryConfig as $aux_key => $aux_value) { $engines[$key]->setConfig($aux_key, $aux_value); } } // Load or build the preprocessor caches. $blocks = $this->loadPreprocessorCaches($engines, $objects); $blocks = mpull($blocks, 'getCacheData'); $this->engineCaches = $blocks; // Finalize the output. foreach ($objects as $key => $info) { $engine = $engines[$key]; $field = $info['field']; $object = $info['object']; $output = $engine->postprocessText($blocks[$key]); $output = $object->didMarkupText($field, $output, $engine); $this->objects[$key]['output'] = $output; } return $this; } /** * Get the output of markup processing for a field queued with * @{method:addObject}. Before you can call this method, you must call * @{method:process}. * * @param PhabricatorMarkupInterface The object to retrieve. * @param string The field to retrieve. * @return string Processed output. * @task markup */ public function getOutput(PhabricatorMarkupInterface $object, $field) { $key = $this->getMarkupFieldKey($object, $field); $this->requireKeyProcessed($key); return $this->objects[$key]['output']; } /** * Retrieve engine metadata for a given field. * * @param PhabricatorMarkupInterface The object to retrieve. * @param string The field to retrieve. * @param string The engine metadata field to retrieve. * @param wild Optional default value. * @task markup */ public function getEngineMetadata( PhabricatorMarkupInterface $object, $field, $metadata_key, $default = null) { $key = $this->getMarkupFieldKey($object, $field); $this->requireKeyProcessed($key); return idx($this->engineCaches[$key]['metadata'], $metadata_key, $default); } /** * @task markup */ private function requireKeyProcessed($key) { if (empty($this->objects[$key])) { throw new Exception( pht( "Call %s before using results (key = '%s').", 'addObject()', $key)); } if (!isset($this->objects[$key]['output'])) { throw new PhutilInvalidStateException('process'); } } /** * @task markup */ private function getMarkupFieldKey( PhabricatorMarkupInterface $object, $field) { static $custom; if ($custom === null) { $custom = array_merge( self::loadCustomInlineRules(), self::loadCustomBlockRules()); $custom = mpull($custom, 'getRuleVersion', null); ksort($custom); $custom = PhabricatorHash::digestForIndex(serialize($custom)); } return $object->getMarkupFieldKey($field).'@'.$this->version.'@'.$custom; } /** * @task markup */ private function loadPreprocessorCaches(array $engines, array $objects) { $blocks = array(); $use_cache = array(); foreach ($objects as $key => $info) { if ($info['object']->shouldUseMarkupCache($info['field'])) { $use_cache[$key] = true; } } if ($use_cache) { try { $blocks = id(new PhabricatorMarkupCache())->loadAllWhere( 'cacheKey IN (%Ls)', array_keys($use_cache)); $blocks = mpull($blocks, null, 'getCacheKey'); } catch (Exception $ex) { phlog($ex); } } $is_readonly = PhabricatorEnv::isReadOnly(); foreach ($objects as $key => $info) { // False check in case MySQL doesn't support unicode characters // in the string (T1191), resulting in unserialize returning false. if (isset($blocks[$key]) && $blocks[$key]->getCacheData() !== false) { // If we already have a preprocessing cache, we don't need to rebuild // it. continue; } $text = $info['object']->getMarkupText($info['field']); $data = $engines[$key]->preprocessText($text); // NOTE: This is just debugging information to help sort out cache issues. // If one machine is misconfigured and poisoning caches you can use this // field to hunt it down. $metadata = array( 'host' => php_uname('n'), ); $blocks[$key] = id(new PhabricatorMarkupCache()) ->setCacheKey($key) ->setCacheData($data) ->setMetadata($metadata); if (isset($use_cache[$key]) && !$is_readonly) { // This is just filling a cache and always safe, even on a read pathway. $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $blocks[$key]->replace(); unset($unguarded); } } return $blocks; } /** * Set the viewing user. Used to implement object permissions. * * @param PhabricatorUser The viewing user. * @return this * @task markup */ public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } /** * Set the context object. Used to implement object permissions. * * @param The object in which context this remarkup is used. * @return this * @task markup */ public function setContextObject($object) { $this->contextObject = $object; return $this; } public function setAuxiliaryConfig($key, $value) { // TODO: This is gross and should be removed. Avoid use. $this->auxiliaryConfig[$key] = $value; return $this; } /* -( Engine Construction )------------------------------------------------ */ /** * @task engine */ public static function newManiphestMarkupEngine() { return self::newMarkupEngine(array( )); } /** * @task engine */ public static function newPhrictionMarkupEngine() { return self::newMarkupEngine(array( 'header.generate-toc' => true, )); } /** * @task engine */ public static function newPhameMarkupEngine() { return self::newMarkupEngine( array( 'macros' => false, 'uri.full' => true, 'uri.same-window' => true, 'uri.base' => PhabricatorEnv::getURI('/'), )); } /** * @task engine */ public static function newFeedMarkupEngine() { return self::newMarkupEngine( array( 'macros' => false, 'youtube' => false, )); } /** * @task engine */ public static function newCalendarMarkupEngine() { return self::newMarkupEngine(array( )); } /** * @task engine */ public static function newDifferentialMarkupEngine(array $options = array()) { return self::newMarkupEngine(array( 'differential.diff' => idx($options, 'differential.diff'), )); } /** * @task engine */ public static function newDiffusionMarkupEngine(array $options = array()) { return self::newMarkupEngine(array( 'header.generate-toc' => true, )); } /** * @task engine */ public static function getEngine($ruleset = 'default') { static $engines = array(); if (isset($engines[$ruleset])) { return $engines[$ruleset]; } $engine = null; switch ($ruleset) { case 'default': $engine = self::newMarkupEngine(array()); break; case 'feed': $engine = self::newMarkupEngine(array()); $engine->setConfig('autoplay.disable', true); break; case 'nolinebreaks': $engine = self::newMarkupEngine(array()); $engine->setConfig('preserve-linebreaks', false); break; case 'diffusion-readme': $engine = self::newMarkupEngine(array()); $engine->setConfig('preserve-linebreaks', false); $engine->setConfig('header.generate-toc', true); break; case 'diviner': $engine = self::newMarkupEngine(array()); $engine->setConfig('preserve-linebreaks', false); // $engine->setConfig('diviner.renderer', new DivinerDefaultRenderer()); $engine->setConfig('header.generate-toc', true); break; case 'extract': // Engine used for reference/edge extraction. Turn off anything which // is slow and doesn't change reference extraction. $engine = self::newMarkupEngine(array()); $engine->setConfig('pygments.enabled', false); break; default: throw new Exception(pht('Unknown engine ruleset: %s!', $ruleset)); } $engines[$ruleset] = $engine; return $engine; } /** * @task engine */ private static function getMarkupEngineDefaultConfiguration() { return array( 'pygments' => PhabricatorEnv::getEnvConfig('pygments.enabled'), 'youtube' => PhabricatorEnv::getEnvConfig( 'remarkup.enable-embedded-youtube'), 'differential.diff' => null, 'header.generate-toc' => false, 'macros' => true, 'uri.allowed-protocols' => PhabricatorEnv::getEnvConfig( 'uri.allowed-protocols'), 'uri.full' => false, 'syntax-highlighter.engine' => PhabricatorEnv::getEnvConfig( 'syntax-highlighter.engine'), 'preserve-linebreaks' => true, ); } /** * @task engine */ public static function newMarkupEngine(array $options) { $options += self::getMarkupEngineDefaultConfiguration(); $engine = new PhutilRemarkupEngine(); $engine->setConfig('preserve-linebreaks', $options['preserve-linebreaks']); $engine->setConfig('pygments.enabled', $options['pygments']); $engine->setConfig( 'uri.allowed-protocols', $options['uri.allowed-protocols']); $engine->setConfig('differential.diff', $options['differential.diff']); $engine->setConfig('header.generate-toc', $options['header.generate-toc']); $engine->setConfig( 'syntax-highlighter.engine', $options['syntax-highlighter.engine']); $style_map = id(new PhabricatorDefaultSyntaxStyle()) ->getRemarkupStyleMap(); $engine->setConfig('phutil.codeblock.style-map', $style_map); $engine->setConfig('uri.full', $options['uri.full']); if (isset($options['uri.base'])) { $engine->setConfig('uri.base', $options['uri.base']); } if (isset($options['uri.same-window'])) { $engine->setConfig('uri.same-window', $options['uri.same-window']); } $rules = array(); $rules[] = new PhutilRemarkupEscapeRemarkupRule(); $rules[] = new PhutilRemarkupEvalRule(); $rules[] = new PhutilRemarkupMonospaceRule(); $rules[] = new PhutilRemarkupDocumentLinkRule(); $rules[] = new PhabricatorNavigationRemarkupRule(); $rules[] = new PhabricatorKeyboardRemarkupRule(); $rules[] = new PhabricatorConfigRemarkupRule(); if ($options['youtube']) { $rules[] = new PhabricatorYoutubeRemarkupRule(); } $rules[] = new PhabricatorIconRemarkupRule(); $rules[] = new PhabricatorEmojiRemarkupRule(); $rules[] = new PhabricatorHandleRemarkupRule(); $applications = PhabricatorApplication::getAllInstalledApplications(); foreach ($applications as $application) { foreach ($application->getRemarkupRules() as $rule) { $rules[] = $rule; } } $rules[] = new PhutilRemarkupHyperlinkRule(); if ($options['macros']) { $rules[] = new PhabricatorImageMacroRemarkupRule(); $rules[] = new PhabricatorMemeRemarkupRule(); } $rules[] = new PhutilRemarkupBoldRule(); $rules[] = new PhutilRemarkupItalicRule(); $rules[] = new PhutilRemarkupDelRule(); $rules[] = new PhutilRemarkupUnderlineRule(); $rules[] = new PhutilRemarkupHighlightRule(); $rules[] = new PhutilRemarkupAnchorRule(); foreach (self::loadCustomInlineRules() as $rule) { $rules[] = clone $rule; } $blocks = array(); $blocks[] = new PhutilRemarkupQuotesBlockRule(); $blocks[] = new PhutilRemarkupReplyBlockRule(); $blocks[] = new PhutilRemarkupLiteralBlockRule(); $blocks[] = new PhutilRemarkupHeaderBlockRule(); $blocks[] = new PhutilRemarkupHorizontalRuleBlockRule(); $blocks[] = new PhutilRemarkupListBlockRule(); $blocks[] = new PhutilRemarkupCodeBlockRule(); $blocks[] = new PhutilRemarkupNoteBlockRule(); $blocks[] = new PhutilRemarkupTableBlockRule(); $blocks[] = new PhutilRemarkupSimpleTableBlockRule(); $blocks[] = new PhutilRemarkupInterpreterBlockRule(); $blocks[] = new PhutilRemarkupDefaultBlockRule(); foreach (self::loadCustomBlockRules() as $rule) { $blocks[] = $rule; } foreach ($blocks as $block) { $block->setMarkupRules($rules); } $engine->setBlockRules($blocks); return $engine; } public static function extractPHIDsFromMentions( PhabricatorUser $viewer, array $content_blocks) { $mentions = array(); $engine = self::newDifferentialMarkupEngine(); $engine->setConfig('viewer', $viewer); foreach ($content_blocks as $content_block) { if ($content_block === null) { continue; } if (!strlen($content_block)) { continue; } $engine->markupText($content_block); $phids = $engine->getTextMetadata( PhabricatorMentionRemarkupRule::KEY_MENTIONED, array()); $mentions += $phids; } return $mentions; } public static function extractFilePHIDsFromEmbeddedFiles( PhabricatorUser $viewer, array $content_blocks) { $files = array(); $engine = self::newDifferentialMarkupEngine(); $engine->setConfig('viewer', $viewer); foreach ($content_blocks as $content_block) { $engine->markupText($content_block); $phids = $engine->getTextMetadata( PhabricatorEmbedFileRemarkupRule::KEY_ATTACH_INTENT_FILE_PHIDS, array()); foreach ($phids as $phid) { $files[$phid] = $phid; } } return array_values($files); } public static function summarizeSentence($corpus) { $corpus = trim($corpus); $blocks = preg_split('/\n+/', $corpus, 2); $block = head($blocks); $sentences = preg_split( '/\b([.?!]+)\B/u', $block, 2, PREG_SPLIT_DELIM_CAPTURE); if (count($sentences) > 1) { $result = $sentences[0].$sentences[1]; } else { $result = head($sentences); } return id(new PhutilUTF8StringTruncator()) ->setMaximumGlyphs(128) ->truncateString($result); } /** * Produce a corpus summary, in a way that shortens the underlying text * without truncating it somewhere awkward. * * TODO: We could do a better job of this. * * @param string Remarkup corpus to summarize. * @return string Summarized corpus. */ public static function summarize($corpus) { // Major goals here are: // - Don't split in the middle of a character (utf-8). // - Don't split in the middle of, e.g., **bold** text, since // we end up with hanging '**' in the summary. // - Try not to pick an image macro, header, embedded file, etc. // - Hopefully don't return too much text. We don't explicitly limit // this right now. $blocks = preg_split("/\n *\n\s*/", $corpus); $best = null; foreach ($blocks as $block) { // This is a test for normal spaces in the block, i.e. a heuristic to // distinguish standard paragraphs from things like image macros. It may // not work well for non-latin text. We prefer to summarize with a // paragraph of normal words over an image macro, if possible. $has_space = preg_match('/\w\s\w/', $block); // This is a test to find embedded images and headers. We prefer to // summarize with a normal paragraph over a header or an embedded object, // if possible. $has_embed = preg_match('/^[{=]/', $block); if ($has_space && !$has_embed) { // This seems like a good summary, so return it. return $block; } if (!$best) { // This is the first block we found; if everything is garbage just // use the first block. $best = $block; } } return $best; } private static function loadCustomInlineRules() { return id(new PhutilClassMapQuery()) ->setAncestorClass('PhabricatorRemarkupCustomInlineRule') ->execute(); } private static function loadCustomBlockRules() { return id(new PhutilClassMapQuery()) ->setAncestorClass('PhabricatorRemarkupCustomBlockRule') ->execute(); } public static function digestRemarkupContent($object, $content) { $parts = array(); $parts[] = get_class($object); if ($object instanceof PhabricatorLiskDAO) { $parts[] = $object->getID(); } $parts[] = $content; $message = implode("\n", $parts); return PhabricatorHash::digestWithNamedKey($message, 'remarkup'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhutilMarkupEngine.php
src/infrastructure/markup/PhutilMarkupEngine.php
<?php abstract class PhutilMarkupEngine extends Phobject { /** * Set a configuration parameter which the engine can read to customize how * the text is marked up. This is a generic interface; consult the * documentation for specific rules and blocks for what options are available * for configuration. * * @param string Key to set in the configuration dictionary. * @param string Value to set. * @return this */ abstract public function setConfig($key, $value); /** * After text has been marked up with @{method:markupText}, you can retrieve * any metadata the markup process generated by calling this method. This is * a generic interface that allows rules to export extra information about * text; consult the documentation for specific rules and blocks to see what * metadata may be available in your configuration. * * @param string Key to retrieve from metadata. * @param mixed Default value to return if the key is not available. * @return mixed Metadata property, or default value. */ abstract public function getTextMetadata($key, $default = null); abstract public function markupText($text); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/PhabricatorMarkupPreviewController.php
src/infrastructure/markup/PhabricatorMarkupPreviewController.php
<?php final class PhabricatorMarkupPreviewController extends PhabricatorController { public function processRequest() { $request = $this->getRequest(); $viewer = $request->getUser(); $text = $request->getStr('text'); $output = PhabricatorMarkupEngine::renderOneObject( id(new PhabricatorMarkupOneOff()) ->setPreserveLinebreaks(true) ->setDisableCache(true) ->setContent($text), 'default', $viewer); return id(new AphrontAjaxResponse()) ->setContent($output); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/rule/PhabricatorNavigationRemarkupRule.php
src/infrastructure/markup/rule/PhabricatorNavigationRemarkupRule.php
<?php final class PhabricatorNavigationRemarkupRule extends PhutilRemarkupRule { public function getPriority() { return 200.0; } public function apply($text) { return preg_replace_callback( '@{nav\b((?:[^}\\\\]+|\\\\.)*)}@m', array($this, 'markupNavigation'), $text); } public function markupNavigation(array $matches) { if (!$this->isFlatText($matches[0])) { return $matches[0]; } $elements = ltrim($matches[1], ", \n"); $elements = explode('>', $elements); $defaults = array( 'name' => null, 'type' => 'link', 'href' => null, 'icon' => null, ); $sequence = array(); $parser = new PhutilSimpleOptions(); foreach ($elements as $element) { if (strpos($element, '=') === false) { $sequence[] = array( 'name' => trim($element), ) + $defaults; } else { $sequence[] = $parser->parse($element) + $defaults; } } if ($this->getEngine()->isTextMode()) { return implode(' > ', ipull($sequence, 'name')); } static $icon_names; if (!$icon_names) { $icon_names = array_fuse(PHUIIconView::getIcons()); } $out = array(); foreach ($sequence as $item) { $item_name = $item['name']; $item_color = PHUITagView::COLOR_GREY; if ($item['type'] == 'instructions') { $item_name = phutil_tag('em', array(), $item_name); $item_color = PHUITagView::COLOR_INDIGO; } $tag = id(new PHUITagView()) ->setType(PHUITagView::TYPE_SHADE) ->setColor($item_color) ->setName($item_name); if ($item['icon']) { $icon_name = 'fa-'.$item['icon']; if (isset($icon_names[$icon_name])) { $tag->setIcon($icon_name); } } if ($item['href'] !== null) { if (PhabricatorEnv::isValidRemoteURIForLink($item['href'])) { $tag->setHref($item['href']); $tag->setExternal(true); } } $out[] = $tag; } if ($this->getEngine()->isHTMLMailMode()) { $arrow_attr = array( 'style' => 'color: #92969D;', ); $nav_attr = array(); } else { $arrow_attr = array( 'class' => 'remarkup-nav-sequence-arrow', ); $nav_attr = array( 'class' => 'remarkup-nav-sequence', ); } $joiner = phutil_tag( 'span', $arrow_attr, " \xE2\x86\x92 "); $out = phutil_implode_html($joiner, $out); $out = phutil_tag( 'span', $nav_attr, $out); return $this->getEngine()->storeText($out); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/rule/PhabricatorObjectRemarkupRule.php
src/infrastructure/markup/rule/PhabricatorObjectRemarkupRule.php
<?php abstract class PhabricatorObjectRemarkupRule extends PhutilRemarkupRule { private $referencePattern; private $embedPattern; const KEY_RULE_OBJECT = 'rule.object'; const KEY_MENTIONED_OBJECTS = 'rule.object.mentioned'; abstract protected function getObjectNamePrefix(); abstract protected function loadObjects(array $ids); public function getPriority() { return 450.0; } protected function getObjectNamePrefixBeginsWithWordCharacter() { $prefix = $this->getObjectNamePrefix(); return preg_match('/^\w/', $prefix); } protected function getObjectIDPattern() { return '[1-9]\d*'; } protected function shouldMarkupObject(array $params) { return true; } protected function getObjectNameText( $object, PhabricatorObjectHandle $handle, $id) { return $this->getObjectNamePrefix().$id; } protected function loadHandles(array $objects) { $phids = mpull($objects, 'getPHID'); $viewer = $this->getEngine()->getConfig('viewer'); $handles = $viewer->loadHandles($phids); $handles = iterator_to_array($handles); $result = array(); foreach ($objects as $id => $object) { $result[$id] = $handles[$object->getPHID()]; } return $result; } protected function getObjectHref( $object, PhabricatorObjectHandle $handle, $id) { $uri = $handle->getURI(); if ($this->getEngine()->getConfig('uri.full')) { $uri = PhabricatorEnv::getURI($uri); } return $uri; } protected function renderObjectRefForAnyMedia( $object, PhabricatorObjectHandle $handle, $anchor, $id) { $href = $this->getObjectHref($object, $handle, $id); $text = $this->getObjectNameText($object, $handle, $id); if ($anchor) { $href = $href.'#'.$anchor; $text = $text.'#'.$anchor; } if ($this->getEngine()->isTextMode()) { return $text.' <'.PhabricatorEnv::getProductionURI($href).'>'; } else if ($this->getEngine()->isHTMLMailMode()) { $href = PhabricatorEnv::getProductionURI($href); return $this->renderObjectTagForMail($text, $href, $handle); } return $this->renderObjectRef($object, $handle, $anchor, $id); } protected function renderObjectRef( $object, PhabricatorObjectHandle $handle, $anchor, $id) { $href = $this->getObjectHref($object, $handle, $id); $text = $this->getObjectNameText($object, $handle, $id); $status_closed = PhabricatorObjectHandle::STATUS_CLOSED; if ($anchor) { $href = $href.'#'.$anchor; $text = $text.'#'.$anchor; } $attr = array( 'phid' => $handle->getPHID(), 'closed' => ($handle->getStatus() == $status_closed), ); return $this->renderHovertag($text, $href, $attr); } protected function renderObjectEmbedForAnyMedia( $object, PhabricatorObjectHandle $handle, $options) { $name = $handle->getFullName(); $href = $handle->getURI(); if ($this->getEngine()->isTextMode()) { return $name.' <'.PhabricatorEnv::getProductionURI($href).'>'; } else if ($this->getEngine()->isHTMLMailMode()) { $href = PhabricatorEnv::getProductionURI($href); return $this->renderObjectTagForMail($name, $href, $handle); } // See T13678. If we're already rendering embedded content, render a // default reference instead to avoid cycles. if (PhabricatorMarkupEngine::isRenderingEmbeddedContent()) { return $this->renderDefaultObjectEmbed($object, $handle); } return $this->renderObjectEmbed($object, $handle, $options); } protected function renderObjectEmbed( $object, PhabricatorObjectHandle $handle, $options) { return $this->renderDefaultObjectEmbed($object, $handle); } final protected function renderDefaultObjectEmbed( $object, PhabricatorObjectHandle $handle) { $name = $handle->getFullName(); $href = $handle->getURI(); $status_closed = PhabricatorObjectHandle::STATUS_CLOSED; $attr = array( 'phid' => $handle->getPHID(), 'closed' => ($handle->getStatus() == $status_closed), ); return $this->renderHovertag($name, $href, $attr); } protected function renderObjectTagForMail( $text, $href, PhabricatorObjectHandle $handle) { $status_closed = PhabricatorObjectHandle::STATUS_CLOSED; $strikethrough = $handle->getStatus() == $status_closed ? 'text-decoration: line-through;' : 'text-decoration: none;'; return phutil_tag( 'a', array( 'href' => $href, 'style' => 'background-color: #e7e7e7; border-color: #e7e7e7; border-radius: 3px; padding: 0 4px; font-weight: bold; color: black;' .$strikethrough, ), $text); } protected function renderHovertag($name, $href, array $attr = array()) { return id(new PHUITagView()) ->setName($name) ->setHref($href) ->setType(PHUITagView::TYPE_OBJECT) ->setPHID(idx($attr, 'phid')) ->setClosed(idx($attr, 'closed')) ->render(); } public function apply($text) { $text = preg_replace_callback( $this->getObjectEmbedPattern(), array($this, 'markupObjectEmbed'), $text); $text = preg_replace_callback( $this->getObjectReferencePattern(), array($this, 'markupObjectReference'), $text); return $text; } private function getObjectEmbedPattern() { if ($this->embedPattern === null) { $prefix = $this->getObjectNamePrefix(); $prefix = preg_quote($prefix); $id = $this->getObjectIDPattern(); $this->embedPattern = '(\B{'.$prefix.'('.$id.')([,\s](?:[^}\\\\]|\\\\.)*)?}\B)u'; } return $this->embedPattern; } private function getObjectReferencePattern() { if ($this->referencePattern === null) { $prefix = $this->getObjectNamePrefix(); $prefix = preg_quote($prefix); $id = $this->getObjectIDPattern(); // If the prefix starts with a word character (like "D"), we want to // require a word boundary so that we don't match "XD1" as "D1". If the // prefix does not start with a word character, we want to require no word // boundary for the same reasons. Test if the prefix starts with a word // character. if ($this->getObjectNamePrefixBeginsWithWordCharacter()) { $boundary = '\\b'; } else { $boundary = '\\B'; } // The "(?<![#@-])" prevents us from linking "#abcdef" or similar, and // "ABC-T1" (see T5714), and from matching "@T1" as a task (it is a user) // (see T9479). // The "\b" allows us to link "(abcdef)" or similar without linking things // in the middle of words. $this->referencePattern = '((?<![#@-])'.$boundary.$prefix.'('.$id.')(?:#([-\w\d]+))?(?!\w))u'; } return $this->referencePattern; } /** * Extract matched object references from a block of text. * * This is intended to make it easy to write unit tests for object remarkup * rules. Production code is not normally expected to call this method. * * @param string Text to match rules against. * @return wild Matches, suitable for writing unit tests against. */ public function extractReferences($text) { $embed_matches = null; preg_match_all( $this->getObjectEmbedPattern(), $text, $embed_matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); $ref_matches = null; preg_match_all( $this->getObjectReferencePattern(), $text, $ref_matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); $results = array(); $sets = array( 'embed' => $embed_matches, 'ref' => $ref_matches, ); foreach ($sets as $type => $matches) { $formatted = array(); foreach ($matches as $match) { $format = array( 'offset' => $match[1][1], 'id' => $match[1][0], ); if (isset($match[2][0])) { $format['tail'] = $match[2][0]; } $formatted[] = $format; } $results[$type] = $formatted; } return $results; } public function markupObjectEmbed(array $matches) { if (!$this->isFlatText($matches[0])) { return $matches[0]; } // If we're rendering a table of contents, just render the raw input. // This could perhaps be handled more gracefully but it seems unusual to // put something like "{P123}" in a header and it's not obvious what users // expect? See T8845. $engine = $this->getEngine(); if ($engine->getState('toc')) { return $matches[0]; } return $this->markupObject(array( 'type' => 'embed', 'id' => $matches[1], 'options' => idx($matches, 2), 'original' => $matches[0], 'quote.depth' => $engine->getQuoteDepth(), )); } public function markupObjectReference(array $matches) { if (!$this->isFlatText($matches[0])) { return $matches[0]; } // If we're rendering a table of contents, just render the monogram. $engine = $this->getEngine(); if ($engine->getState('toc')) { return $matches[0]; } return $this->markupObject(array( 'type' => 'ref', 'id' => $matches[1], 'anchor' => idx($matches, 2), 'original' => $matches[0], 'quote.depth' => $engine->getQuoteDepth(), )); } private function markupObject(array $params) { if (!$this->shouldMarkupObject($params)) { return $params['original']; } $regex = trim( PhabricatorEnv::getEnvConfig('remarkup.ignored-object-names')); if ($regex && preg_match($regex, $params['original'])) { return $params['original']; } $engine = $this->getEngine(); $token = $engine->storeText('x'); $metadata_key = self::KEY_RULE_OBJECT.'.'.$this->getObjectNamePrefix(); $metadata = $engine->getTextMetadata($metadata_key, array()); $metadata[] = array( 'token' => $token, ) + $params; $engine->setTextMetadata($metadata_key, $metadata); return $token; } public function didMarkupText() { $engine = $this->getEngine(); $metadata_key = self::KEY_RULE_OBJECT.'.'.$this->getObjectNamePrefix(); $metadata = $engine->getTextMetadata($metadata_key, array()); if (!$metadata) { return; } $ids = ipull($metadata, 'id'); $objects = $this->loadObjects($ids); // For objects that are invalid or which the user can't see, just render // the original text. // TODO: We should probably distinguish between these cases and render a // "you can't see this" state for nonvisible objects. foreach ($metadata as $key => $spec) { if (empty($objects[$spec['id']])) { $engine->overwriteStoredText( $spec['token'], $spec['original']); unset($metadata[$key]); } } $phids = $engine->getTextMetadata(self::KEY_MENTIONED_OBJECTS, array()); foreach ($objects as $object) { $phids[$object->getPHID()] = $object->getPHID(); } $engine->setTextMetadata(self::KEY_MENTIONED_OBJECTS, $phids); $handles = $this->loadHandles($objects); foreach ($metadata as $key => $spec) { $handle = $handles[$spec['id']]; $object = $objects[$spec['id']]; switch ($spec['type']) { case 'ref': $view = $this->renderObjectRefForAnyMedia( $object, $handle, $spec['anchor'], $spec['id']); break; case 'embed': $spec['options'] = $this->assertFlatText($spec['options']); $view = $this->renderObjectEmbedForAnyMedia( $object, $handle, $spec['options']); break; } $engine->overwriteStoredText($spec['token'], $view); } $engine->setTextMetadata($metadata_key, array()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/rule/PhabricatorRemarkupCustomBlockRule.php
src/infrastructure/markup/rule/PhabricatorRemarkupCustomBlockRule.php
<?php abstract class PhabricatorRemarkupCustomBlockRule extends PhutilRemarkupBlockRule { public function getRuleVersion() { return 1; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/rule/PhabricatorRemarkupCustomInlineRule.php
src/infrastructure/markup/rule/PhabricatorRemarkupCustomInlineRule.php
<?php abstract class PhabricatorRemarkupCustomInlineRule extends PhutilRemarkupRule { public function getRuleVersion() { return 1; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/rule/PhabricatorYoutubeRemarkupRule.php
src/infrastructure/markup/rule/PhabricatorYoutubeRemarkupRule.php
<?php final class PhabricatorYoutubeRemarkupRule extends PhutilRemarkupRule { public function getPriority() { return 350.0; } public function apply($text) { try { $uri = new PhutilURI($text); } catch (Exception $ex) { return $text; } $domain = $uri->getDomain(); if (!preg_match('/(^|\.)youtube\.com\z/', $domain)) { return $text; } $v_params = array(); $params = $uri->getQueryParamsAsPairList(); foreach ($params as $pair) { list($k, $v) = $pair; if ($k === 'v') { $v_params[] = $v; } } if (count($v_params) !== 1) { return $text; } $v_param = head($v_params); $text_mode = $this->getEngine()->isTextMode(); $mail_mode = $this->getEngine()->isHTMLMailMode(); if ($text_mode || $mail_mode) { return $text; } $youtube_src = 'https://www.youtube.com/embed/'.$v_param; $iframe = $this->newTag( 'div', array( 'class' => 'embedded-youtube-video', ), $this->newTag( 'iframe', array( 'width' => '650', 'height' => '400', 'style' => 'margin: 1em auto; border: 0px;', 'src' => $youtube_src, 'frameborder' => 0, ), '')); return $this->getEngine()->storeText($iframe); } public function didMarkupText() { CelerityAPI::getStaticResourceResponse() ->addContentSecurityPolicyURI('frame-src', 'https://www.youtube.com/'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/rule/PhabricatorKeyboardRemarkupRule.php
src/infrastructure/markup/rule/PhabricatorKeyboardRemarkupRule.php
<?php final class PhabricatorKeyboardRemarkupRule extends PhutilRemarkupRule { public function getPriority() { return 200.0; } public function apply($text) { return preg_replace_callback( '@{key\b((?:[^}\\\\]+|\\\\.)*)}@m', array($this, 'markupKeystrokes'), $text); } public function markupKeystrokes(array $matches) { if (!$this->isFlatText($matches[0])) { return $matches[0]; } $keys = explode(' ', $matches[1]); foreach ($keys as $k => $v) { $v = trim($v, " \n"); $v = preg_replace('/\\\\(.)/', '\\1', $v); if (!strlen($v)) { unset($keys[$k]); continue; } $keys[$k] = $v; } $special = array( array( 'name' => pht('Command'), 'symbol' => "\xE2\x8C\x98", 'aliases' => array( 'cmd', 'command', ), ), array( 'name' => pht('Option'), 'symbol' => "\xE2\x8C\xA5", 'aliases' => array( 'opt', 'option', ), ), array( 'name' => pht('Shift'), 'symbol' => "\xE2\x87\xA7", 'aliases' => array( 'shift', ), ), array( 'name' => pht('Escape'), 'symbol' => "\xE2\x8E\x8B", 'aliases' => array( 'esc', 'escape', ), ), array( 'name' => pht('Enter'), 'symbol' => "\xE2\x8F\x8E", 'aliases' => array( 'enter', 'return', ), ), array( 'name' => pht('Control'), 'symbol' => "\xE2\x8C\x83", 'aliases' => array( 'ctrl', 'control', ), ), array( 'name' => pht('Up'), 'symbol' => "\xE2\x86\x91", 'heavy' => "\xE2\xAC\x86", 'aliases' => array( 'up', 'arrow-up', 'up-arrow', 'north', ), ), array( 'name' => pht('Tab'), 'symbol' => "\xE2\x87\xA5", 'aliases' => array( 'tab', ), ), array( 'name' => pht('Right'), 'symbol' => "\xE2\x86\x92", 'heavy' => "\xE2\x9E\xA1", 'aliases' => array( 'right', 'right-arrow', 'arrow-right', 'east', ), ), array( 'name' => pht('Left'), 'symbol' => "\xE2\x86\x90", 'heavy' => "\xE2\xAC\x85", 'aliases' => array( 'left', 'left-arrow', 'arrow-left', 'west', ), ), array( 'name' => pht('Down'), 'symbol' => "\xE2\x86\x93", 'heavy' => "\xE2\xAC\x87", 'aliases' => array( 'down', 'down-arrow', 'arrow-down', 'south', ), ), array( 'name' => pht('Up Right'), 'symbol' => "\xE2\x86\x97", 'heavy' => "\xE2\xAC\x88", 'aliases' => array( 'up-right', 'upright', 'up-right-arrow', 'upright-arrow', 'arrow-up-right', 'arrow-upright', 'northeast', 'north-east', ), ), array( 'name' => pht('Down Right'), 'symbol' => "\xE2\x86\x98", 'heavy' => "\xE2\xAC\x8A", 'aliases' => array( 'down-right', 'downright', 'down-right-arrow', 'downright-arrow', 'arrow-down-right', 'arrow-downright', 'southeast', 'south-east', ), ), array( 'name' => pht('Down Left'), 'symbol' => "\xE2\x86\x99", 'heavy' => "\xE2\xAC\x8B", 'aliases' => array( 'down-left', 'downleft', 'down-left-arrow', 'downleft-arrow', 'arrow-down-left', 'arrow-downleft', 'southwest', 'south-west', ), ), array( 'name' => pht('Up Left'), 'symbol' => "\xE2\x86\x96", 'heavy' => "\xE2\xAC\x89", 'aliases' => array( 'up-left', 'upleft', 'up-left-arrow', 'upleft-arrow', 'arrow-up-left', 'arrow-upleft', 'northwest', 'north-west', ), ), ); $map = array(); foreach ($special as $spec) { foreach ($spec['aliases'] as $alias) { $map[$alias] = $spec; } } $is_text = $this->getEngine()->isTextMode(); $is_html_mail = $this->getEngine()->isHTMLMailMode(); if ($is_html_mail) { $key_style = array( 'display: inline-block;', 'min-width: 1em;', 'padding: 4px 5px 5px;', 'font-weight: normal;', 'font-size: 0.8rem;', 'text-align: center;', 'text-decoration: none;', 'line-height: 0.6rem;', 'border-radius: 3px;', 'box-shadow: inset 0 -1px 0 rgba(71, 87, 120, 0.08);', 'user-select: none;', 'background: #f7f7f7;', 'border: 1px solid #C7CCD9;', ); $key_style = implode(' ', $key_style); $join_style = array( 'padding: 0 4px;', 'color: #92969D;', ); $join_style = implode(' ', $join_style); } else { $key_style = null; $join_style = null; } $parts = array(); foreach ($keys as $k => $v) { $normal = phutil_utf8_strtolower($v); if (isset($map[$normal])) { $spec = $map[$normal]; } else { $spec = array( 'name' => null, 'symbol' => $v, ); } if ($is_text) { $parts[] = '['.$spec['symbol'].']'; } else { $parts[] = phutil_tag( 'kbd', array( 'title' => $spec['name'], 'style' => $key_style, ), $spec['symbol']); } } if ($is_text) { $parts = implode(' + ', $parts); } else { $glue = phutil_tag( 'span', array( 'class' => 'kbd-join', 'style' => $join_style, ), '+'); $parts = phutil_implode_html($glue, $parts); } return $this->getEngine()->storeText($parts); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/rule/PhabricatorConfigRemarkupRule.php
src/infrastructure/markup/rule/PhabricatorConfigRemarkupRule.php
<?php final class PhabricatorConfigRemarkupRule extends PhutilRemarkupRule { public function apply($text) { return preg_replace_callback( '(@{config:([^}]+)})', array($this, 'markupConfig'), $text); } public function getPriority() { // We're reusing the Diviner atom syntax, so make sure we evaluate before // the Diviner rule evaluates. return id(new DivinerSymbolRemarkupRule())->getPriority() - 1; } public function markupConfig(array $matches) { if (!$this->isFlatText($matches[0])) { return $matches[0]; } $config_key = $matches[1]; try { $option = PhabricatorEnv::getEnvConfig($config_key); } catch (Exception $ex) { return $matches[0]; } $is_text = $this->getEngine()->isTextMode(); $is_html_mail = $this->getEngine()->isHTMLMailMode(); if ($is_text || $is_html_mail) { return pht('"%s"', $config_key); } $link = phutil_tag( 'a', array( 'href' => urisprintf('/config/edit/%s/', $config_key), 'target' => '_blank', ), $config_key); return $this->getEngine()->storeText($link); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/__tests__/PhabricatorMarkupEngineTestCase.php
src/infrastructure/markup/__tests__/PhabricatorMarkupEngineTestCase.php
<?php final class PhabricatorMarkupEngineTestCase extends PhabricatorTestCase { public function testRemarkupSentenceSummmaries() { $this->assertSentenceSummary( 'The quick brown fox. Jumped over the lazy dog.', 'The quick brown fox.'); $this->assertSentenceSummary( 'Go to www.help.com for details. Good day.', 'Go to www.help.com for details.'); $this->assertSentenceSummary( 'Coxy lummox gives squid who asks for job pen.', 'Coxy lummox gives squid who asks for job pen.'); $this->assertSentenceSummary( 'DEPRECATED', 'DEPRECATED'); $this->assertSentenceSummary( 'Never use this! It is deadly poison.', 'Never use this!'); $this->assertSentenceSummary( "a short poem\nmeow meow meow\nmeow meow meow\n\n- cat", 'a short poem'); $this->assertSentenceSummary( 'WOW!! GREAT PROJECT!', 'WOW!!'); } private function assertSentenceSummary($corpus, $summary) { $this->assertEqual( $summary, PhabricatorMarkupEngine::summarizeSentence($corpus), pht('Summary of: %s', $corpus)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/__tests__/PhutilTranslatedHTMLTestCase.php
src/infrastructure/markup/__tests__/PhutilTranslatedHTMLTestCase.php
<?php final class PhutilTranslatedHTMLTestCase extends PhutilTestCase { public function testHTMLTranslations() { $string = '%s awoke <strong>suddenly</strong> at %s.'; $when = '<4 AM>'; $translator = $this->newTranslator('en_US'); // When no components are HTML, everything is treated as a string. $who = '<span>Abraham</span>'; $translation = $translator->translate( $string, $who, $when); $this->assertEqual( 'string', gettype($translation)); $this->assertEqual( '<span>Abraham</span> awoke <strong>suddenly</strong> at <4 AM>.', $translation); // When at least one component is HTML, everything is treated as HTML. $who = phutil_tag('span', array(), 'Abraham'); $translation = $translator->translate( $string, $who, $when); $this->assertTrue($translation instanceof PhutilSafeHTML); $this->assertEqual( '<span>Abraham</span> awoke <strong>suddenly</strong> at &lt;4 AM&gt;.', $translation->getHTMLContent()); $translation = $translator->translate( $string, $who, new PhutilNumber(1383930802)); $this->assertEqual( '<span>Abraham</span> awoke <strong>suddenly</strong> at 1,383,930,802.', $translation->getHTMLContent()); // In this translation, we have no alternatives for the first conversion. $translator->setTranslations( array( 'Run the command %s %d time(s).' => array( array( 'Run the command %s once.', 'Run the command %s %d times.', ), ), )); $this->assertEqual( 'Run the command <tt>ls</tt> 123 times.', (string)$translator->translate( 'Run the command %s %d time(s).', hsprintf('<tt>%s</tt>', 'ls'), 123)); } private function newTranslator($locale_code) { $locale = PhutilLocale::loadLocale($locale_code); return id(new PhutilTranslator()) ->setLocale($locale); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/__tests__/PhabricatorAnchorTestCase.php
src/infrastructure/markup/__tests__/PhabricatorAnchorTestCase.php
<?php final class PhabricatorAnchorTestCase extends PhabricatorTestCase { public function testAnchors() { $low_ascii = ''; for ($ii = 19; $ii <= 127; $ii++) { $low_ascii .= chr($ii); } $snowman = "\xE2\x9B\x84"; $map = array( '' => '', 'Bells and Whistles' => 'bells-and-whistles', 'Termination for Nonpayment' => 'termination-for-nonpayment', $low_ascii => '0123456789-abcdefghijklmnopqrstu', 'xxxx xxxx xxxx xxxx xxxx on' => 'xxxx-xxxx-xxxx-xxxx-xxxx', 'xxxx xxxx xxxx xxxx xxxx ox' => 'xxxx-xxxx-xxxx-xxxx-xxxx-ox', "So, You Want To Build A {$snowman}?" => "so-you-want-to-build-a-{$snowman}", str_repeat($snowman, 128) => str_repeat($snowman, 32), ); foreach ($map as $input => $expect) { $anchor = PhutilRemarkupHeaderBlockRule::getAnchorNameFromHeaderText( $input); $this->assertEqual( $expect, $anchor, pht('Anchor for "%s".', $input)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/__tests__/PhutilSafeHTMLTestCase.php
src/infrastructure/markup/__tests__/PhutilSafeHTMLTestCase.php
<?php final class PhutilSafeHTMLTestCase extends PhutilTestCase { public function testOperator() { if (!extension_loaded('operator')) { $this->assertSkipped(pht('Operator extension not available.')); } $a = phutil_tag('a'); $ab = $a.phutil_tag('b'); $this->assertEqual('<a></a><b></b>', $ab->getHTMLContent()); $this->assertEqual('<a></a>', $a->getHTMLContent()); $a .= phutil_tag('a'); $this->assertEqual('<a></a><a></a>', $a->getHTMLContent()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/__tests__/PhutilMarkupTestCase.php
src/infrastructure/markup/__tests__/PhutilMarkupTestCase.php
<?php final class PhutilMarkupTestCase extends PhutilTestCase { public function testTagDefaults() { $this->assertEqual( (string)phutil_tag('br'), (string)phutil_tag('br', array())); $this->assertEqual( (string)phutil_tag('br', array()), (string)phutil_tag('br', array(), null)); } public function testTagEmpty() { $this->assertEqual( '<br />', (string)phutil_tag('br', array(), null)); $this->assertEqual( '<div></div>', (string)phutil_tag('div', array(), null)); $this->assertEqual( '<div></div>', (string)phutil_tag('div', array(), '')); } public function testTagBasics() { $this->assertEqual( '<br />', (string)phutil_tag('br')); $this->assertEqual( '<div>y</div>', (string)phutil_tag('div', array(), 'y')); } public function testTagAttributes() { $this->assertEqual( '<div u="v">y</div>', (string)phutil_tag('div', array('u' => 'v'), 'y')); $this->assertEqual( '<br u="v" />', (string)phutil_tag('br', array('u' => 'v'))); } public function testTagEscapes() { $this->assertEqual( '<br u="&lt;" />', (string)phutil_tag('br', array('u' => '<'))); $this->assertEqual( '<div><br /></div>', (string)phutil_tag('div', array(), phutil_tag('br'))); } public function testTagNullAttribute() { $this->assertEqual( '<br />', (string)phutil_tag('br', array('y' => null))); } public function testTagJavascriptProtocolRejection() { $hrefs = array( 'javascript:alert(1)' => true, 'JAVASCRIPT:alert(2)' => true, // NOTE: When interpreted as a URI, this is dropped because of leading // whitespace. ' javascript:alert(3)' => array(true, false), '/' => false, '/path/to/stuff/' => false, '' => false, 'http://example.com/' => false, '#' => false, 'javascript://anything' => true, // Chrome 33 and IE11, at a minimum, treat this as Javascript. "javascript\n:alert(4)" => true, // Opera currently accepts a variety of unicode spaces. This test case // has a smattering of them. "\xE2\x80\x89javascript:" => true, "javascript\xE2\x80\x89:" => true, "\xE2\x80\x84javascript:" => true, "javascript\xE2\x80\x84:" => true, // Because we're aggressive, all of unicode should trigger detection // by default. "\xE2\x98\x83javascript:" => true, "javascript\xE2\x98\x83:" => true, "\xE2\x98\x83javascript\xE2\x98\x83:" => true, // We're aggressive about this, so we'll intentionally raise false // positives in these cases. 'javascript~:alert(5)' => true, '!!!javascript!!!!:alert(6)' => true, // However, we should raise true negatives in these slightly more // reasonable cases. 'javascript/:docs.html' => false, 'javascripts:x.png' => false, 'COOLjavascript:page' => false, '/javascript:alert(1)' => false, ); foreach (array(true, false) as $use_uri) { foreach ($hrefs as $href => $expect) { if (is_array($expect)) { $expect = ($use_uri ? $expect[1] : $expect[0]); } if ($use_uri) { $href_value = new PhutilURI($href); } else { $href_value = $href; } $caught = null; try { phutil_tag('a', array('href' => $href_value), 'click for candy'); } catch (Exception $ex) { $caught = $ex; } $desc = pht( 'Unexpected result for "%s". <uri = %s, expect exception = %s>', $href, $use_uri ? pht('Yes') : pht('No'), $expect ? pht('Yes') : pht('No')); $this->assertEqual( $expect, $caught instanceof Exception, $desc); } } } public function testURIEscape() { $this->assertEqual( '%2B/%20%3F%23%26%3A%21xyz%25', phutil_escape_uri('+/ ?#&:!xyz%')); } public function testURIPathComponentEscape() { $this->assertEqual( 'a%252Fb', phutil_escape_uri_path_component('a/b')); $str = ''; for ($ii = 0; $ii <= 255; $ii++) { $str .= chr($ii); } $this->assertEqual( $str, phutil_unescape_uri_path_component( rawurldecode( // Simulates webserver. phutil_escape_uri_path_component($str)))); } public function testHsprintf() { $this->assertEqual( '<div>&lt;3</div>', (string)hsprintf('<div>%s</div>', '<3')); } public function testAppendHTML() { $html = phutil_tag('hr'); $html->appendHTML(phutil_tag('br'), '<evil>'); $this->assertEqual('<hr /><br />&lt;evil&gt;', $html->getHTMLContent()); } public function testArrayEscaping() { $this->assertEqual( '<div>&lt;div&gt;</div>', phutil_escape_html( array( hsprintf('<div>'), array( array( '<', array( 'd', array( array( hsprintf('i'), ), 'v', ), ), array( array( '>', ), ), ), ), hsprintf('</div>'), ))); $this->assertEqual( '<div><br /><hr /><wbr /></div>', phutil_tag( 'div', array(), array( array( array( phutil_tag('br'), array( phutil_tag('hr'), ), phutil_tag('wbr'), ), ), ))->getHTMLContent()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupDelRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupDelRule.php
<?php final class PhutilRemarkupDelRule extends PhutilRemarkupRule { public function getPriority() { return 1000.0; } public function apply($text) { if ($this->getEngine()->isTextMode()) { return $text; } return $this->replaceHTML( '@(?<!~)~~([^\s~].*?~*)~~@s', array($this, 'applyCallback'), $text); } protected function applyCallback(array $matches) { return hsprintf('<del>%s</del>', $matches[1]); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupRule.php
<?php abstract class PhutilRemarkupRule extends Phobject { private $engine; private $replaceCallback; public function setEngine(PhutilRemarkupEngine $engine) { $this->engine = $engine; return $this; } public function getEngine() { return $this->engine; } public function getPriority() { return 500.0; } abstract public function apply($text); public function getPostprocessKey() { return spl_object_hash($this); } public function didMarkupText() { return; } protected function replaceHTML($pattern, $callback, $text) { $this->replaceCallback = $callback; return phutil_safe_html(preg_replace_callback( $pattern, array($this, 'replaceHTMLCallback'), phutil_escape_html($text))); } private function replaceHTMLCallback(array $match) { return phutil_escape_html(call_user_func( $this->replaceCallback, array_map('phutil_safe_html', $match))); } /** * Safely generate a tag. * * In Remarkup contexts, it's not safe to use arbitrary text in tag * attributes: even though it will be escaped, it may contain replacement * tokens which are then replaced with markup. * * This method acts as @{function:phutil_tag}, but checks attributes before * using them. * * @param string Tag name. * @param dict<string, wild> Tag attributes. * @param wild Tag content. * @return PhutilSafeHTML Tag object. */ protected function newTag($name, array $attrs, $content = null) { foreach ($attrs as $key => $attr) { if ($attr !== null) { $attrs[$key] = $this->assertFlatText($attr); } } return phutil_tag($name, $attrs, $content); } /** * Assert that a text token is flat (it contains no replacement tokens). * * Because tokens can be replaced with markup, it is dangerous to use * arbitrary input text in tag attributes. Normally, rule precedence should * prevent this. Asserting that text is flat before using it as an attribute * provides an extra layer of security. * * Normally, you can call @{method:newTag} rather than calling this method * directly. @{method:newTag} will check attributes for you. * * @param wild Ostensibly flat text. * @return string Flat text. */ protected function assertFlatText($text) { $text = (string)hsprintf('%s', phutil_safe_html($text)); $rich = (strpos($text, PhutilRemarkupBlockStorage::MAGIC_BYTE) !== false); if ($rich) { throw new Exception( pht( 'Remarkup rule precedence is dangerous: rendering text with tokens '. 'as flat text!')); } return $text; } /** * Check whether text is flat (contains no replacement tokens) or not. * * @param wild Ostensibly flat text. * @return bool True if the text is flat. */ protected function isFlatText($text) { $text = (string)hsprintf('%s', phutil_safe_html($text)); return (strpos($text, PhutilRemarkupBlockStorage::MAGIC_BYTE) === false); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupHyperlinkRef.php
src/infrastructure/markup/markuprule/PhutilRemarkupHyperlinkRef.php
<?php final class PhutilRemarkupHyperlinkRef extends Phobject { private $token; private $uri; private $embed; private $result; public function __construct(array $map) { $this->token = $map['token']; $this->uri = $map['uri']; $this->embed = ($map['mode'] === '{'); } public function getToken() { return $this->token; } public function getURI() { return $this->uri; } public function isEmbed() { return $this->embed; } public function setResult($result) { $this->result = $result; return $this; } public function getResult() { return $this->result; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupHyperlinkRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupHyperlinkRule.php
<?php final class PhutilRemarkupHyperlinkRule extends PhutilRemarkupRule { const KEY_HYPERLINKS = 'hyperlinks'; public function getPriority() { return 400.0; } public function apply($text) { static $angle_pattern; static $curly_pattern; static $bare_pattern; if ($angle_pattern === null) { // See T13608. A previous version of this code matched bare URIs // starting with "\w{3,}", which can take a very long time to match // against long inputs. // // Use a protocol length limit in all patterns for general sanity, // and a negative lookbehind in the bare pattern to avoid explosive // complexity during expression evaluation. $protocol_fragment = '\w{3,32}'; $uri_fragment = '[^\s'.PhutilRemarkupBlockStorage::MAGIC_BYTE.']+'; $angle_pattern = sprintf( '(<(%s://%s?)>)', $protocol_fragment, $uri_fragment); $curly_pattern = sprintf( '({(%s://%s?)})', $protocol_fragment, $uri_fragment); $bare_pattern = sprintf( '((?<!\w)%s://%s)', $protocol_fragment, $uri_fragment); } // Hyperlinks with explicit "<>" around them get linked exactly, without // the "<>". Angle brackets are basically special and mean "this is a URL // with weird characters". This is assumed to be reasonable because they // don't appear in most normal text or most normal URLs. $text = preg_replace_callback( $angle_pattern, array($this, 'markupHyperlinkAngle'), $text); // We match "{uri}", but do not link it by default. $text = preg_replace_callback( $curly_pattern, array($this, 'markupHyperlinkCurly'), $text); // Anything else we match "ungreedily", which means we'll look for // stuff that's probably puncutation or otherwise not part of the URL and // not link it. This lets someone write "QuicK! Go to // http://www.example.com/!". We also apply some paren balancing rules. // NOTE: We're explicitly avoiding capturing stored blocks, so text like // `http://www.example.com/[[x | y]]` doesn't get aggressively captured. $text = preg_replace_callback( $bare_pattern, array($this, 'markupHyperlinkUngreedy'), $text); return $text; } public function markupHyperlinkAngle(array $matches) { return $this->markupHyperlink('<', $matches); } public function markupHyperlinkCurly(array $matches) { return $this->markupHyperlink('{', $matches); } protected function markupHyperlink($mode, array $matches) { $raw_uri = $matches[1]; try { $uri = new PhutilURI($raw_uri); } catch (Exception $ex) { return $matches[0]; } $engine = $this->getEngine(); $token = $engine->storeText($raw_uri); $list_key = self::KEY_HYPERLINKS; $link_list = $engine->getTextMetadata($list_key, array()); $link_list[] = array( 'token' => $token, 'uri' => $raw_uri, 'mode' => $mode, ); $engine->setTextMetadata($list_key, $link_list); return $token; } protected function renderHyperlink($link, $is_embed) { // If the URI is "{uri}" and no handler picked it up, we just render it // as plain text. if ($is_embed) { return $this->renderRawLink($link, $is_embed); } $engine = $this->getEngine(); $same_window = $engine->getConfig('uri.same-window', false); if ($same_window) { $target = null; } else { $target = '_blank'; } return phutil_tag( 'a', array( 'href' => $link, 'class' => 'remarkup-link', 'target' => $target, 'rel' => 'noreferrer', ), $link); } private function renderRawLink($link, $is_embed) { if ($is_embed) { return '{'.$link.'}'; } else { return $link; } } protected function markupHyperlinkUngreedy($matches) { $match = $matches[0]; $tail = null; $trailing = null; if (preg_match('/[;,.:!?]+$/', $match, $trailing)) { $tail = $trailing[0]; $match = substr($match, 0, -strlen($tail)); } // If there's a closing paren at the end but no balancing open paren in // the URL, don't link the close paren. This is an attempt to gracefully // handle the two common paren cases, Wikipedia links and English language // parentheticals, e.g.: // // http://en.wikipedia.org/wiki/Noun_(disambiguation) // (see also http://www.example.com) // // We could apply a craftier heuristic here which tries to actually balance // the parens, but this is probably sufficient. if (preg_match('/\\)$/', $match) && !preg_match('/\\(/', $match)) { $tail = ')'.$tail; $match = substr($match, 0, -1); } try { $uri = new PhutilURI($match); } catch (Exception $ex) { return $matches[0]; } $link = $this->markupHyperlink(null, array(null, $match)); return hsprintf('%s%s', $link, $tail); } public function didMarkupText() { $engine = $this->getEngine(); $protocols = $engine->getConfig('uri.allowed-protocols', array()); $is_toc = $engine->getState('toc'); $is_text = $engine->isTextMode(); $is_mail = $engine->isHTMLMailMode(); $list_key = self::KEY_HYPERLINKS; $raw_list = $engine->getTextMetadata($list_key, array()); $links = array(); foreach ($raw_list as $key => $link) { $token = $link['token']; $raw_uri = $link['uri']; $mode = $link['mode']; $is_embed = ($mode === '{'); $is_literal = ($mode === '<'); // If we're rendering in a "Table of Contents" or a plain text mode, // we're going to render the raw URI without modifications. if ($is_toc || $is_text) { $result = $this->renderRawLink($raw_uri, $is_embed); $engine->overwriteStoredText($token, $result); continue; } // If this URI doesn't use a whitelisted protocol, don't link it. This // is primarily intended to prevent "javascript://" silliness. $uri = new PhutilURI($raw_uri); $protocol = $uri->getProtocol(); $valid_protocol = idx($protocols, $protocol); if (!$valid_protocol) { $result = $this->renderRawLink($raw_uri, $is_embed); $engine->overwriteStoredText($token, $result); continue; } // If the URI is written as "<uri>", we'll render it literally even if // some handler would otherwise deal with it. // If we're rendering for HTML mail, we also render literally. if ($is_literal || $is_mail) { $result = $this->renderHyperlink($raw_uri, $is_embed); $engine->overwriteStoredText($token, $result); continue; } // Otherwise, this link is a valid resource which extensions are allowed // to handle. $links[$key] = $link; } if (!$links) { return; } foreach ($links as $key => $link) { $links[$key] = new PhutilRemarkupHyperlinkRef($link); } $extensions = PhutilRemarkupHyperlinkEngineExtension::getAllLinkEngines(); foreach ($extensions as $extension) { $extension = id(clone $extension) ->setEngine($engine) ->processHyperlinks($links); foreach ($links as $key => $link) { $result = $link->getResult(); if ($result !== null) { $engine->overwriteStoredText($link->getToken(), $result); unset($links[$key]); } } if (!$links) { break; } } // Render any remaining links in a normal way. foreach ($links as $link) { $result = $this->renderHyperlink($link->getURI(), $link->isEmbed()); $engine->overwriteStoredText($link->getToken(), $result); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupUnderlineRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupUnderlineRule.php
<?php final class PhutilRemarkupUnderlineRule extends PhutilRemarkupRule { public function getPriority() { return 1000.0; } public function apply($text) { if ($this->getEngine()->isTextMode()) { return $text; } return $this->replaceHTML( '@(?<!_|/)__([^\s_/].*?_*)__(?!/|\.\S)@s', array($this, 'applyCallback'), $text); } protected function applyCallback(array $matches) { return hsprintf('<u>%s</u>', $matches[1]); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupHighlightRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupHighlightRule.php
<?php final class PhutilRemarkupHighlightRule extends PhutilRemarkupRule { public function getPriority() { return 1000.0; } public function apply($text) { if ($this->getEngine()->isTextMode()) { return $text; } return $this->replaceHTML( '@!!(.+?)(!{2,})@', array($this, 'applyCallback'), $text); } protected function applyCallback(array $matches) { // Remove the two exclamation points that represent syntax. $excitement = substr($matches[2], 2); // If the internal content consists of ONLY exclamation points, leave it // untouched so "!!!!!" is five exclamation points instead of one // highlighted exclamation point. if (preg_match('/^!+\z/', $matches[1])) { return $matches[0]; } // $excitement now has two fewer !'s than we started with. return hsprintf('<span class="remarkup-highlight">%s%s</span>', $matches[1], $excitement); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupMonospaceRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupMonospaceRule.php
<?php final class PhutilRemarkupMonospaceRule extends PhutilRemarkupRule { public function getPriority() { return 100.0; } public function apply($text) { // NOTE: We don't require a trailing non-boundary on the backtick syntax, // to permit the use case of naming and pluralizing a class, like // "Load all the `PhutilArray`s and then iterate over them." In theory, the // required \B on the leading backtick should protect us from most // collateral damage. return preg_replace_callback( '@##([\s\S]+?)##|\B`(.+?)`@', array($this, 'markupMonospacedText'), $text); } protected function markupMonospacedText(array $matches) { if ($this->getEngine()->isTextMode()) { $result = $matches[0]; } else if ($this->getEngine()->isHTMLMailMode()) { $match = isset($matches[2]) ? $matches[2] : $matches[1]; $result = phutil_tag( 'tt', array( 'style' => 'background: #ebebeb; font-size: 13px;', ), $match); } else { $match = isset($matches[2]) ? $matches[2] : $matches[1]; $result = phutil_tag( 'tt', array( 'class' => 'remarkup-monospaced', ), $match); } return $this->getEngine()->storeText($result); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupEvalRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupEvalRule.php
<?php final class PhutilRemarkupEvalRule extends PhutilRemarkupRule { const KEY_EVAL = 'eval'; public function getPriority() { return 50; } public function apply($text) { return preg_replace_callback( '/\${{{(.+?)}}}/', array($this, 'newExpressionToken'), $text); } public function newExpressionToken(array $matches) { $expression = $matches[1]; if (!$this->isFlatText($expression)) { return $matches[0]; } $engine = $this->getEngine(); $token = $engine->storeText($expression); $list_key = self::KEY_EVAL; $expression_list = $engine->getTextMetadata($list_key, array()); $expression_list[] = array( 'token' => $token, 'expression' => $expression, 'original' => $matches[0], ); $engine->setTextMetadata($list_key, $expression_list); return $token; } public function didMarkupText() { $engine = $this->getEngine(); $list_key = self::KEY_EVAL; $expression_list = $engine->getTextMetadata($list_key, array()); foreach ($expression_list as $expression_item) { $token = $expression_item['token']; $expression = $expression_item['expression']; $result = $this->evaluateExpression($expression); if ($result === null) { $result = $expression_item['original']; } $engine->overwriteStoredText($token, $result); } } private function evaluateExpression($expression) { static $string_map; if ($string_map === null) { $string_map = array( 'strings' => array( 'platform' => array( 'server' => array( 'name' => PlatformSymbols::getPlatformServerName(), 'path' => pht('phabricator/'), ), 'client' => array( 'name' => PlatformSymbols::getPlatformClientName(), 'path' => pht('arcanist/'), ), ), ), ); } $parts = explode('.', $expression); $cursor = $string_map; foreach ($parts as $part) { if (isset($cursor[$part])) { $cursor = $cursor[$part]; } else { break; } } if (is_string($cursor)) { return $cursor; } return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupBoldRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupBoldRule.php
<?php final class PhutilRemarkupBoldRule extends PhutilRemarkupRule { public function getPriority() { return 1000.0; } public function apply($text) { if ($this->getEngine()->isTextMode()) { return $text; } return $this->replaceHTML( '@\\*\\*(.+?)\\*\\*@s', array($this, 'applyCallback'), $text); } protected function applyCallback(array $matches) { if ($this->getEngine()->isAnchorMode()) { return $matches[1]; } return hsprintf('<strong>%s</strong>', $matches[1]); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupLinebreaksRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupLinebreaksRule.php
<?php final class PhutilRemarkupLinebreaksRule extends PhutilRemarkupRule { public function apply($text) { if ($this->getEngine()->isTextMode()) { return $text; } return phutil_escape_html_newlines($text); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupAnchorRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupAnchorRule.php
<?php final class PhutilRemarkupAnchorRule extends PhutilRemarkupRule { public function getPriority() { return 200.0; } public function apply($text) { return preg_replace_callback( '/{anchor\s+#([^\s}]+)}/s', array($this, 'markupAnchor'), $text); } protected function markupAnchor(array $matches) { $engine = $this->getEngine(); if ($engine->isTextMode()) { return null; } if ($engine->isHTMLMailMode()) { return null; } if ($engine->isAnchorMode()) { return null; } if (!$this->isFlatText($matches[0])) { return $matches[0]; } if (!self::isValidAnchorName($matches[1])) { return $matches[0]; } $tag_view = phutil_tag( 'a', array( 'name' => $matches[1], ), ''); return $this->getEngine()->storeText($tag_view); } public static function isValidAnchorName($anchor_name) { $normal_anchor = self::normalizeAnchor($anchor_name); if ($normal_anchor === $anchor_name) { return true; } return false; } public static function normalizeAnchor($anchor) { // Replace all latin characters which are not "a-z" or "0-9" with "-". // Preserve other characters, since non-latin letters and emoji work // fine in anchors. $anchor = preg_replace('/[\x00-\x2F\x3A-\x60\x7B-\x7F]+/', '-', $anchor); $anchor = trim($anchor, '-'); return $anchor; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupDocumentLinkRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupDocumentLinkRule.php
<?php final class PhutilRemarkupDocumentLinkRule extends PhutilRemarkupRule { public function getPriority() { return 150.0; } public function apply($text) { // Handle mediawiki-style links: [[ href | name ]] $text = preg_replace_callback( '@\B\\[\\[([^|\\]]+)(?:\\|([^\\]]+))?\\]\\]\B@U', array($this, 'markupDocumentLink'), $text); // Handle markdown-style links: [name](href) $text = preg_replace_callback( '@'. '\B'. '\\[([^\\]]+)\\]'. '\\('. '(\s*'. // See T12343. This is making some kind of effort to implement // parenthesis balancing rules. It won't get nested parentheses // right, but should do OK for Wikipedia pages, which seem to be // the most important use case. // Match zero or more non-parenthesis, non-space characters. '[^\s()]*'. // Match zero or more sequences of "(...)", where two balanced // parentheses enclose zero or more normal characters. If we // match some, optionally match more stuff at the end. '(?:(?:\\([^ ()]*\\))+[^\s()]*)?'. '\s*)'. '\\)'. '\B'. '@U', array($this, 'markupAlternateLink'), $text); return $text; } protected function renderHyperlink($link, $name) { $engine = $this->getEngine(); $is_anchor = false; if (strncmp($link, '/', 1) == 0) { $base = phutil_string_cast($engine->getConfig('uri.base')); $base = rtrim($base, '/'); $link = $base.$link; } else if (strncmp($link, '#', 1) == 0) { $here = $engine->getConfig('uri.here'); $link = $here.$link; $is_anchor = true; } if ($engine->isTextMode()) { // If present, strip off "mailto:" or "tel:". $link = preg_replace('/^(?:mailto|tel):/', '', $link); if (!strlen($name)) { return $link; } return $name.' <'.$link.'>'; } if (!strlen($name)) { $name = $link; $name = preg_replace('/^(?:mailto|tel):/', '', $name); } if ($engine->getState('toc')) { return $name; } $same_window = $engine->getConfig('uri.same-window', false); if ($same_window) { $target = null; } else { $target = '_blank'; } // For anchors on the same page, always stay here. if ($is_anchor) { $target = null; } return phutil_tag( 'a', array( 'href' => $link, 'class' => 'remarkup-link', 'target' => $target, 'rel' => 'noreferrer', ), $name); } public function markupAlternateLink(array $matches) { $uri = trim($matches[2]); if (!strlen($uri)) { return $matches[0]; } // NOTE: We apply some special rules to avoid false positives here. The // major concern is that we do not want to convert `x[0][1](y)` in a // discussion about C source code into a link. To this end, we: // // - Don't match at word boundaries; // - require the URI to contain a "/" character or "@" character; and // - reject URIs which being with a quote character. if ($uri[0] == '"' || $uri[0] == "'" || $uri[0] == '`') { return $matches[0]; } if (strpos($uri, '/') === false && strpos($uri, '@') === false && strncmp($uri, 'tel:', 4)) { return $matches[0]; } return $this->markupDocumentLink( array( $matches[0], $matches[2], $matches[1], )); } public function markupDocumentLink(array $matches) { $uri = trim($matches[1]); $name = trim(idx($matches, 2, '')); if (!$this->isFlatText($uri)) { return $matches[0]; } if (!$this->isFlatText($name)) { return $matches[0]; } // If whatever is being linked to begins with "/" or "#", or has "://", // or is "mailto:" or "tel:", treat it as a URI instead of a wiki page. $is_uri = preg_match('@(^/)|(://)|(^#)|(^(?:mailto|tel):)@', $uri); if ($is_uri && strncmp('/', $uri, 1) && strncmp('#', $uri, 1)) { $protocols = $this->getEngine()->getConfig( 'uri.allowed-protocols', array()); try { $protocol = id(new PhutilURI($uri))->getProtocol(); if (!idx($protocols, $protocol)) { // Don't treat this as a URI if it's not an allowed protocol. $is_uri = false; } } catch (Exception $ex) { // We can end up here if we try to parse an ambiguous URI, see // T12796. $is_uri = false; } } // As a special case, skip "[[ / ]]" so that Phriction picks it up as a // link to the Phriction root. It is more useful to be able to use this // syntax to link to the root document than the home page of the install. if ($uri == '/') { $is_uri = false; } if (!$is_uri) { return $matches[0]; } return $this->getEngine()->storeText($this->renderHyperlink($uri, $name)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupEscapeRemarkupRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupEscapeRemarkupRule.php
<?php final class PhutilRemarkupEscapeRemarkupRule extends PhutilRemarkupRule { public function getPriority() { return 0; } public function apply($text) { if (strpos($text, "\1") === false) { return $text; } $replace = $this->getEngine()->storeText("\1"); return str_replace("\1", $replace, $text); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupHyperlinkEngineExtension.php
src/infrastructure/markup/markuprule/PhutilRemarkupHyperlinkEngineExtension.php
<?php abstract class PhutilRemarkupHyperlinkEngineExtension extends Phobject { private $engine; final public function getHyperlinkEngineKey() { return $this->getPhobjectClassConstant('LINKENGINEKEY', 32); } final public static function getAllLinkEngines() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getHyperlinkEngineKey') ->execute(); } final public function setEngine(PhutilRemarkupEngine $engine) { $this->engine = $engine; return $this; } final public function getEngine() { return $this->engine; } abstract public function processHyperlinks(array $hyperlinks); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/markuprule/PhutilRemarkupItalicRule.php
src/infrastructure/markup/markuprule/PhutilRemarkupItalicRule.php
<?php final class PhutilRemarkupItalicRule extends PhutilRemarkupRule { public function getPriority() { return 1000.0; } public function apply($text) { if ($this->getEngine()->isTextMode()) { return $text; } return $this->replaceHTML( '@(?<!:)//(.+?)//@s', array($this, 'applyCallback'), $text); } protected function applyCallback(array $matches) { return hsprintf('<em>%s</em>', $matches[1]); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/view/PHUIRemarkupView.php
src/infrastructure/markup/view/PHUIRemarkupView.php
<?php /** * Simple API for rendering blocks of Remarkup. * * Example usage: * * $fancy_text = new PHUIRemarkupView($viewer, $raw_remarkup); * $view->appendChild($fancy_text); * */ final class PHUIRemarkupView extends AphrontView { private $corpus; private $contextObject; private $options; private $oneoff; private $generateTableOfContents; // TODO: In the long run, rules themselves should define available options. // For now, just define constants here so we can more easily replace things // later once this is cleaned up. const OPTION_PRESERVE_LINEBREAKS = 'preserve-linebreaks'; const OPTION_GENERATE_TOC = 'header.generate-toc'; public function __construct(PhabricatorUser $viewer, $corpus) { $this->setUser($viewer); $this->corpus = $corpus; } public function setContextObject($context_object) { $this->contextObject = $context_object; return $this; } public function getContextObject() { return $this->contextObject; } public function setRemarkupOption($key, $value) { $this->options[$key] = $value; return $this; } public function setRemarkupOptions(array $options) { foreach ($options as $key => $value) { $this->setRemarkupOption($key, $value); } return $this; } public function setGenerateTableOfContents($generate) { $this->generateTableOfContents = $generate; return $this; } public function getGenerateTableOfContents() { return $this->generateTableOfContents; } public function getTableOfContents() { return $this->oneoff->getTableOfContents(); } public function render() { $viewer = $this->getViewer(); $corpus = $this->corpus; $context = $this->getContextObject(); $options = $this->options; $oneoff = id(new PhabricatorMarkupOneOff()) ->setContent($corpus) ->setContentCacheFragment($this->getContentCacheFragment()); if ($options) { $oneoff->setEngine($this->getEngine()); } else { $oneoff->setPreserveLinebreaks(true); } $generate_toc = $this->getGenerateTableOfContents(); $oneoff->setGenerateTableOfContents($generate_toc); $this->oneoff = $oneoff; $content = PhabricatorMarkupEngine::renderOneObject( $oneoff, 'default', $viewer, $context); return $content; } private function getEngine() { $options = $this->options; $viewer = $this->getViewer(); $viewer_key = $viewer->getCacheFragment(); $engine_key = $this->getEngineCacheFragment(); $cache = PhabricatorCaches::getRequestCache(); $cache_key = "remarkup.engine({$viewer_key}, {$engine_key})"; $engine = $cache->getKey($cache_key); if (!$engine) { $engine = PhabricatorMarkupEngine::newMarkupEngine($options); $cache->setKey($cache_key, $engine); } return $engine; } private function getEngineCacheFragment() { $options = $this->options; ksort($options); $engine_key = serialize($options); $engine_key = PhabricatorHash::digestForIndex($engine_key); return $engine_key; } private function getContentCacheFragment() { $corpus = $this->corpus; $content_fragment = PhabricatorHash::digestForIndex($corpus); $options_fragment = array( 'toc' => $this->getGenerateTableOfContents(), ); $options_fragment = serialize($options_fragment); $options_fragment = PhabricatorHash::digestForIndex($options_fragment); return "remarkup({$content_fragment}, {$options_fragment})"; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/view/PHUIRemarkupImageView.php
src/infrastructure/markup/view/PHUIRemarkupImageView.php
<?php final class PHUIRemarkupImageView extends AphrontView { private $uri; private $width; private $height; private $alt; private $classes = array(); public function setURI($uri) { $this->uri = $uri; return $this; } public function getURI() { return $this->uri; } public function setWidth($width) { $this->width = $width; return $this; } public function getWidth() { return $this->width; } public function setHeight($height) { $this->height = $height; return $this; } public function getHeight() { return $this->height; } public function setAlt($alt) { $this->alt = $alt; return $this; } public function getAlt() { return $this->alt; } public function addClass($class) { $this->classes[] = $class; return $this; } public function render() { $id = celerity_generate_unique_node_id(); Javelin::initBehavior( 'remarkup-load-image', array( 'uri' => (string)$this->uri, 'imageID' => $id, )); $classes = null; if ($this->classes) { $classes = implode(' ', $this->classes); } return phutil_tag( 'img', array( 'id' => $id, 'width' => $this->getWidth(), 'height' => $this->getHeight(), 'alt' => $this->getAlt(), 'class' => $classes, )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupLiteralBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupLiteralBlockRule.php
<?php final class PhutilRemarkupLiteralBlockRule extends PhutilRemarkupBlockRule { public function getPriority() { return 450; } public function getMatchingLineCount(array $lines, $cursor) { // NOTE: We're consuming all continguous blocks of %%% literals, so this: // // %%%a%%% // %%%b%%% // // ...is equivalent to: // // %%%a // b%%% // // If they are separated by a blank newline, they are parsed as two // different blocks. This more clearly represents the original text in the // output text and assists automated escaping of blocks coming into the // system. $start_pattern = '(^\s*%%%)'; $end_pattern = '(%%%\s*$)'; $trivial_pattern = '(^\s*%%%\s*$)'; if (!preg_match($start_pattern, $lines[$cursor])) { return 0; } $start_cursor = $cursor; $found_empty = false; $block_start = null; while (true) { if (!isset($lines[$cursor])) { break; } $line = $lines[$cursor]; if ($block_start === null) { $is_start = preg_match($start_pattern, $line); // If we've matched a block and then consumed one or more empty lines // after it, stop merging more blocks into the match. if ($found_empty) { break; } if ($is_start) { $block_start = $cursor; } } if ($block_start !== null) { $is_end = preg_match($end_pattern, $line); // If a line contains only "%%%", it will match both the start and // end patterns, but it only counts as a block start. if ($is_end && ($cursor === $block_start)) { $is_trivial = preg_match($trivial_pattern, $line); if ($is_trivial) { $is_end = false; } } if ($is_end) { $block_start = null; $cursor++; continue; } } if ($block_start === null) { if (strlen(trim($line))) { break; } $found_empty = true; } $cursor++; } return ($cursor - $start_cursor); } public function markupText($text, $children) { $text = rtrim($text); $text = phutil_split_lines($text, $retain_endings = true); foreach ($text as $key => $line) { $line = preg_replace('/^\s*%%%/', '', $line); $line = preg_replace('/%%%(\s*)\z/', '\1', $line); $text[$key] = $line; } if ($this->getEngine()->isTextMode()) { return implode('', $text); } return phutil_tag( 'p', array( 'class' => 'remarkup-literal', ), phutil_implode_html(phutil_tag('br', array()), $text)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupBlockRule.php
<?php abstract class PhutilRemarkupBlockRule extends Phobject { private $engine; private $rules = array(); /** * Determine the order in which blocks execute. Blocks with smaller priority * numbers execute sooner than blocks with larger priority numbers. The * default priority for blocks is `500`. * * Priorities are used to disambiguate syntax which can match multiple * patterns. For example, ` - Lorem ipsum...` may be a code block or a * list. * * @return int Priority at which this block should execute. */ public function getPriority() { return 500; } final public function getPriorityVector() { return id(new PhutilSortVector()) ->addInt($this->getPriority()) ->addString(get_class($this)); } abstract public function markupText($text, $children); /** * This will get an array of unparsed lines and return the number of lines * from the first array value that it can parse. * * @param array $lines * @param int $cursor * * @return int */ abstract public function getMatchingLineCount(array $lines, $cursor); protected function didMarkupText() { return; } public function willMarkupChildBlocks() { return; } public function didMarkupChildBlocks() { return; } final public function setEngine(PhutilRemarkupEngine $engine) { $this->engine = $engine; $this->updateRules(); return $this; } final protected function getEngine() { return $this->engine; } public function setMarkupRules(array $rules) { assert_instances_of($rules, 'PhutilRemarkupRule'); $this->rules = $rules; $this->updateRules(); return $this; } private function updateRules() { $engine = $this->getEngine(); if ($engine) { $this->rules = msort($this->rules, 'getPriority'); foreach ($this->rules as $rule) { $rule->setEngine($engine); } } return $this; } final public function getMarkupRules() { return $this->rules; } final public function postprocess() { $this->didMarkupText(); } final protected function applyRules($text) { foreach ($this->getMarkupRules() as $rule) { $text = $rule->apply($text); } return $text; } public function supportsChildBlocks() { return false; } public function extractChildText($text) { throw new PhutilMethodNotImplementedException(); } protected function renderRemarkupTable(array $out_rows) { assert_instances_of($out_rows, 'array'); if ($this->getEngine()->isTextMode()) { $lengths = array(); foreach ($out_rows as $r => $row) { foreach ($row['content'] as $c => $cell) { $text = $this->getEngine()->restoreText($cell['content']); $lengths[$c][$r] = phutil_utf8_strlen($text); } } $max_lengths = array_map('max', $lengths); $out = array(); foreach ($out_rows as $r => $row) { $headings = false; foreach ($row['content'] as $c => $cell) { $length = $max_lengths[$c] - $lengths[$c][$r]; $out[] = '| '.$cell['content'].str_repeat(' ', $length).' '; if ($cell['type'] == 'th') { $headings = true; } } $out[] = "|\n"; if ($headings) { foreach ($row['content'] as $c => $cell) { $char = ($cell['type'] == 'th' ? '-' : ' '); $out[] = '| '.str_repeat($char, $max_lengths[$c]).' '; } $out[] = "|\n"; } } return rtrim(implode('', $out), "\n"); } if ($this->getEngine()->isHTMLMailMode()) { $table_attributes = array( 'style' => 'border-collapse: separate; border-spacing: 1px; background: #d3d3d3; margin: 12px 0;', ); $cell_attributes = array( 'style' => 'background: #ffffff; padding: 3px 6px;', ); } else { $table_attributes = array( 'class' => 'remarkup-table', ); $cell_attributes = array(); } $out = array(); $out[] = "\n"; foreach ($out_rows as $row) { $cells = array(); foreach ($row['content'] as $cell) { $cells[] = phutil_tag( $cell['type'], $cell_attributes, $cell['content']); } $out[] = phutil_tag($row['type'], array(), $cells); $out[] = "\n"; } $table = phutil_tag('table', $table_attributes, $out); return phutil_tag_div('remarkup-table-wrap', $table); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupHeaderBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupHeaderBlockRule.php
<?php final class PhutilRemarkupHeaderBlockRule extends PhutilRemarkupBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; if (preg_match('/^(={1,5}|#{2,5}|# ).*+$/', $lines[$cursor])) { $num_lines = 1; } else { if (isset($lines[$cursor + 1])) { $line = $lines[$cursor].$lines[$cursor + 1]; if (preg_match('/^([^\n]+)\n[-=]{2,}\s*$/', $line)) { $num_lines = 2; $cursor++; } } } if ($num_lines) { $cursor++; while (isset($lines[$cursor]) && !strlen(trim($lines[$cursor]))) { $num_lines++; $cursor++; } } return $num_lines; } const KEY_HEADER_TOC = 'headers.toc'; public function markupText($text, $children) { $text = trim($text); $lines = phutil_split_lines($text); if (count($lines) > 1) { $level = ($lines[1][0] == '=') ? 1 : 2; $text = trim($lines[0]); } else { $level = 0; for ($ii = 0; $ii < min(5, strlen($text)); $ii++) { if ($text[$ii] == '=' || $text[$ii] == '#') { ++$level; } else { break; } } $text = trim($text, ' =#'); } $engine = $this->getEngine(); if ($engine->isTextMode()) { $char = ($level == 1) ? '=' : '-'; return $text."\n".str_repeat($char, phutil_utf8_strlen($text)); } $use_anchors = $engine->getConfig('header.generate-toc'); $anchor = null; if ($use_anchors) { $anchor = $this->generateAnchor($level, $text); } $text = phutil_tag( 'h'.($level + 1), array( 'class' => 'remarkup-header', ), array($anchor, $this->applyRules($text))); return $text; } private function generateAnchor($level, $text) { $engine = $this->getEngine(); // When a document contains a link inside a header, like this: // // = [[ http://wwww.example.com/ | example ]] = // // ...we want to generate a TOC entry with just "example", but link the // header itself. We push the 'toc' state so all the link rules generate // just names. $engine->pushState('toc'); $plain_text = $text; $plain_text = $this->applyRules($plain_text); $plain_text = $engine->restoreText($plain_text); $engine->popState('toc'); $anchor = self::getAnchorNameFromHeaderText($plain_text); if (!strlen($anchor)) { return null; } $base = $anchor; $key = self::KEY_HEADER_TOC; $anchors = $engine->getTextMetadata($key, array()); $suffix = 1; while (isset($anchors[$anchor])) { $anchor = $base.'-'.$suffix; $anchor = trim($anchor, '-'); $suffix++; } $anchors[$anchor] = array($level, $plain_text); $engine->setTextMetadata($key, $anchors); return phutil_tag( 'a', array( 'name' => $anchor, ), ''); } public static function renderTableOfContents(PhutilRemarkupEngine $engine) { $key = self::KEY_HEADER_TOC; $anchors = $engine->getTextMetadata($key, array()); if (count($anchors) < 2) { // Don't generate a TOC if there are no headers, or if there's only // one header (since such a TOC would be silly). return null; } $depth = 0; $toc = array(); foreach ($anchors as $anchor => $info) { list($level, $name) = $info; while ($depth < $level) { $toc[] = hsprintf('<ul>'); $depth++; } while ($depth > $level) { $toc[] = hsprintf('</ul>'); $depth--; } $toc[] = phutil_tag( 'li', array(), phutil_tag( 'a', array( 'href' => '#'.$anchor, ), $name)); } while ($depth > 0) { $toc[] = hsprintf('</ul>'); $depth--; } return phutil_implode_html("\n", $toc); } public static function getAnchorNameFromHeaderText($text) { $anchor = phutil_utf8_strtolower($text); $anchor = PhutilRemarkupAnchorRule::normalizeAnchor($anchor); // Truncate the fragment to something reasonable. $anchor = id(new PhutilUTF8StringTruncator()) ->setMaximumGlyphs(32) ->setTerminator('') ->truncateString($anchor); // If the fragment is terminated by a word which "The U.S. Government // Printing Office Style Manual" normally discourages capitalizing in // titles, discard it. This is an arbitrary heuristic intended to avoid // awkward hanging words in anchors. $anchor = preg_replace( '/-(a|an|the|at|by|for|in|of|on|per|to|up|and|as|but|if|or|nor)\z/', '', $anchor); return $anchor; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupSimpleTableBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupSimpleTableBlockRule.php
<?php final class PhutilRemarkupSimpleTableBlockRule extends PhutilRemarkupBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; while (isset($lines[$cursor])) { if (preg_match('/^(\s*\|.*+\n?)+$/', $lines[$cursor])) { $num_lines++; $cursor++; } else { break; } } return $num_lines; } public function markupText($text, $children) { $matches = array(); $rows = array(); foreach (explode("\n", $text) as $line) { // Ignore ending delimiters. $line = rtrim($line, '|'); // NOTE: The complexity in this regular expression allows us to match // a table like "| a | [[ href | b ]] | c |". preg_match_all( '/\|'. '('. '(?:'. '(?:\\[\\[.*?\\]\\])'. // [[ ... | ... ]], a link '|'. '(?:[^|[]+)'. // Anything but "|" or "[". '|'. '(?:\\[[^\\|[])'. // "[" followed by anything but "[" or "|" ')*'. ')/', $line, $matches); $any_header = false; $any_content = false; $cells = array(); foreach ($matches[1] as $cell) { $cell = trim($cell); // If this row only has empty cells and "--" cells, and it has at // least one "--" cell, it's marking the rows above as <th> cells // instead of <td> cells. // If it has other types of cells, it's always a content row. // If it has only empty cells, it's an empty row. if (strlen($cell)) { if (preg_match('/^--+\z/', $cell)) { $any_header = true; } else { $any_content = true; } } $cells[] = array('type' => 'td', 'content' => $this->applyRules($cell)); } $is_header = ($any_header && !$any_content); if (!$is_header) { $rows[] = array('type' => 'tr', 'content' => $cells); } else if ($rows) { // Mark previous row with headings. foreach ($cells as $i => $cell) { if ($cell['content']) { $last_key = last_key($rows); if (!isset($rows[$last_key]['content'][$i])) { // If this row has more cells than the previous row, there may // not be a cell above this one to turn into a <th />. continue; } $rows[$last_key]['content'][$i]['type'] = 'th'; } } } } if (!$rows) { return $this->applyRules($text); } return $this->renderRemarkupTable($rows); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupInlineBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupInlineBlockRule.php
<?php final class PhutilRemarkupInlineBlockRule extends PhutilRemarkupBlockRule { public function getMatchingLineCount(array $lines, $cursor) { return 1; } public function markupText($text, $children) { return $this->applyRules($text); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupHorizontalRuleBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupHorizontalRuleBlockRule.php
<?php final class PhutilRemarkupHorizontalRuleBlockRule extends PhutilRemarkupBlockRule { /** * This rule executes at priority `300`, so it can preempt the list block * rule and claim blocks which begin `---`. */ public function getPriority() { return 300; } public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; $pattern = '/^\s*(?:_{3,}|\*\s?\*\s?\*(\s|\*)*|\-\s?\-\s?\-(\s|\-)*)$/'; if (preg_match($pattern, rtrim($lines[$cursor], "\n\r"))) { $num_lines++; $cursor++; while (isset($lines[$cursor]) && !strlen(trim($lines[$cursor]))) { $num_lines++; $cursor++; } } return $num_lines; } public function markupText($text, $children) { if ($this->getEngine()->isTextMode()) { return rtrim($text); } return phutil_tag('hr', array('class' => 'remarkup-hr')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupDefaultBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupDefaultBlockRule.php
<?php final class PhutilRemarkupDefaultBlockRule extends PhutilRemarkupBlockRule { public function getPriority() { return 750; } public function getMatchingLineCount(array $lines, $cursor) { return 1; } public function markupText($text, $children) { $engine = $this->getEngine(); $text = trim($text); $text = $this->applyRules($text); if ($engine->isTextMode()) { if (!$this->getEngine()->getConfig('preserve-linebreaks')) { $text = preg_replace('/ *\n */', ' ', $text); } return $text; } if ($engine->getConfig('preserve-linebreaks')) { $text = phutil_escape_html_newlines($text); } if (!strlen($text)) { return null; } $default_attributes = $engine->getConfig('default.p.attributes'); if ($default_attributes) { $attributes = $default_attributes; } else { $attributes = array(); } return phutil_tag('p', $attributes, $text); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupNoteBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupNoteBlockRule.php
<?php final class PhutilRemarkupNoteBlockRule extends PhutilRemarkupBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; if (preg_match($this->getRegEx(), $lines[$cursor])) { $num_lines++; $cursor++; while (isset($lines[$cursor])) { if (trim($lines[$cursor])) { $num_lines++; $cursor++; continue; } break; } } return $num_lines; } public function markupText($text, $children) { $matches = array(); preg_match($this->getRegEx(), $text, $matches); if (idx($matches, 'showword')) { $word = $matches['showword']; $show = true; } else { $word = $matches['hideword']; $show = false; } $class_suffix = phutil_utf8_strtolower($word); // This is the "(IMPORTANT)" or "NOTE:" part. $word_part = rtrim(substr($text, 0, strlen($matches[0]))); // This is the actual text. $text_part = substr($text, strlen($matches[0])); $text_part = $this->applyRules(rtrim($text_part)); $text_mode = $this->getEngine()->isTextMode(); $html_mail_mode = $this->getEngine()->isHTMLMailMode(); if ($text_mode) { return $word_part.' '.$text_part; } if ($show) { $content = array( phutil_tag( 'span', array( 'class' => 'remarkup-note-word', ), $word_part), ' ', $text_part, ); } else { $content = $text_part; } if ($html_mail_mode) { if ($class_suffix == 'important') { $attributes = array( 'style' => 'margin: 16px 0; padding: 12px; border-left: 3px solid #c0392b; background: #f4dddb;', ); } else if ($class_suffix == 'note') { $attributes = array( 'style' => 'margin: 16px 0; padding: 12px; border-left: 3px solid #2980b9; background: #daeaf3;', ); } else if ($class_suffix == 'warning') { $attributes = array( 'style' => 'margin: 16px 0; padding: 12px; border-left: 3px solid #f1c40f; background: #fdf5d4;', ); } } else { $attributes = array( 'class' => 'remarkup-'.$class_suffix, ); } return phutil_tag( 'div', $attributes, $content); } private function getRegEx() { static $regex; if ($regex === null) { $words = array( 'NOTE', 'IMPORTANT', 'WARNING', ); foreach ($words as $k => $word) { $words[$k] = preg_quote($word, '/'); } $words = implode('|', $words); $regex = '/^(?:'. '(?:\((?P<hideword>'.$words.')\))'. '|'. '(?:(?P<showword>'.$words.'):))\s*'. '/'; } return $regex; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupTableBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupTableBlockRule.php
<?php final class PhutilRemarkupTableBlockRule extends PhutilRemarkupBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; if (preg_match('/^\s*<table>/i', $lines[$cursor])) { $num_lines++; $cursor++; while (isset($lines[$cursor])) { $num_lines++; if (preg_match('@</table>\s*$@i', $lines[$cursor])) { break; } $cursor++; } } return $num_lines; } public function markupText($text, $children) { $root = id(new PhutilHTMLParser()) ->parseDocument($text); $nodes = $root->selectChildrenWithTags(array('table')); $out = array(); $seen_table = false; foreach ($nodes as $node) { if ($node->isContentNode()) { $content = $node->getContent(); if (!strlen(trim($content))) { // Ignore whitespace. continue; } // If we find other content, fail the rule. This can happen if the // input is two consecutive table tags on one line with some text // in between them, which we currently forbid. return $text; } else { // If we have multiple table tags, just return the raw text. if ($seen_table) { return $text; } $seen_table = true; $out[] = $this->newTable($node); } } if ($this->getEngine()->isTextMode()) { return implode('', $out); } else { return phutil_implode_html('', $out); } } private function newTable(PhutilDOMNode $table) { $nodes = $table->selectChildrenWithTags( array( 'colgroup', 'tr', )); $colgroup = null; $rows = array(); foreach ($nodes as $node) { if ($node->isContentNode()) { $content = $node->getContent(); // If this is whitespace, ignore it. if (!strlen(trim($content))) { continue; } // If we have nonempty content between the rows, this isn't a valid // table. We can't really do anything reasonable with this, so just // fail out and render the raw text. return $table->newRawString(); } if ($node->getTagName() === 'colgroup') { // This table has multiple "<colgroup />" tags. Just bail out. if ($colgroup !== null) { return $table->newRawString(); } // This table has a "<colgroup />" after a "<tr />". We could parse // this, but just reject it out of an abundance of caution. if ($rows) { return $table->newRawString(); } $colgroup = $node; continue; } $rows[] = $node; } $row_specs = array(); foreach ($rows as $row) { $cells = $row->selectChildrenWithTags(array('td', 'th')); $cell_specs = array(); foreach ($cells as $cell) { if ($cell->isContentNode()) { $content = $node->getContent(); if ($content === null || !strlen(trim($content))) { continue; } return $table->newRawString(); } // Respect newlines in table cells as literal linebreaks. $content = $cell->newRawContentString(); $content = trim($content, "\r\n"); $lines = phutil_split_lines($content, $retain_endings = false); foreach ($lines as $key => $line) { $lines[$key] = $this->applyRules($line); } $content = phutil_implode_html( phutil_tag('br'), $lines); $cell_specs[] = array( 'type' => $cell->getTagName(), 'content' => $content, ); } $row_specs[] = array( 'type' => 'tr', 'content' => $cell_specs, ); } return $this->renderRemarkupTable($row_specs); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupQuotesBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupQuotesBlockRule.php
<?php final class PhutilRemarkupQuotesBlockRule extends PhutilRemarkupQuotedBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $pos = $cursor; if (preg_match('/^>/', $lines[$pos])) { do { ++$pos; } while (isset($lines[$pos]) && preg_match('/^>/', $lines[$pos])); } return ($pos - $cursor); } public function extractChildText($text) { return array('', $this->normalizeQuotedBody($text)); } public function markupText($text, $children) { if ($this->getEngine()->isTextMode()) { return $this->getQuotedText($children); } $attributes = array(); if ($this->getEngine()->isHTMLMailMode()) { $style = array( 'border-left: 3px solid #a7b5bf;', 'color: #464c5c;', 'font-style: italic;', 'margin: 4px 0 12px 0;', 'padding: 4px 12px;', 'background-color: #f8f9fc;', ); $attributes['style'] = implode(' ', $style); } return phutil_tag( 'blockquote', $attributes, $children); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupTestInterpreterRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupTestInterpreterRule.php
<?php final class PhutilRemarkupTestInterpreterRule extends PhutilRemarkupBlockInterpreter { public function getInterpreterName() { return 'phutil_test_block_interpreter'; } public function markupContent($content, array $argv) { return sprintf( "Content: (%s)\nArgv: (%s)", $content, phutil_build_http_querystring($argv)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupQuotedBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupQuotedBlockRule.php
<?php abstract class PhutilRemarkupQuotedBlockRule extends PhutilRemarkupBlockRule { final public function supportsChildBlocks() { return true; } public function willMarkupChildBlocks() { $engine = $this->getEngine(); $depth = $engine->getQuoteDepth(); $depth = $depth + 1; $engine->setQuoteDepth($depth); } public function didMarkupChildBlocks() { $engine = $this->getEngine(); $depth = $engine->getQuoteDepth(); $depth = $depth - 1; $engine->setQuoteDepth($depth); } final protected function normalizeQuotedBody($text) { $text = phutil_split_lines($text, true); foreach ($text as $key => $line) { $text[$key] = substr($line, 1); } // If every line in the block is empty or begins with at least one leading // space, strip the initial space off each line. When we quote text, we // normally add "> " (with a space) to the beginning of each line, which // can disrupt some other rules. If the block appears to have this space // in front of each line, remove it. $strip_space = true; foreach ($text as $key => $line) { $len = strlen($line); if (!$len) { // We'll still strip spaces if there are some completely empty // lines, they may have just had trailing whitespace trimmed. continue; } // If this line is part of a nested quote block, just ignore it when // realigning this quote block. It's either an author attribution // line with ">>!", or we'll deal with it in a subrule when processing // the nested quote block. if ($line[0] == '>') { continue; } if ($line[0] == ' ' || $line[0] == "\n") { continue; } // The first character of this line is something other than a space, so // we can't strip spaces. $strip_space = false; break; } if ($strip_space) { foreach ($text as $key => $line) { $len = strlen($line); if (!$len) { continue; } if ($line[0] !== ' ') { continue; } $text[$key] = substr($line, 1); } } // Strip leading empty lines. foreach ($text as $key => $line) { if (!strlen(trim($line))) { unset($text[$key]); } else { break; } } return implode('', $text); } final protected function getQuotedText($text) { $text = rtrim($text, "\n"); $no_whitespace = array( // For readability, we render nested quotes as ">> quack", // not "> > quack". '>' => true, // If the line is empty except for a newline, do not add an // unnecessary dangling space. "\n" => true, ); $text = phutil_split_lines($text, true); foreach ($text as $key => $line) { $c = null; if (isset($line[0])) { $c = $line[0]; } else { $c = null; } if (isset($no_whitespace[$c])) { $text[$key] = '>'.$line; } else { $text[$key] = '> '.$line; } } $text = implode('', $text); return $text; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupBlockInterpreter.php
src/infrastructure/markup/blockrule/PhutilRemarkupBlockInterpreter.php
<?php abstract class PhutilRemarkupBlockInterpreter extends Phobject { private $engine; final public function setEngine($engine) { $this->engine = $engine; return $this; } final public function getEngine() { return $this->engine; } /** * @return string */ abstract public function getInterpreterName(); abstract public function markupContent($content, array $argv); protected function markupError($string) { if ($this->getEngine()->isTextMode()) { return '('.$string.')'; } else { return phutil_tag( 'div', array( 'class' => 'remarkup-interpreter-error', ), $string); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupInterpreterBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupInterpreterBlockRule.php
<?php final class PhutilRemarkupInterpreterBlockRule extends PhutilRemarkupBlockRule { const START_BLOCK_PATTERN = '/^([\w]+)\s*(?:\(([^)]+)\)\s*)?{{{/'; const END_BLOCK_PATTERN = '/}}}\s*$/'; public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; if (preg_match(self::START_BLOCK_PATTERN, $lines[$cursor])) { $num_lines++; while (isset($lines[$cursor])) { if (preg_match(self::END_BLOCK_PATTERN, $lines[$cursor])) { break; } $num_lines++; $cursor++; } } return $num_lines; } public function markupText($text, $children) { $lines = explode("\n", $text); $first_key = head_key($lines); $last_key = last_key($lines); while (trim($lines[$last_key]) === '') { unset($lines[$last_key]); $last_key = last_key($lines); } $matches = null; preg_match(self::START_BLOCK_PATTERN, head($lines), $matches); $argv = array(); if (isset($matches[2])) { $argv = id(new PhutilSimpleOptions())->parse($matches[2]); } $interpreters = id(new PhutilClassMapQuery()) ->setAncestorClass('PhutilRemarkupBlockInterpreter') ->execute(); foreach ($interpreters as $interpreter) { $interpreter->setEngine($this->getEngine()); } $lines[$first_key] = preg_replace( self::START_BLOCK_PATTERN, '', $lines[$first_key]); $lines[$last_key] = preg_replace( self::END_BLOCK_PATTERN, '', $lines[$last_key]); if (trim($lines[$first_key]) === '') { unset($lines[$first_key]); } if (trim($lines[$last_key]) === '') { unset($lines[$last_key]); } $content = implode("\n", $lines); $interpreters = mpull($interpreters, null, 'getInterpreterName'); if (isset($interpreters[$matches[1]])) { return $interpreters[$matches[1]]->markupContent($content, $argv); } $message = pht('No interpreter found: %s', $matches[1]); if ($this->getEngine()->isTextMode()) { return '('.$message.')'; } return phutil_tag( 'div', array( 'class' => 'remarkup-interpreter-error', ), $message); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupReplyBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupReplyBlockRule.php
<?php final class PhutilRemarkupReplyBlockRule extends PhutilRemarkupQuotedBlockRule { public function getPriority() { return 400; } public function getMatchingLineCount(array $lines, $cursor) { $pos = $cursor; if (preg_match('/^>>!/', $lines[$pos])) { do { ++$pos; } while (isset($lines[$pos]) && preg_match('/^>/', $lines[$pos])); } return ($pos - $cursor); } public function extractChildText($text) { $text = phutil_split_lines($text, true); $head = substr(reset($text), 3); $body = array_slice($text, 1); $body = implode('', $body); $body = $this->normalizeQuotedBody($body); return array(trim($head), $body); } public function markupText($text, $children) { $text = $this->applyRules($text); if ($this->getEngine()->isTextMode()) { $children = $this->getQuotedText($children); return $text."\n\n".$children; } if ($this->getEngine()->isHTMLMailMode()) { $block_attributes = array( 'style' => 'border-left: 3px solid #8C98B8; color: #6B748C; font-style: italic; margin: 4px 0 12px 0; padding: 8px 12px; background-color: #F8F9FC;', ); $head_attributes = array( 'style' => 'font-style: normal; padding-bottom: 4px;', ); $reply_attributes = array( 'style' => 'margin: 0; padding: 0; border: 0; color: rgb(107, 116, 140);', ); } else { $block_attributes = array( 'class' => 'remarkup-reply-block', ); $head_attributes = array( 'class' => 'remarkup-reply-head', ); $reply_attributes = array( 'class' => 'remarkup-reply-body', ); } return phutil_tag( 'blockquote', $block_attributes, array( "\n", phutil_tag( 'div', $head_attributes, $text), "\n", phutil_tag( 'div', $reply_attributes, $children), "\n", )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupListBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupListBlockRule.php
<?php final class PhutilRemarkupListBlockRule extends PhutilRemarkupBlockRule { /** * This rule must apply before the Code block rule because it needs to * win blocks which begin ` - Lorem ipsum`. */ public function getPriority() { return 400; } public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; $first_line = $cursor; $is_one_line = false; while (isset($lines[$cursor])) { if (!$num_lines) { if (preg_match(self::START_BLOCK_PATTERN, $lines[$cursor])) { $num_lines++; $cursor++; $is_one_line = true; continue; } } else { if (preg_match(self::CONT_BLOCK_PATTERN, $lines[$cursor])) { $num_lines++; $cursor++; $is_one_line = false; continue; } // Allow lists to continue across multiple paragraphs, as long as lines // are indented or a single empty line separates indented lines. $this_empty = !strlen(trim($lines[$cursor])); $this_indented = preg_match('/^ /', $lines[$cursor]); $next_empty = true; $next_indented = false; if (isset($lines[$cursor + 1])) { $next_empty = !strlen(trim($lines[$cursor + 1])); $next_indented = preg_match('/^ /', $lines[$cursor + 1]); } if ($this_empty || $this_indented) { if (($this_indented && !$this_empty) || ($next_indented && !$next_empty)) { $num_lines++; $cursor++; continue; } } if ($this_empty) { $num_lines++; } } break; } // If this list only has one item in it, and the list marker is "#", and // it's not the last line in the input, parse it as a header instead of a // list. This produces better behavior for alternate Markdown headers. if ($is_one_line) { if (($first_line + $num_lines) < count($lines)) { if (strncmp($lines[$first_line], '#', 1) === 0) { return 0; } } } return $num_lines; } /** * The maximum sub-list depth you can nest to. Avoids silliness and blowing * the stack. */ const MAXIMUM_LIST_NESTING_DEPTH = 12; const START_BLOCK_PATTERN = '@^\s*(?:[-*#]+|([1-9][0-9]*)[.)]|\[\D?\])\s+@'; const CONT_BLOCK_PATTERN = '@^\s*(?:[-*#]+|[0-9]+[.)]|\[\D?\])\s+@'; const STRIP_BLOCK_PATTERN = '@^\s*(?:[-*#]+|[0-9]+[.)])\s*@'; public function markupText($text, $children) { $items = array(); $lines = explode("\n", $text); // We allow users to delimit lists using either differing indentation // levels: // // - a // - b // // ...or differing numbers of item-delimiter characters: // // - a // -- b // // If they use the second style but block-indent the whole list, we'll // get the depth counts wrong for the first item. To prevent this, // un-indent every item by the minimum indentation level for the whole // block before we begin parsing. $regex = self::START_BLOCK_PATTERN; $min_space = PHP_INT_MAX; foreach ($lines as $ii => $line) { $matches = null; if (preg_match($regex, $line)) { $regex = self::CONT_BLOCK_PATTERN; if (preg_match('/^(\s+)/', $line, $matches)) { $space = strlen($matches[1]); } else { $space = 0; } $min_space = min($min_space, $space); } } $regex = self::START_BLOCK_PATTERN; if ($min_space) { foreach ($lines as $key => $line) { if (preg_match($regex, $line)) { $regex = self::CONT_BLOCK_PATTERN; $lines[$key] = substr($line, $min_space); } } } // The input text may have linewraps in it, like this: // // - derp derp derp derp // derp derp derp derp // - blarp blarp blarp blarp // // Group text lines together into list items, stored in $items. So the // result in the above case will be: // // array( // array( // "- derp derp derp derp", // " derp derp derp derp", // ), // array( // "- blarp blarp blarp blarp", // ), // ); $item = array(); $starts_at = null; $regex = self::START_BLOCK_PATTERN; foreach ($lines as $line) { $match = null; if (preg_match($regex, $line, $match)) { if (!$starts_at && !empty($match[1])) { $starts_at = $match[1]; } $regex = self::CONT_BLOCK_PATTERN; if ($item) { $items[] = $item; $item = array(); } } $item[] = $line; } if ($item) { $items[] = $item; } if (!$starts_at) { $starts_at = 1; } // Process each item to normalize the text, remove line wrapping, and // determine its depth (indentation level) and style (ordered vs unordered). // // We preserve consecutive linebreaks and interpret them as paragraph // breaks. // // Given the above example, the processed array will look like: // // array( // array( // 'text' => 'derp derp derp derp derp derp derp derp', // 'depth' => 0, // 'style' => '-', // ), // array( // 'text' => 'blarp blarp blarp blarp', // 'depth' => 0, // 'style' => '-', // ), // ); $has_marks = false; foreach ($items as $key => $item) { // Trim space around newlines, to strip trailing whitespace and formatting // indentation. $item = preg_replace('/ *(\n+) */', '\1', implode("\n", $item)); // Replace single newlines with a space. Preserve multiple newlines as // paragraph breaks. $item = preg_replace('/(?<!\n)\n(?!\n)/', ' ', $item); $item = rtrim($item); if (!strlen($item)) { unset($items[$key]); continue; } $matches = null; if (preg_match('/^\s*([-*#]{2,})/', $item, $matches)) { // Alternate-style indents; use number of list item symbols. $depth = strlen($matches[1]) - 1; } else if (preg_match('/^(\s+)/', $item, $matches)) { // Markdown-style indents; use indent depth. $depth = strlen($matches[1]); } else { $depth = 0; } if (preg_match('/^\s*(?:#|[0-9])/', $item)) { $style = '#'; } else { $style = '-'; } // Strip leading indicators off the item. $text = preg_replace(self::STRIP_BLOCK_PATTERN, '', $item); // Look for "[]", "[ ]", "[*]", "[x]", etc., which we render as a // checkbox. We don't render [1], [2], etc., as checkboxes, as these // are often used as footnotes. $mark = null; $matches = null; if (preg_match('/^\s*\[(\D?)\]\s*/', $text, $matches)) { if (strlen(trim($matches[1]))) { $mark = true; } else { $mark = false; } $has_marks = true; $text = substr($text, strlen($matches[0])); } $items[$key] = array( 'text' => $text, 'depth' => $depth, 'style' => $style, 'mark' => $mark, ); } $items = array_values($items); // Users can create a sub-list by indenting any deeper amount than the // previous list, so these are both valid: // // - a // - b // // - a // - b // // In the former case, we'll have depths (0, 2). In the latter case, depths // (0, 4). We don't actually care about how many spaces there are, only // how many list indentation levels (that is, we want to map both of // those cases to (0, 1), indicating "outermost list" and "first sublist"). // // This is made more complicated because lists at two different indentation // levels might be at the same list level: // // - a // - b // - c // - d // // Here, 'b' and 'd' are at the same list level (2) but different indent // levels (2, 4). // // Users can also create "staircases" like this: // // - a // - b // # c // // While this is silly, we'd like to render it as faithfully as possible. // // In order to do this, we convert the list of nodes into a tree, // normalizing indentation levels and inserting dummy nodes as necessary to // make the tree well-formed. See additional notes at buildTree(). // // In the case above, the result is a tree like this: // // - <null> // - <null> // - a // - b // # c $l = 0; $r = count($items); $tree = $this->buildTree($items, $l, $r, $cur_level = 0); // We may need to open a list on a <null> node, but they do not have // list style information yet. We need to propagate list style information // backward through the tree. In the above example, the tree now looks // like this: // // - <null (style=#)> // - <null (style=-)> // - a // - b // # c $this->adjustTreeStyleInformation($tree); // Finally, we have enough information to render the tree. $out = $this->renderTree($tree, 0, $has_marks, $starts_at); if ($this->getEngine()->isTextMode()) { $out = implode('', $out); $out = rtrim($out, "\n"); $out = preg_replace('/ +$/m', '', $out); return $out; } return phutil_implode_html('', $out); } /** * See additional notes in @{method:markupText}. */ private function buildTree(array $items, $l, $r, $cur_level) { if ($l == $r) { return array(); } if ($cur_level > self::MAXIMUM_LIST_NESTING_DEPTH) { // This algorithm is recursive and we don't need you blowing the stack // with your oh-so-clever 50,000-item-deep list. Cap indentation levels // at a reasonable number and just shove everything deeper up to this // level. $nodes = array(); for ($ii = $l; $ii < $r; $ii++) { $nodes[] = array( 'level' => $cur_level, 'items' => array(), ) + $items[$ii]; } return $nodes; } $min = $l; for ($ii = $r - 1; $ii >= $l; $ii--) { if ($items[$ii]['depth'] <= $items[$min]['depth']) { $min = $ii; } } $min_depth = $items[$min]['depth']; $nodes = array(); if ($min != $l) { $nodes[] = array( 'text' => null, 'level' => $cur_level, 'style' => null, 'mark' => null, 'items' => $this->buildTree($items, $l, $min, $cur_level + 1), ); } $last = $min; for ($ii = $last + 1; $ii < $r; $ii++) { if ($items[$ii]['depth'] == $min_depth) { $nodes[] = array( 'level' => $cur_level, 'items' => $this->buildTree($items, $last + 1, $ii, $cur_level + 1), ) + $items[$last]; $last = $ii; } } $nodes[] = array( 'level' => $cur_level, 'items' => $this->buildTree($items, $last + 1, $r, $cur_level + 1), ) + $items[$last]; return $nodes; } /** * See additional notes in @{method:markupText}. */ private function adjustTreeStyleInformation(array &$tree) { // The effect here is just to walk backward through the nodes at this level // and apply the first style in the list to any empty nodes we inserted // before it. As we go, also recurse down the tree. $style = '-'; for ($ii = count($tree) - 1; $ii >= 0; $ii--) { if ($tree[$ii]['style'] !== null) { // This is the earliest node we've seen with style, so set the // style to its style. $style = $tree[$ii]['style']; } else { // This node has no style, so apply the current style. $tree[$ii]['style'] = $style; } if ($tree[$ii]['items']) { $this->adjustTreeStyleInformation($tree[$ii]['items']); } } } /** * See additional notes in @{method:markupText}. */ private function renderTree( array $tree, $level, $has_marks, $starts_at = 1) { $style = idx(head($tree), 'style'); $out = array(); if (!$this->getEngine()->isTextMode()) { switch ($style) { case '#': $tag = 'ol'; break; case '-': $tag = 'ul'; break; } $start_attr = null; if (ctype_digit(phutil_string_cast($starts_at)) && $starts_at > 1) { $start_attr = hsprintf(' start="%d"', $starts_at); } if ($has_marks) { $out[] = hsprintf( '<%s class="remarkup-list remarkup-list-with-checkmarks"%s>', $tag, $start_attr); } else { $out[] = hsprintf( '<%s class="remarkup-list"%s>', $tag, $start_attr); } $out[] = "\n"; } $number = $starts_at; foreach ($tree as $item) { if ($this->getEngine()->isTextMode()) { if ($item['text'] === null) { // Don't render anything. } else { $indent = str_repeat(' ', 2 * $level); $out[] = $indent; if ($item['mark'] !== null) { if ($item['mark']) { $out[] = '[X] '; } else { $out[] = '[ ] '; } } else { switch ($style) { case '#': $out[] = $number.'. '; $number++; break; case '-': $out[] = '- '; break; } } $parts = preg_split('/\n{2,}/', $item['text']); foreach ($parts as $key => $part) { if ($key != 0) { $out[] = "\n\n ".$indent; } $out[] = $this->applyRules($part); } $out[] = "\n"; } } else { if ($item['text'] === null) { $out[] = hsprintf('<li class="remarkup-list-item phantom-item">'); } else { if ($item['mark'] !== null) { if ($item['mark'] == true) { $out[] = hsprintf( '<li class="remarkup-list-item remarkup-checked-item">'); } else { $out[] = hsprintf( '<li class="remarkup-list-item remarkup-unchecked-item">'); } $out[] = phutil_tag( 'input', array( 'type' => 'checkbox', 'checked' => ($item['mark'] ? 'checked' : null), 'disabled' => 'disabled', )); $out[] = ' '; } else { $out[] = hsprintf('<li class="remarkup-list-item">'); } $parts = preg_split('/\n{2,}/', $item['text']); foreach ($parts as $key => $part) { if ($key != 0) { $out[] = array( "\n", phutil_tag('br'), phutil_tag('br'), "\n", ); } $out[] = $this->applyRules($part); } } } if ($item['items']) { $subitems = $this->renderTree($item['items'], $level + 1, $has_marks); foreach ($subitems as $i) { $out[] = $i; } } if (!$this->getEngine()->isTextMode()) { $out[] = hsprintf("</li>\n"); } } if (!$this->getEngine()->isTextMode()) { switch ($style) { case '#': $out[] = hsprintf('</ol>'); break; case '-': $out[] = hsprintf('</ul>'); break; } } return $out; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/blockrule/PhutilRemarkupCodeBlockRule.php
src/infrastructure/markup/blockrule/PhutilRemarkupCodeBlockRule.php
<?php final class PhutilRemarkupCodeBlockRule extends PhutilRemarkupBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; $match_ticks = null; if (preg_match('/^(\s{2,}).+/', $lines[$cursor])) { $match_ticks = false; } else if (preg_match('/^\s*(```)/', $lines[$cursor])) { $match_ticks = true; } else { return $num_lines; } $num_lines++; if ($match_ticks && preg_match('/^\s*(```)(.*)(```)\s*$/', $lines[$cursor])) { return $num_lines; } $cursor++; while (isset($lines[$cursor])) { if ($match_ticks) { if (preg_match('/```\s*$/', $lines[$cursor])) { $num_lines++; break; } $num_lines++; } else { if (strlen(trim($lines[$cursor]))) { if (!preg_match('/^\s{2,}/', $lines[$cursor])) { break; } } $num_lines++; } $cursor++; } return $num_lines; } public function markupText($text, $children) { if (preg_match('/^\s*```/', $text)) { // If this is a ```-style block, trim off the backticks and any leading // blank line. $text = preg_replace('/^\s*```(\s*\n)?/', '', $text); $text = preg_replace('/```\s*$/', '', $text); } $lines = explode("\n", $text); while ($lines && !strlen(last($lines))) { unset($lines[last_key($lines)]); } $options = array( 'counterexample' => false, 'lang' => null, 'name' => null, 'lines' => null, ); $parser = new PhutilSimpleOptions(); $custom = $parser->parse(head($lines)); if ($custom) { $valid = true; foreach ($custom as $key => $value) { if (!array_key_exists($key, $options)) { $valid = false; break; } } if ($valid) { array_shift($lines); $options = $custom + $options; } } // Normalize the text back to a 0-level indent. $min_indent = 80; foreach ($lines as $line) { for ($ii = 0; $ii < strlen($line); $ii++) { if ($line[$ii] != ' ') { $min_indent = min($ii, $min_indent); break; } } } $text = implode("\n", $lines); if ($min_indent) { $indent_string = str_repeat(' ', $min_indent); $text = preg_replace('/^'.$indent_string.'/m', '', $text); } if ($this->getEngine()->isTextMode()) { $out = array(); $header = array(); if ($options['counterexample']) { $header[] = 'counterexample'; } if ($options['name'] != '') { $header[] = 'name='.$options['name']; } if ($header) { $out[] = implode(', ', $header); } $text = preg_replace('/^/m', ' ', $text); $out[] = $text; return implode("\n", $out); } if (empty($options['lang'])) { // If the user hasn't specified "lang=..." explicitly, try to guess the // language. If we fail, fall back to configured defaults. $lang = PhutilLanguageGuesser::guessLanguage($text); if (!$lang) { $lang = nonempty( $this->getEngine()->getConfig('phutil.codeblock.language-default'), 'text'); } $options['lang'] = $lang; } $code_body = $this->highlightSource($text, $options); $name_header = null; $block_style = null; if ($this->getEngine()->isHTMLMailMode()) { $map = $this->getEngine()->getConfig('phutil.codeblock.style-map'); if ($map) { $raw_body = id(new PhutilPygmentizeParser()) ->setMap($map) ->parse((string)$code_body); $code_body = phutil_safe_html($raw_body); } $style_rules = array( 'padding: 6px 12px;', 'font-size: 13px;', 'font-weight: bold;', 'display: inline-block;', 'border-top-left-radius: 3px;', 'border-top-right-radius: 3px;', 'color: rgba(0,0,0,.75);', ); if ($options['counterexample']) { $style_rules[] = 'background: #f7e6e6'; } else { $style_rules[] = 'background: rgba(71, 87, 120, 0.08);'; } $header_attributes = array( 'style' => implode(' ', $style_rules), ); $block_style = 'margin: 12px 0;'; } else { $header_attributes = array( 'class' => 'remarkup-code-header', ); } if ($options['name']) { $name_header = phutil_tag( 'div', $header_attributes, $options['name']); } $class = 'remarkup-code-block'; if ($options['counterexample']) { $class = 'remarkup-code-block code-block-counterexample'; } $attributes = array( 'class' => $class, 'style' => $block_style, 'data-code-lang' => $options['lang'], 'data-sigil' => 'remarkup-code-block', ); return phutil_tag( 'div', $attributes, array($name_header, $code_body)); } private function highlightSource($text, array $options) { if ($options['counterexample']) { $aux_class = ' remarkup-counterexample'; } else { $aux_class = null; } $aux_style = null; if ($this->getEngine()->isHTMLMailMode()) { $aux_style = array( 'font: 11px/15px "Menlo", "Consolas", "Monaco", monospace;', 'padding: 12px;', 'margin: 0;', ); if ($options['counterexample']) { $aux_style[] = 'background: #f7e6e6;'; } else { $aux_style[] = 'background: rgba(71, 87, 120, 0.08);'; } $aux_style = implode(' ', $aux_style); } if ($options['lines']) { // Put a minimum size on this because the scrollbar is otherwise // unusable. $height = max(6, (int)$options['lines']); $aux_style = $aux_style .' ' .'max-height: ' .(2 * $height) .'em; overflow: auto;'; } $engine = $this->getEngine()->getConfig('syntax-highlighter.engine'); if (!$engine) { $engine = 'PhutilDefaultSyntaxHighlighterEngine'; } $engine = newv($engine, array()); $engine->setConfig( 'pygments.enabled', $this->getEngine()->getConfig('pygments.enabled')); return phutil_tag( 'pre', array( 'class' => 'remarkup-code'.$aux_class, 'style' => $aux_style, ), PhutilSafeHTML::applyFunction( 'rtrim', $engine->highlightSource($options['lang'], $text))); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/engine/PhutilSyntaxHighlighterEngine.php
src/infrastructure/markup/syntax/engine/PhutilSyntaxHighlighterEngine.php
<?php abstract class PhutilSyntaxHighlighterEngine extends Phobject { abstract public function setConfig($key, $value); abstract public function getHighlightFuture($language, $source); abstract public function getLanguageFromFilename($filename); final public function highlightSource($language, $source) { try { return $this->getHighlightFuture($language, $source)->resolve(); } catch (PhutilSyntaxHighlighterException $ex) { return id(new PhutilDefaultSyntaxHighlighter()) ->getHighlightFuture($source) ->resolve(); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/engine/PhutilDefaultSyntaxHighlighterEngine.php
src/infrastructure/markup/syntax/engine/PhutilDefaultSyntaxHighlighterEngine.php
<?php final class PhutilDefaultSyntaxHighlighterEngine extends PhutilSyntaxHighlighterEngine { private $config = array(); public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getLanguageFromFilename($filename) { static $default_map = array( // All files which have file extensions that we haven't already matched // map to their extensions. '@\\.([^./]+)$@' => 1, ); $maps = array(); if (!empty($this->config['filename.map'])) { $maps[] = $this->config['filename.map']; } $maps[] = $default_map; foreach ($maps as $map) { foreach ($map as $regexp => $lang) { $matches = null; if (preg_match($regexp, $filename, $matches)) { if (is_numeric($lang)) { return idx($matches, $lang); } else { return $lang; } } } } return null; } public function getHighlightFuture($language, $source) { if ($language === null) { $language = PhutilLanguageGuesser::guessLanguage($source); } $have_pygments = !empty($this->config['pygments.enabled']); if ($language == 'php' && PhutilXHPASTBinary::isAvailable()) { return id(new PhutilXHPASTSyntaxHighlighter()) ->getHighlightFuture($source); } if ($language == 'console') { return id(new PhutilConsoleSyntaxHighlighter()) ->getHighlightFuture($source); } if ($language == 'diviner' || $language == 'remarkup') { return id(new PhutilDivinerSyntaxHighlighter()) ->getHighlightFuture($source); } if ($language == 'rainbow') { return id(new PhutilRainbowSyntaxHighlighter()) ->getHighlightFuture($source); } if ($language == 'php') { return id(new PhutilLexerSyntaxHighlighter()) ->setConfig('lexer', new PhutilPHPFragmentLexer()) ->setConfig('language', 'php') ->getHighlightFuture($source); } if ($language == 'py' || $language == 'python') { return id(new PhutilLexerSyntaxHighlighter()) ->setConfig('lexer', new PhutilPythonFragmentLexer()) ->setConfig('language', 'py') ->getHighlightFuture($source); } if ($language == 'java') { return id(new PhutilLexerSyntaxHighlighter()) ->setConfig('lexer', new PhutilJavaFragmentLexer()) ->setConfig('language', 'java') ->getHighlightFuture($source); } if ($language == 'json') { return id(new PhutilLexerSyntaxHighlighter()) ->setConfig('lexer', new PhutilJSONFragmentLexer()) ->getHighlightFuture($source); } if ($language == 'invisible') { return id(new PhutilInvisibleSyntaxHighlighter()) ->getHighlightFuture($source); } // Don't invoke Pygments for plain text, since it's expensive and has // no effect. if ($language !== 'text' && $language !== 'txt') { if ($have_pygments) { return id(new PhutilPygmentsSyntaxHighlighter()) ->setConfig('language', $language) ->getHighlightFuture($source); } } return id(new PhutilDefaultSyntaxHighlighter()) ->getHighlightFuture($source); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/engine/__tests__/PhutilDefaultSyntaxHighlighterEngineTestCase.php
src/infrastructure/markup/syntax/engine/__tests__/PhutilDefaultSyntaxHighlighterEngineTestCase.php
<?php /** * Test cases for @{class:PhutilDefaultSyntaxHighlighterEngine}. */ final class PhutilDefaultSyntaxHighlighterEngineTestCase extends PhutilTestCase { public function testFilenameGreediness() { $names = array( 'x.php' => 'php', '/x.php' => 'php', 'x.y.php' => 'php', '/x.y/z.php' => 'php', '/x.php/' => null, ); $engine = new PhutilDefaultSyntaxHighlighterEngine(); foreach ($names as $path => $language) { $detect = $engine->getLanguageFromFilename($path); $this->assertEqual( $language, $detect, pht('Language detect for %s', $path)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilDivinerSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilDivinerSyntaxHighlighter.php
<?php /** * Simple syntax highlighter for the ".diviner" format, which is just Remarkup * with a specific ruleset. This should also work alright for Remarkup. */ final class PhutilDivinerSyntaxHighlighter extends Phobject { private $config = array(); private $replaceClass; public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getHighlightFuture($source) { $source = phutil_escape_html($source); // This highlighter isn't perfect but tries to do an okay job at getting // some of the basics at least. There's lots of room for improvement. $blocks = explode("\n\n", $source); foreach ($blocks as $key => $block) { if (preg_match('/^[^ ](?! )/m', $block)) { $blocks[$key] = $this->highlightBlock($block); } } $source = implode("\n\n", $blocks); $source = phutil_safe_html($source); return new ImmediateFuture($source); } private function highlightBlock($source) { // Highlight "@{class:...}" links to other documentation pages. $source = $this->highlightPattern('/@{([\w@]+?):([^}]+?)}/', $source, 'nc'); // Highlight "@title", "@group", etc. $source = $this->highlightPattern('/^@(\w+)/m', $source, 'k'); // Highlight bold, italic and monospace. $source = $this->highlightPattern('@\\*\\*(.+?)\\*\\*@s', $source, 's'); $source = $this->highlightPattern('@(?<!:)//(.+?)//@s', $source, 's'); $source = $this->highlightPattern( '@##([\s\S]+?)##|\B`(.+?)`\B@', $source, 's'); // Highlight stuff that looks like headers. $source = $this->highlightPattern('/^=(.*)$/m', $source, 'nv'); return $source; } private function highlightPattern($regexp, $source, $class) { $this->replaceClass = $class; $source = preg_replace_callback( $regexp, array($this, 'replacePattern'), $source); return $source; } public function replacePattern($matches) { // NOTE: The goal here is to make sure a <span> never crosses a newline. $content = $matches[0]; $content = explode("\n", $content); foreach ($content as $key => $line) { $content[$key] = '<span class="'.$this->replaceClass.'">'. $line. '</span>'; } return implode("\n", $content); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilLexerSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilLexerSyntaxHighlighter.php
<?php final class PhutilLexerSyntaxHighlighter extends PhutilSyntaxHighlighter { private $config = array(); public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getHighlightFuture($source) { $strip = false; $state = 'start'; $lang = idx($this->config, 'language'); if ($lang == 'php') { if (strpos($source, '<?') === false) { $state = 'php'; } } $lexer = idx($this->config, 'lexer'); $tokens = $lexer->getTokens($source, $state); $tokens = $lexer->mergeTokens($tokens); $result = array(); foreach ($tokens as $token) { list($type, $value, $context) = $token; $data_name = null; switch ($type) { case 'nc': case 'nf': case 'na': $data_name = $value; break; } if (strpos($value, "\n") !== false) { $value = explode("\n", $value); } else { $value = array($value); } foreach ($value as $part) { if (strlen($part)) { if ($type) { $result[] = phutil_tag( 'span', array( 'class' => $type, 'data-symbol-context' => $context, 'data-symbol-name' => $data_name, ), $part); } else { $result[] = $part; } } $result[] = "\n"; } // Throw away the last "\n". array_pop($result); } $result = phutil_implode_html('', $result); return new ImmediateFuture($result); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilDefaultSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilDefaultSyntaxHighlighter.php
<?php final class PhutilDefaultSyntaxHighlighter extends Phobject { public function setConfig($key, $value) { return $this; } public function getHighlightFuture($source) { $result = hsprintf('%s', $source); return new ImmediateFuture($result); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilConsoleSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilConsoleSyntaxHighlighter.php
<?php /** * Simple syntax highlighter for console output. We just try to highlight the * commands so it's easier to follow transcripts. */ final class PhutilConsoleSyntaxHighlighter extends Phobject { private $config = array(); public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getHighlightFuture($source) { $in_command = false; $lines = explode("\n", $source); foreach ($lines as $key => $line) { $matches = null; // Parse commands like this: // // some/path/ $ ./bin/example # Do things // // ...into path, command, and comment components. $pattern = '@'. ($in_command ? '()(.*?)' : '^(\S+[\\\\/] )?([$] .*?)'). '(#.*|\\\\)?$@'; if (preg_match($pattern, $line, $matches)) { $lines[$key] = hsprintf( '%s<span class="gp">%s</span>%s', $matches[1], $matches[2], (!empty($matches[3]) ? hsprintf('<span class="k">%s</span>', $matches[3]) : '')); $in_command = (idx($matches, 3) == '\\'); } else { $lines[$key] = hsprintf('<span class="go">%s</span>', $line); } } $lines = phutil_implode_html("\n", $lines); return new ImmediateFuture($lines); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilSyntaxHighlighterException.php
src/infrastructure/markup/syntax/highlighter/PhutilSyntaxHighlighterException.php
<?php final class PhutilSyntaxHighlighterException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilXHPASTSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilXHPASTSyntaxHighlighter.php
<?php final class PhutilXHPASTSyntaxHighlighter extends Phobject { public function getHighlightFuture($source) { $scrub = false; if (strpos($source, '<?') === false) { $source = "<?php\n".$source; $scrub = true; } return new PhutilXHPASTSyntaxHighlighterFuture( PhutilXHPASTBinary::getParserFuture($source), $source, $scrub); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilSyntaxHighlighter.php
<?php abstract class PhutilSyntaxHighlighter extends Phobject { abstract public function setConfig($key, $value); abstract public function getHighlightFuture($source); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilRainbowSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilRainbowSyntaxHighlighter.php
<?php /** * Highlights source code with a rainbow of colors, regardless of the language. * This highlighter is useless, absurd, and extremely slow. */ final class PhutilRainbowSyntaxHighlighter extends Phobject { private $config = array(); public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getHighlightFuture($source) { $color = 0; $colors = array( 'rbw_r', 'rbw_o', 'rbw_y', 'rbw_g', 'rbw_b', 'rbw_i', 'rbw_v', ); $result = array(); foreach (phutil_utf8v($source) as $character) { if ($character == ' ' || $character == "\n") { $result[] = $character; continue; } $result[] = phutil_tag( 'span', array('class' => $colors[$color]), $character); $color = ($color + 1) % count($colors); } $result = phutil_implode_html('', $result); return new ImmediateFuture($result); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilPygmentsSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilPygmentsSyntaxHighlighter.php
<?php final class PhutilPygmentsSyntaxHighlighter extends Phobject { private $config = array(); public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getHighlightFuture($source) { $language = idx($this->config, 'language'); if (preg_match('/\r(?!\n)/', $source)) { // TODO: Pygments converts "\r" newlines into "\n" newlines, so we can't // use it on files with "\r" newlines. If we have "\r" not followed by // "\n" in the file, skip highlighting. $language = null; } if ($language) { $language = $this->getPygmentsLexerNameFromLanguageName($language); // See T13224. Under Ubuntu, avoid leaving an intermedite "dash" shell // process so we hit "pygmentize" directly if we have to SIGKILL this // because it explodes. $future = new ExecFuture( 'exec pygmentize -O encoding=utf-8 -O stripnl=False -f html -l %s', $language); $scrub = false; if ($language == 'php' && strpos($source, '<?') === false) { $source = "<?php\n".$source; $scrub = true; } // See T13224. In some cases, "pygmentize" has explosive runtime on small // inputs. Put a hard cap on how long it is allowed to run for to limit // the amount of damage it can do. $future->setTimeout(15); $future->write($source); return new PhutilDefaultSyntaxHighlighterEnginePygmentsFuture( $future, $source, $scrub); } return id(new PhutilDefaultSyntaxHighlighter()) ->getHighlightFuture($source); } private function getPygmentsLexerNameFromLanguageName($language) { static $map = array( 'adb' => 'ada', 'ads' => 'ada', 'ahkl' => 'ahk', 'as' => 'as3', 'asax' => 'aspx-vb', 'ascx' => 'aspx-vb', 'ashx' => 'aspx-vb', 'ASM' => 'nasm', 'asm' => 'nasm', 'asmx' => 'aspx-vb', 'aspx' => 'aspx-vb', 'autodelegate' => 'myghty', 'autohandler' => 'mason', 'aux' => 'tex', 'axd' => 'aspx-vb', 'b' => 'brainfuck', 'bas' => 'vb.net', 'bf' => 'brainfuck', 'bmx' => 'blitzmax', 'c++' => 'cpp', 'c++-objdump' => 'cpp-objdump', 'cc' => 'cpp', 'cfc' => 'cfm', 'cfg' => 'ini', 'cfml' => 'cfm', 'cl' => 'common-lisp', 'clj' => 'clojure', 'cmd' => 'bat', 'coffee' => 'coffee-script', 'cs' => 'csharp', 'csh' => 'tcsh', 'cw' => 'redcode', 'cxx' => 'cpp', 'cxx-objdump' => 'cpp-objdump', 'darcspatch' => 'dpatch', 'def' => 'modula2', 'dhandler' => 'mason', 'di' => 'd', 'duby' => 'rb', 'dyl' => 'dylan', 'ebuild' => 'bash', 'eclass' => 'bash', 'el' => 'common-lisp', 'eps' => 'postscript', 'erl' => 'erlang', 'erl-sh' => 'erl', 'f' => 'fortran', 'f90' => 'fortran', 'feature' => 'Cucumber', 'fhtml' => 'velocity', 'flx' => 'felix', 'flxh' => 'felix', 'frag' => 'glsl', 'g' => 'antlr-ruby', 'G' => 'antlr-ruby', 'gdc' => 'gooddata-cl', 'gemspec' => 'rb', 'geo' => 'glsl', 'GNUmakefile' => 'make', 'h' => 'c', 'h++' => 'cpp', 'hh' => 'cpp', 'hpp' => 'cpp', 'hql' => 'sql', 'hrl' => 'erlang', 'hs' => 'haskell', 'htaccess' => 'apacheconf', 'htm' => 'html', 'html' => 'html+evoque', 'hxx' => 'cpp', 'hy' => 'hybris', 'hyb' => 'hybris', 'ik' => 'ioke', 'inc' => 'pov', 'j' => 'objective-j', 'jbst' => 'duel', 'kid' => 'genshi', 'ksh' => 'bash', 'less' => 'css', 'lgt' => 'logtalk', 'lisp' => 'common-lisp', 'll' => 'llvm', 'm' => 'objective-c', 'mak' => 'make', 'Makefile' => 'make', 'makefile' => 'make', 'man' => 'groff', 'mao' => 'mako', 'mc' => 'mason', 'md' => 'minid', 'mhtml' => 'mason', 'mi' => 'mason', 'ml' => 'ocaml', 'mli' => 'ocaml', 'mll' => 'ocaml', 'mly' => 'ocaml', 'mm' => 'objective-c', 'mo' => 'modelica', 'mod' => 'modula2', 'moo' => 'moocode', 'mu' => 'mupad', 'myt' => 'myghty', 'ns2' => 'newspeak', 'pas' => 'delphi', 'patch' => 'diff', 'phtml' => 'html+php', 'pl' => 'prolog', 'plot' => 'gnuplot', 'plt' => 'gnuplot', 'pm' => 'perl', 'po' => 'pot', 'pp' => 'puppet', 'pro' => 'prolog', 'proto' => 'protobuf', 'ps' => 'postscript', 'pxd' => 'cython', 'pxi' => 'cython', 'py' => 'python', 'pyw' => 'python', 'pyx' => 'cython', 'R' => 'splus', 'r' => 'rebol', 'r3' => 'rebol', 'rake' => 'rb', 'Rakefile' => 'rb', 'rbw' => 'rb', 'rbx' => 'rb', 'rest' => 'rst', 'rl' => 'ragel-em', 'robot' => 'robotframework', 'Rout' => 'rconsole', 'rss' => 'xml', 's' => 'gas', 'S' => 'splus', 'sc' => 'python', 'scm' => 'scheme', 'SConscript' => 'python', 'SConstruct' => 'python', 'scss' => 'css', 'sh' => 'bash', 'sh-session' => 'console', 'spt' => 'cheetah', 'sqlite3-console' => 'sqlite3', 'st' => 'smalltalk', 'sv' => 'v', 'tac' => 'python', 'tmpl' => 'cheetah', 'toc' => 'tex', 'tpl' => 'smarty', 'txt' => 'text', 'vapi' => 'vala', 'vb' => 'vb.net', 'vert' => 'glsl', 'vhd' => 'vhdl', 'vimrc' => 'vim', 'vm' => 'velocity', 'weechatlog' => 'irc', 'wlua' => 'lua', 'wsdl' => 'xml', 'xhtml' => 'html', 'xml' => 'xml+evoque', 'xqy' => 'xquery', 'xsd' => 'xml', 'xsl' => 'xslt', 'xslt' => 'xml', 'yml' => 'yaml', ); return idx($map, $language, $language); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/PhutilInvisibleSyntaxHighlighter.php
src/infrastructure/markup/syntax/highlighter/PhutilInvisibleSyntaxHighlighter.php
<?php final class PhutilInvisibleSyntaxHighlighter extends Phobject { private $config = array(); public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getHighlightFuture($source) { $keys = array_map('chr', range(0x0, 0x1F)); $vals = array_map( array($this, 'decimalToHtmlEntityDecoded'), range(0x2400, 0x241F)); $invisible = array_combine($keys, $vals); $result = array(); foreach (str_split($source) as $character) { if (isset($invisible[$character])) { $result[] = phutil_tag( 'span', array('class' => 'invisible'), $invisible[$character]); if ($character === "\n") { $result[] = $character; } } else { $result[] = $character; } } $result = phutil_implode_html('', $result); return new ImmediateFuture($result); } private function decimalToHtmlEntityDecoded($dec) { return html_entity_decode("&#{$dec};"); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/xhpast/PhutilXHPASTSyntaxHighlighterFuture.php
src/infrastructure/markup/syntax/highlighter/xhpast/PhutilXHPASTSyntaxHighlighterFuture.php
<?php final class PhutilXHPASTSyntaxHighlighterFuture extends FutureProxy { private $source; private $scrub; public function __construct(Future $proxied, $source, $scrub = false) { parent::__construct($proxied); $this->source = $source; $this->scrub = $scrub; } protected function didReceiveResult($result) { try { return $this->applyXHPHighlight($result); } catch (Exception $ex) { // XHP can't highlight source that isn't syntactically valid. Fall back // to the fragment lexer. $source = ($this->scrub ? preg_replace('/^.*\n/', '', $this->source) : $this->source); return id(new PhutilLexerSyntaxHighlighter()) ->setConfig('lexer', new PhutilPHPFragmentLexer()) ->setConfig('language', 'php') ->getHighlightFuture($source) ->resolve(); } } private function applyXHPHighlight($result) { // We perform two passes here: one using the AST to find symbols we care // about -- particularly, class names and function names. These are used // in the crossreference stuff to link into Diffusion. After we've done our // AST pass, we do a followup pass on the token stream to catch all the // simple stuff like strings and comments. $tree = XHPASTTree::newFromDataAndResolvedExecFuture( $this->source, $result); $root = $tree->getRootNode(); $tokens = $root->getTokens(); $interesting_symbols = $this->findInterestingSymbols($root); if ($this->scrub) { // If we're scrubbing, we prepended "<?php\n" to the text to force the // highlighter to treat it as PHP source. Now, we need to remove that. $ok = false; if (count($tokens) >= 2) { if ($tokens[0]->getTypeName() === 'T_OPEN_TAG') { if ($tokens[1]->getTypeName() === 'T_WHITESPACE') { $ok = true; } } } if (!$ok) { throw new Exception( pht( 'Expected T_OPEN_TAG, T_WHITESPACE tokens at head of results '. 'for highlighting parse of PHP snippet.')); } // Remove the "<?php". unset($tokens[0]); $value = $tokens[1]->getValue(); if ((strlen($value) < 1) || ($value[0] != "\n")) { throw new Exception( pht( 'Expected "\\n" at beginning of T_WHITESPACE token at head of '. 'tokens for highlighting parse of PHP snippet.')); } $value = substr($value, 1); $tokens[1]->overwriteValue($value); } $out = array(); foreach ($tokens as $key => $token) { $value = $token->getValue(); $class = null; $multi = false; $attrs = array(); if (isset($interesting_symbols[$key])) { $sym = $interesting_symbols[$key]; $class = $sym[0]; $attrs['data-symbol-context'] = idx($sym, 'context'); $attrs['data-symbol-name'] = idx($sym, 'symbol'); } else { switch ($token->getTypeName()) { case 'T_WHITESPACE': break; case 'T_DOC_COMMENT': $class = 'dc'; $multi = true; break; case 'T_COMMENT': $class = 'c'; $multi = true; break; case 'T_CONSTANT_ENCAPSED_STRING': case 'T_ENCAPSED_AND_WHITESPACE': case 'T_INLINE_HTML': $class = 's'; $multi = true; break; case 'T_VARIABLE': $class = 'nv'; break; case 'T_OPEN_TAG': case 'T_OPEN_TAG_WITH_ECHO': case 'T_CLOSE_TAG': $class = 'o'; break; case 'T_LNUMBER': case 'T_DNUMBER': $class = 'm'; break; case 'T_STRING': static $magic = array( 'true' => true, 'false' => true, 'null' => true, ); if (isset($magic[strtolower($value)])) { $class = 'k'; break; } $class = 'nx'; break; default: $class = 'k'; break; } } if ($class) { $attrs['class'] = $class; if ($multi) { // If the token may have multiple lines in it, make sure each // <span> crosses no more than one line so the lines can be put // in a table, etc., later. $value = phutil_split_lines($value, $retain_endings = true); } else { $value = array($value); } foreach ($value as $val) { $out[] = phutil_tag('span', $attrs, $val); } } else { $out[] = $value; } } return phutil_implode_html('', $out); } private function findInterestingSymbols(XHPASTNode $root) { // Class name symbols appear in: // class X extends X implements X, X { ... } // new X(); // $x instanceof X // catch (X $x) // function f(X $x) // X::f(); // X::$m; // X::CONST; // These are PHP builtin tokens which can appear in a classname context. // Don't link them since they don't go anywhere useful. static $builtin_class_tokens = array( 'self' => true, 'parent' => true, 'static' => true, ); // Fortunately XHPAST puts all of these in a special node type so it's // easy to find them. $result_map = array(); $class_names = $root->selectDescendantsOfType('n_CLASS_NAME'); foreach ($class_names as $class_name) { foreach ($class_name->getTokens() as $key => $token) { if (isset($builtin_class_tokens[$token->getValue()])) { // This is something like "self::method()". continue; } $result_map[$key] = array( 'nc', // "Name, Class" 'symbol' => $class_name->getConcreteString(), ); } } // Function name symbols appear in: // f() $function_calls = $root->selectDescendantsOfType('n_FUNCTION_CALL'); foreach ($function_calls as $call) { $call = $call->getChildByIndex(0); if ($call->getTypeName() == 'n_SYMBOL_NAME') { // This is a normal function call, not some $f() shenanigans. foreach ($call->getTokens() as $key => $token) { $result_map[$key] = array( 'nf', // "Name, Function" 'symbol' => $call->getConcreteString(), ); } } } // Upon encountering $x->y, link y without context, since $x is unknown. $prop_access = $root->selectDescendantsOfType('n_OBJECT_PROPERTY_ACCESS'); foreach ($prop_access as $access) { $right = $access->getChildByIndex(1); if ($right->getTypeName() == 'n_INDEX_ACCESS') { // otherwise $x->y[0] doesn't get highlighted $right = $right->getChildByIndex(0); } if ($right->getTypeName() == 'n_STRING') { foreach ($right->getTokens() as $key => $token) { $result_map[$key] = array( 'na', // "Name, Attribute" 'symbol' => $right->getConcreteString(), ); } } } // Upon encountering x::y, try to link y with context x. $static_access = $root->selectDescendantsOfType('n_CLASS_STATIC_ACCESS'); foreach ($static_access as $access) { $class = $access->getChildByIndex(0); $right = $access->getChildByIndex(1); if ($class->getTypeName() == 'n_CLASS_NAME' && ($right->getTypeName() == 'n_STRING' || $right->getTypeName() == 'n_VARIABLE')) { $classname = head($class->getTokens())->getValue(); $result = array( 'na', 'symbol' => ltrim($right->getConcreteString(), '$'), ); if (!isset($builtin_class_tokens[$classname])) { $result['context'] = $classname; } foreach ($right->getTokens() as $key => $token) { $result_map[$key] = $result; } } } return $result_map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/__tests__/PhutilJSONFragmentLexerHighlighterTestCase.php
src/infrastructure/markup/syntax/highlighter/__tests__/PhutilJSONFragmentLexerHighlighterTestCase.php
<?php final class PhutilJSONFragmentLexerHighlighterTestCase extends PhutilTestCase { public function testLexer() { $highlighter = id(new PhutilLexerSyntaxHighlighter()) ->setConfig('language', 'json') ->setConfig('lexer', new PhutilJSONFragmentLexer()); $path = dirname(__FILE__).'/data/jsonfragment/'; foreach (Filesystem::listDirectory($path, $include_hidden = false) as $f) { if (preg_match('/.test$/', $f)) { $expect = preg_replace('/.test$/', '.expect', $f); $source = Filesystem::readFile($path.'/'.$f); $this->assertEqual( Filesystem::readFile($path.'/'.$expect), (string)$highlighter->getHighlightFuture($source)->resolve(), $f); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/__tests__/PhutilXHPASTSyntaxHighlighterTestCase.php
src/infrastructure/markup/syntax/highlighter/__tests__/PhutilXHPASTSyntaxHighlighterTestCase.php
<?php final class PhutilXHPASTSyntaxHighlighterTestCase extends PhutilTestCase { private function highlight($source) { $highlighter = new PhutilXHPASTSyntaxHighlighter(); $future = $highlighter->getHighlightFuture($source); return $future->resolve(); } private function read($file) { $path = dirname(__FILE__).'/xhpast/'.$file; return Filesystem::readFile($path); } public function testBuiltinClassnames() { $this->assertEqual( $this->read('builtin-classname.expect'), (string)$this->highlight($this->read('builtin-classname.source')), pht('Builtin classnames should not be marked as linkable symbols.')); $this->assertEqual( rtrim($this->read('trailing-comment.expect')), (string)$this->highlight($this->read('trailing-comment.source')), pht('Trailing comments should not be dropped.')); $this->assertEqual( $this->read('multiline-token.expect'), (string)$this->highlight($this->read('multiline-token.source')), pht('Multi-line tokens should be split across lines.')); $this->assertEqual( $this->read('leading-whitespace.expect'), (string)$this->highlight($this->read('leading-whitespace.source')), pht('Snippets with leading whitespace should be preserved.')); $this->assertEqual( $this->read('no-leading-whitespace.expect'), (string)$this->highlight($this->read('no-leading-whitespace.source')), pht('Snippets with no leading whitespace should be preserved.')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/syntax/highlighter/__tests__/PhutilPHPFragmentLexerHighlighterTestCase.php
src/infrastructure/markup/syntax/highlighter/__tests__/PhutilPHPFragmentLexerHighlighterTestCase.php
<?php final class PhutilPHPFragmentLexerHighlighterTestCase extends PhutilTestCase { public function testLexer() { $highlighter = new PhutilLexerSyntaxHighlighter(); $highlighter->setConfig('language', 'php'); $highlighter->setConfig('lexer', new PhutilPHPFragmentLexer()); $path = dirname(__FILE__).'/phpfragment/'; foreach (Filesystem::listDirectory($path, $include_hidden = false) as $f) { if (preg_match('/.test$/', $f)) { $expect = preg_replace('/.test$/', '.expect', $f); $source = Filesystem::readFile($path.'/'.$f); $this->assertEqual( Filesystem::readFile($path.'/'.$expect), (string)$highlighter->getHighlightFuture($source)->resolve(), $f); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false